View Source ExCurl.Client behaviour (ex_curl v0.3.0)
A helper to create HTTP Clients based on ExCurl that can share common options.
Example HTTP Client
You can use ExCurl.Client
on any module to provide HTTP Client functionality and share default options. Below is an example based on the great
Tesla documentation:
defmodule GitHubClient do
use ExCurl.Client, defaults: [base_url: "https://api.github.com", headers: %{"Authorization" => "Bearer some-secret-token"}]
def user_repos(username), do: get("/users/#{username}/repos")
end
We can then use this client with the shared defaults and custom functions:
# A custom GET request using our default base_url and headers
GitHubClient.get("/users/danielrudn")
# Our custom function, requiring only a username
GitHubClient.user_repos("danielrudn")
Response Handling
You may define an optional handle_response/1
callback to transform a response after a successful request.
A common example would be parsing a JSON string into a map. Below we have the same GitHub
client as above
but we also parse the JSON response if possible using the handle_response/1
callback:
defmodule GitHubClient do
use ExCurl.Client, defaults: [base_url: "https://api.github.com", headers: %{"Authorization" => "Bearer some-secret-token"}]
def handle_response(%ExCurl.Response{body: body}) do
case Jason.decode(body) do
{:ok, decoded_body} -> decoded_body
_ -> body
end
end
def user_repos(username), do: get("/users/#{username}/repos")
end
Options
All of the Shared Options from ExCurl are available. There are also the following additional options:
base_url
- The base URL used for all requests by this client module
Summary
Callbacks
See Response Handling for usage and examples.