Composable APIs with Elixir pipes
Wednesday, 7 September 2016 · 7 min read · elixirA rockstar developer, climbing out of the mess that is your library.
Taking lessons from Plug, Ecto, and Swoosh let’s examine how these libraries create composable and intuitive APIs like so:
Background
Because Elixir is immutable, libraries often feature some kind of model object (usually a struct
) that gets passed around throughout the library. Examples include Plug.Conn
and Ecto.Query
.
These model objects are used in methods that look like this:
For example, the Plug.Conn
model struct
has the following fields:
Wow! That’s a lot of fields! How on earth can a developer interact with an object of this complexity?
Naturally, we don’t expect anyone to be able (or want) to construct a valid payload of this caliber. Instead, as library authors we can provide a set of intuitive interfaces to interact with this gigantic struct
.
By providing a set of methods to interact with the underlying struct
, libraries ensure that each
update made by the user obeys contracts and passes validations that need to be enforced.
Example
Let’s look at one such method. Below is Plug
’s put_resp_content_type
:
For your reference, here’s how put_resp_content_type
is used:
Here’s a simplified version of put_resp_content_type
that’s a bit easier on the eyes:
In essence, methods like put_resp_content_type
and order_by
does the following things:
- First, it validates the user
input
, - transforms the user
input
to follow some desired structure or formatting, - inserts the transformed
input
into thestruct
, and finally - returns the new, updated
struct
All of the above steps can occur without users needing to know the nitty-gritty implementation details beyond the method’s public signature.
In addition, by defining multiple methods you can create composable functions that is more idiomatic Elixir, due the prevalence of the pipe operator in the language.
In Closing
Many Elixir libraries such as Plug
and Ecto
provide functions that act as their public API, shielding users from the complexity underneath. This is a much better approach than having users build the model struct themselves (and inevitably screw up!)
📬 Get updates straight to your inbox.
Subscribe to my newsletter so you don't miss new content.