Usage
Setup
First of all, we need to install tesla_keys
and all dependencies to work with tesla
:
Mix.install([:tesla, :jason, {:tesla_keys, "~> 0.1.3"}])
Using
Let's create an HTTP client to consume the {JSON} Placeholder
fake API. To learn more about it, see the guide.
defmodule Client do
use Tesla
plug Tesla.Middleware.BaseUrl, "https://jsonplaceholder.typicode.com/"
# middleware for remapping request and response body keys
plug TeslaKeys.Middleware.Remapper, keys: [{"body", "content"}]
# middleware for case conversion of the request and response body keys
plug TeslaKeys.Middleware.Case
plug Tesla.Middleware.Logger
plug Tesla.Middleware.PathParams
plug Tesla.Middleware.JSON
def list_posts() do
get("/posts")
end
def update_post(id, body) do
params = [id: id]
put("/posts/:id", body, opts: [path_params: params])
end
end
In the example above, the {JSON} Placeholder
expects the post body to have the following structure:
{
"id": 1,
"title": "...",
"body": "...",
"userId": 1
}
But when we use the TeslaKeys plugs to handle our request and response, we make some changes to the body data along the way, getting the following structure relative to the previous one:
%{
"id" => 1,
"title" => "...",
"content" => "...",
"user_id" => 1
}
That way, when we use TeslaKeys.Middleware.Remapper
we are remapping the body
key to content
and when we use TeslaKeys.Middleware.Case
, we are doing the case conversion.
params = %{"title" => "foo", "content" => "bar", "user_id" => 1}
with {:ok, %{body: body}} <- Client.update_post(1, params) do
body
end
When running the request above, we noticed that to satisfy the structure expected by the API, the request was sent as:
%{"body" => "bar", "title" => "foo", "userId" => 1}
and it was responded by it as:
%{"body" => "bar", "id" => 1, "title" => "foo", "userId" => 1}
but we got the desired result:
%{"content" => "bar", "id" => 1, "title" => "foo", "user_id" => 1}