View Source Tesla

Test Hex.pm Hexdocs.pm Hex.pm Hex.pm codecov

Tesla is an HTTP client that leverages middleware to streamline HTTP requests and responses over a common interface for various adapters.

It simplifies HTTP communication by providing a flexible and composable middleware stack. Developers can easily build custom API clients by stacking middleware components that handle tasks like authentication, logging, and retries. Tesla supports multiple HTTP adapters such as Mint, Finch, Hackney, etc.

Tesla is ideal for developers who need a flexible and efficient HTTP client. Its ability to swap out HTTP adapters and create custom middleware pipelines empowers you to make different architectural decisions and build tools tailored to your application's needs with minimal effort.

Inspired by Faraday from Ruby.

Getting started

Add :tesla as dependency in mix.exs:

defp deps do
  [
     # or latest version
    {:tesla, "~> 1.11"},
    # optional, required by JSON middleware
    {:jason, "~> 1.4"},
    # optional, required by Mint adapter, recommended
    {:mint, "~> 1.0"}
  ]
end

:httpc as default Adapter

The default adapter is erlang's built-in httpc, primarily to avoid additional dependencies when using Tesla in a new project. But it is not recommended to use it in production environment as it does not validate SSL certificates among other issues. Instead, consider using Mint, Finch, or Hackney adapters. We believe that such security issues should be addressed by :httpc itself and we are not planning to fix them in Tesla due to backward compatibility.

Configure default adapter in config/config.exs.

# config/config.exs

# Make sure to install `mint` package as well, recommended
config :tesla, adapter: Tesla.Adapter.Mint

To make a simple GET request, run iex -S mix and execute:

iex> Tesla.get!("https://httpbin.org/get").status
# => 200

That will not include any middleware and will use the global default adapter. Create a client to compose middleware and reuse it across requests.

iex> client = Tesla.client([
...>  {Tesla.Middleware.BaseUrl, "https://httpbin.org/"},
...>  Tesla.Middleware.JSON,
...> ])

iex> Tesla.get!(client, "/json").body
# => %{"slideshow" => ...}

Lastly, you can enforce the adapter to be used by a specific client:

iex> client = Tesla.client([], {Tesla.Adapter.Hackney, pool: :my_pool})

Happy hacking!

What to do next?

Check out the following sections to learn more about Tesla:

Explanations

Howtos

Migrations

References

Middleware

Tesla is built around the concept of composable middlewares.

Formats
Auth
Error handling

Adapters

Tesla supports multiple HTTP adapter that do the actual HTTP request processing.

Sponsors