View Source ExCurl.Client behaviour (ex_curl v0.2.1)

A helper to create HTTP Clients based on ExCurl that can share common options.

example-http-client

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: %{"authentication" => "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

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: %{"authentication" => "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

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

Link to this section Summary

Link to this section Callbacks

Link to this callback

handle_response(response)

View Source (optional)
@callback handle_response(
  response :: %ExCurl.Response{
    appconnect_time: term(),
    body: term(),
    connect_time: term(),
    headers: term(),
    metrics_returned: term(),
    namelookup_time: term(),
    pretransfer_time: term(),
    starttransfer_time: term(),
    status_code: term(),
    total_time: term()
  }
) :: any()

See Response Handling for usage and examples.