Elixir:
Sending an HTTP request
How to:
Use Elixir’s HTTPoison
library. It’s neat, simple, and gets the job done.
- Add HTTPoison to your project’s
mix.exs
:
defp deps do
[
{:httpoison, "~> 1.8"}
]
end
Run
mix deps.get
in your terminal to fetch the dependency.Now you’re set to send a GET request:
case HTTPoison.get("https://jsonplaceholder.typicode.com/posts/1") do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
IO.inspect(body) # you've got your data!
{:error, %HTTPoison.Error{reason: reason}} ->
IO.inspect(reason) # handle error
end
Sample output: a JSON string of post data from the placeholder API.
Deep Dive
Historically, you’d use :httpc
that comes with Erlang/OTP or Elixir’s HTTPotion
. HTTPoison is more popular now, with cleaner syntax and built upon Hackney, a robust HTTP client for Erlang.
Alternatives to HTTPoison include Tesla – a flexible HTTP client with middleware support, and Mint – a shiny, low-level HTTP client.
Implementation wise, these libraries handle connection pooling, SSL, and keep-alive, tricky stuff that’s essential for efficient HTTP requests. They act like friendly librarians who handle the nitty-gritty, so you don’t have to crawl through the stacks yourself.
See Also
- HTTPoison GitHub – for all the details and updates.
- HexDocs for HTTPoison – the place for comprehensive documentation.
- Elixir Forum – to chat with the community.