### Example HEAD Request Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Demonstrates a successful HEAD request to an example URL. ```elixir HTTPoison.head("https://example.com") {:ok, %HTTPoison.Response{status_code: 200, body: ""}} ``` -------------------------------- ### Example OPTIONS Request Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Demonstrates an OPTIONS request to an example API endpoint. ```elixir HTTPoison.options("https://api.example.com") {:ok, %HTTPoison.Response{status_code: 200, ...}} ``` -------------------------------- ### HTTPoison Request Example Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/types.md Demonstrates how to make a GET request with custom options for timeout, receive timeout, SSL versions, and redirect handling. ```elixir HTTPoison.get( "https://api.example.com/data", [], timeout: 10000, recv_timeout: 5000, ssl: [{:versions, [:'tlsv1.2']}], follow_redirect: true, max_redirect: 10 ) ``` -------------------------------- ### Start HTTPoison Client and Make a GET Request Source: https://github.com/edgurgel/httpoison/blob/main/README.md Starts the HTTPoison client and makes a GET request to a specified URL. Handles successful responses and connection errors. ```elixir iex> HTTPoison.start iex> HTTPoison.get! "https://postman-echo.com/get" %HTTPoison.Response{ status_code: 200, body: "{\n \"args\": {},\n \"headers\": {\n \"x-forwarded-proto\": \"https\",\n \"x-forwarded-port\": \"443\",\n \"host\": \"postman-echo.com\",\n \"x-amzn-trace-id\": \"Root=1-644624fb-769bca0458e739dc07f6b630\",\n \"user-agent\": \"hackney/1.18.1\"\n },\n \"url\": \"https://postman-echo.com/get\"\n}", headers: [ ... ] } iex> HTTPoison.get! "http://localhost:1" ** (HTTPoison.Error) :econnrefused iex> HTTPoison.get "http://localhost:1" {:error, %HTTPoison.Error{id: nil, reason: :econnrefused}} ``` -------------------------------- ### Start HTTPoison Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Starts HTTPoison and its dependencies. Returns {:ok, [atom]} on success or {:error, term} on failure. ```elixir HTTPoison.start() {:ok, [:httpoison, :hackney]} ``` -------------------------------- ### Complete Example - Custom API Client Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison-base.md This example demonstrates how to create a custom API client by defining a module that uses HTTPoison.Base and overrides its callback functions. ```APIDOC ## Complete Example This example demonstrates how to create a custom API client by defining a module that uses `HTTPoison.Base` and overrides its callback functions. ```elixir defmodule MyAPI do use HTTPoison.Base @base_url "https://api.example.com" @default_timeout 10000 def process_request_url(url) do @base_url <> url end def process_request_headers(headers) do headers |> Enum.into([]) |> Keyword.put_new("User-Agent", "MyApp/1.0") |> Keyword.put_new("Accept", "application/json") end def process_request_body(body) when is_map(body) do Jason.encode!(body) end def process_request_body(body), do: body def process_request_options(options) do Keyword.put_new(options, :recv_timeout, @default_timeout) end def process_response_body(body) do Jason.decode!(body) rescue _ -> body end def process_response_status_code(code) do case code do 200 -> :ok 201 -> :created 404 -> :not_found 500 -> :server_error _ -> code end end end # Usage {:ok, response} = MyAPI.post("/users", %{"name" => "John", "email" => "john@example.com"}) response.status_code # => :created response.body # => %{"id" => 1, "name" => "John", "email" => "john@example.com"} ``` ``` -------------------------------- ### Interact with GitHub API Client Source: https://github.com/edgurgel/httpoison/blob/main/README.md Example of starting and making a GET request using the custom GitHub API client. It retrieves the number of public repositories for a given user. ```elixir iex> GitHub.start iex> GitHub.get!("/users/myfreeweb").body[:public_repos] 37 ``` -------------------------------- ### HTTPoison.start/0 Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Starts HTTPoison and its dependencies. This function is necessary to initialize the library before making any HTTP requests. ```APIDOC ## HTTPoison.start/0 ### Description Starts HTTPoison and its dependencies. ### Method N/A (Function Call) ### Parameters #### None ### Returns `{:ok, [atom]}` on success, `{:error, term}` on failure. The list contains started applications. ### Example ```elixir HTTPoison.start() {:ok, [:httpoison, :hackney]} ``` ``` -------------------------------- ### Basic GET Request Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/INDEX.md Demonstrates how to perform a simple GET request to a given URL and receive the response. ```APIDOC ## Basic GET Request ### Description Demonstrates how to perform a simple GET request to a given URL and receive the response. ### Method GET ### Endpoint `https://api.example.com/users` ### Request Example ```elixir HTTPoison.get("https://api.example.com/users") # => {:ok, %HTTPoison.Response{status_code: 200, body: "..."}} ``` ``` -------------------------------- ### HTTPoison.AsyncEnd Example Usage Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/response-structures.md An example demonstrating how to receive and process an AsyncEnd message, typically used to detect the completion of a stream. ```elixir receive do %HTTPoison.AsyncEnd{id: id} -> IO.puts("Stream complete") end ``` -------------------------------- ### Complete HTTPoison.Base Example Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison-base.md A full example demonstrating how to implement a custom API client using HTTPoison.Base. This includes custom processing for request URLs, headers, bodies, options, and response bodies and status codes. ```elixir defmodule MyAPI do use HTTPoison.Base @base_url "https://api.example.com" @default_timeout 10000 def process_request_url(url) do @base_url <> url end def process_request_headers(headers) do headers |> Enum.into([]) |> Keyword.put_new("User-Agent", "MyApp/1.0") |> Keyword.put_new("Accept", "application/json") end def process_request_body(body) when is_map(body) do Jason.encode!(body) end def process_request_body(body), do: body def process_request_options(options) do Keyword.put_new(options, :recv_timeout, @default_timeout) end def process_response_body(body) do Jason.decode!(body) rescue _ -> body end def process_response_status_code(code) do case code do 200 -> :ok 201 -> :created 404 -> :not_found 500 -> :server_error _ -> code end end end # Usage {:ok, response} = MyAPI.post("/users", %{"name" => "John", "email" => "john@example.com"}) response.status_code # => :created response.body # => %{"id" => 1, "name" => "John", "email" => "john@example.com"} ``` -------------------------------- ### Configure SSL and Receive Timeout for GET Request Source: https://github.com/edgurgel/httpoison/blob/main/README.md Shows how to configure SSL options and set a receive timeout for a GET request, useful for APIs requiring bearer tokens. ```elixir token = "some_token_from_another_request" url = "https://example.com/api/endpoint_that_needs_a_bearer_token" headers = ["Authorization": "Bearer #{token}", "Accept": "Application/json; Charset=utf-8"] options = [ssl: [{:versions, [:'tlsv1.2']}], recv_timeout: 500] {:ok, response} = HTTPoison.get(url, headers, options) ``` -------------------------------- ### Configure TLS Versions Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Use the `ssl` option to specify allowed TLS versions. This example requires TLS 1.2 or higher. ```elixir HTTPoison.get( "https://api.example.com", [], ssl: [versions: [:'tlsv1.2', :'tlsv1.3']] ) ``` -------------------------------- ### Complete HTTPoison Request Options Example Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Demonstrates a POST request with extensive options including timeouts, SSL configuration, redirect handling, proxy settings, and Hackney pool configuration. ```elixir HTTPoison.post( "https://api.example.com/upload", {:multipart, [...]}, [{"Content-Type", "multipart/form-data"}], [ # Timeouts timeout: 30000, recv_timeout: 60000, # SSL ssl: [ versions: [:'tlsv1.2', :'tlsv1.3'], certfile: "client.crt", keyfile: "client.key" ], # Redirect follow_redirect: true, max_redirect: 5, # Proxy proxy: "http://proxy.internal:8080", proxy_auth: {"proxyuser", "proxypass"}, # Response max_body_length: 5_000_000, # Hackney hackney: [pool: :api_pool] ] ) ``` -------------------------------- ### Perform Async HTTP GET Request Source: https://github.com/edgurgel/httpoison/blob/main/README.md Initiates an asynchronous GET request to the GitHub homepage and streams the response to the current process. Be cautious as this can flood the receiver with messages. ```elixir iex> HTTPoison.get! "https://github.com/", %{}, stream_to: self %HTTPoison.AsyncResponse{id: #Reference<0.0.0.1654>} iex> flush %HTTPoison.AsyncStatus{code: 200, id: #Reference<0.0.0.1654>} %HTTPoison.AsyncHeaders{headers: %{"Connection" => "keep-alive", ...}, id: #Reference<0.0.0.1654>} %HTTPoison.AsyncChunk{chunk: "...", id: #Reference<0.0.0.1654>} %HTTPoison.AsyncEnd{id: #Reference<0.0.0.1654>} :ok ``` -------------------------------- ### Basic GET Request Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/INDEX.md Perform a basic GET request to a specified URL. This function returns an {:ok, %HTTPoison.Response{}} tuple on success. ```elixir HTTPoison.get("https://api.example.com/users") # => {:ok, %HTTPoison.Response{status_code: 200, body: "..."}} ``` -------------------------------- ### Proxy Configuration in HTTPoison Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/errors.md Example of configuring proxy settings for HTTP requests. Common failures include connection refused and timeouts. ```elixir HTTPoison.get( url, [], proxy: "http://proxy.example.com:8080", proxy_auth: {"user", "password"} ) ``` -------------------------------- ### Make a GET Request with HTTPoison Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Issues a GET request to a URL. Handles optional headers and request options. Returns {:ok, Response.t() | AsyncResponse.t()} or {:error, Error.t()}. ```elixir HTTPoison.get("https://api.github.com") {:ok, %HTTPoison.Response{status_code: 200, body: "..."}} ``` ```elixir HTTPoison.get("https://api.github.com/users/octocat", [{"Accept", "application/json"}]) {:ok, %HTTPoison.Response{...}} ``` ```elixir HTTPoison.get("https://api.github.com", [], recv_timeout: 10000) {:ok, %HTTPoison.Response{...}} ``` -------------------------------- ### HTTPoison.get with options Source: https://github.com/edgurgel/httpoison/blob/main/README.md Makes a GET request with custom options, such as headers and SSL configurations. ```APIDOC ## GET / ### Description Makes a GET request to a specified URL with custom headers and request options. This is useful for authenticated requests or fine-tuning connection parameters. ### Method GET ### Endpoint [URL] ### Parameters #### Path Parameters None explicitly listed for this function signature, but URL is required. #### Query Parameters None explicitly listed. #### Request Body None. #### Options - **headers** (list of tuples): Custom headers to include in the request. - **options** (keyword list): A list of options to configure the request. Supported options include: - `:ssl`: Options for the SSL module (e.g., `[{:versions, [:'tlsv1.2']}]`). - `:recv_timeout`: Timeout in milliseconds for receiving the response (default: 5000ms). ### Request Example ```elixir token = "some_token_from_another_request" url = "https://example.com/api/endpoint_that_needs_a_bearer_token" headers = [{"Authorization", "Bearer #{token}"}, {"Accept", "Application/json; Charset=utf-8"}] options = [ssl: [{:versions, [:'tlsv1.2']}], recv_timeout: 500] HTTPoison.get(url, headers, options) ``` ### Response Returns `{:ok, response}` on success or `{:error, reason}` on failure. #### Success Response (200) `HTTPoison.Response` struct containing status code, body, and headers. #### Response Example ```elixir {:ok, response} ``` ``` -------------------------------- ### Install HTTPoison Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/README.md Add HTTPoison to your project's dependencies. Requires Elixir 1.17+ and Erlang/OTP 27+. ```elixir def deps do [ {:httpoison, "~> 3.0"} ] end ``` -------------------------------- ### HTTPoison.Error String Conversion Examples Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/errors.md Illustrates how HTTPoison.Error exceptions are converted to strings, showing the difference in output for synchronous and asynchronous errors. ```elixir {:error, %HTTPoison.Error{reason: :econnrefused}} # When converted to string: ":econnrefused" {:error, %HTTPoison.Error{reason: :timeout, id: #Reference<0.0.0.1>}} # When converted to string: "[Reference: #Reference<0.0.0.1>] - :timeout" ``` -------------------------------- ### HTTPoison.get! Source: https://github.com/edgurgel/httpoison/blob/main/README.md Makes a GET request and returns the response body. Raises an error if the request fails. ```APIDOC ## GET / ### Description Makes a GET request to the specified URL and returns the response body. This function will raise an exception if the request fails. ### Method GET ### Endpoint [URL] ### Parameters None explicitly listed for this function signature, but URL is required. ### Request Example ```elixir HTTPoison.get! "https://postman-echo.com/get" ``` ### Response Returns the response body upon success. Raises `HTTPoison.Error` on failure. #### Success Response `HTTPoison.Response` struct containing status code, body, and headers. #### Response Example ```elixir %HTTPoison.Response{ status_code: 200, body: "{\n \"args\": {},\n \"headers\": {\n \"x-forwarded-proto\": \"https\",\n \"x-forwarded-port\": \"443\",\n \"host\": \"postman-echo.com\",\n \"x-amzn-trace-id\": \"Root=1-644624fb-769bca0458e739dc07f6b630\",\n \"user-agent\": \"hackney/1.18.1\"\n },\n \"url\": \"https://postman-echo.com/get\"\n}", headers: [ ... ] } ``` ``` -------------------------------- ### Make a GET Request (Raising Exception) with HTTPoison Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Issues a GET request, raising an HTTPoison.Error exception on failure. Returns Response.t() or AsyncResponse.t() on success. ```elixir HTTPoison.get!("https://api.github.com") %HTTPoison.Response{status_code: 200, body: "..."} ``` -------------------------------- ### Basic GET Request Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/README.md Perform a simple GET request to a specified URL. The response includes the status code, body, and headers. ```elixir HTTPoison.get("https://api.example.com/users") # => {:ok, %HTTPoison.Response{status_code: 200, body: "...", headers: [...]}} ``` -------------------------------- ### HTTPoison.get Source: https://github.com/edgurgel/httpoison/blob/main/README.md Makes a GET request and returns a tuple with the result. Returns {:ok, response} on success or {:error, reason} on failure. ```APIDOC ## GET / ### Description Makes a GET request to the specified URL and returns a tuple indicating success or failure. This function does not raise exceptions on failure. ### Method GET ### Endpoint [URL] ### Parameters #### Path Parameters None explicitly listed for this function signature, but URL is required. #### Query Parameters None explicitly listed. #### Request Body None. ### Request Example ```elixir HTTPoison.get "http://localhost:1" ``` ### Response Returns `{:ok, response}` on success or `{:error, reason}` on failure. #### Success Response (200) `HTTPoison.Response` struct containing status code, body, and headers. #### Response Example ```elixir {:ok, %HTTPoison.Response{status_code: 200, body: body, headers: headers}} ``` #### Error Response `{:error, %HTTPoison.Error{reason: reason}}` #### Error Response Example ```elixir {:error, %HTTPoison.Error{id: nil, reason: :econnrefused}} ``` ``` -------------------------------- ### Define GitHub API Client with HTTPoison.Base Source: https://github.com/edgurgel/httpoison/blob/main/README.md Wrap HTTPoison.Base to create a custom API client. This example defines a GitHub API client that processes request URLs and decodes JSON responses. ```elixir defmodule GitHub do use HTTPoison.Base @expected_fields ~w( login id avatar_url gravatar_id url html_url followers_url following_url gists_url starred_url subscriptions_url organizations_url repos_url events_url received_events_url type site_admin name company blog location email hireable bio public_repos public_gists followers following created_at updated_at ) def process_request_url(url) do "https://api.github.com" <> url end def process_response_body(body) do body |> Poison.decode! |> Map.take(@expected_fields) |> Enum.map(fn({k, v}) -> {String.to_atom(k), v} end) end end ``` -------------------------------- ### Explicitly Create a Connection Pool Source: https://github.com/edgurgel/httpoison/blob/main/README.md Create a pool manually with specific configuration options, such as timeout and maximum connections, when your application starts. The timeout defines how long a connection is kept alive in the pool, and max_connections sets the pool's size. ```elixir :ok = :hackney_pool.start_pool(:first_pool, [timeout: 15000, max_connections: 100]) ``` -------------------------------- ### HTTPoison.get/1, HTTPoison.get/2, HTTPoison.get/3 Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Issues a GET request to the specified URL. Supports custom headers and request options. ```APIDOC ## HTTPoison.get/1, HTTPoison.get/2, HTTPoison.get/3 ### Description Issues a GET request to the given URL. Supports custom headers and request options. ### Method GET (HTTP) ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Function Parameters - **url** (`binary | any`) - Required - Target URL as a binary string or charlist. - **headers** (`[{atom, binary} | {binary, binary}] | %{binary => binary} | any`) - Optional - HTTP headers. - **options** (`keyword | any`) - Optional - Request options (timeout, ssl, etc.). ### Returns `{:ok, Response.t() | AsyncResponse.t()}` on success, `{:error, Error.t()}` on failure. ### Example ```elixir HTTPoison.get("https://api.github.com") {:ok, %HTTPoison.Response{status_code: 200, body: "..."}} HTTPoison.get("https://api.github.com/users/octocat", [{"Accept", "application/json"}]) {:ok, %HTTPoison.Response{...}} HTTPoison.get("https://api.github.com", [], recv_timeout: 10000) {:ok, %HTTPoison.Response{...}} ``` ``` -------------------------------- ### HTTPoison.get!/1, HTTPoison.get!/2, HTTPoison.get!/3 Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Issues a GET request, raising an exception if the request fails. This is a convenience function for synchronous error handling. ```APIDOC ## HTTPoison.get!/1, HTTPoison.get!/2, HTTPoison.get!/3 ### Description Issues a GET request, raising an exception on failure. This is a convenience function for synchronous error handling. ### Method GET (HTTP) ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Function Parameters - **url** (`binary | any`) - Required - Target URL. - **headers** (`[{atom, binary} | {binary, binary}] | %{binary => binary} | any`) - Optional - HTTP headers. - **options** (`keyword | any`) - Optional - Request options. ### Returns `Response.t() | AsyncResponse.t()` ### Throws `HTTPoison.Error` if the request fails. ### Example ```elixir HTTPoison.get!("https://api.github.com") %HTTPoison.Response{status_code: 200, body: "..."} ``` ``` -------------------------------- ### Configuring Hackney Connection Pools Globally Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Illustrates how to configure hackney connection pools globally in your application configuration or by starting pools with custom settings. ```elixir # config/config.exs config :hackney, use_default_pool: true # Or create pools with custom settings in your supervisor :ok = :hackney_pool.start_pool(:api_pool, [ timeout: 15000, max_connections: 100 ]) ``` -------------------------------- ### Process Request Options with HTTPoison.Base Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison-base.md Customizes request options before the request is issued. The default behavior returns options unchanged. This example ensures a receive timeout is set. ```elixir defmodule API do use HTTPoison.Base def process_request_options(options) do Keyword.put_new(options, :recv_timeout, 10000) end end API.get("/users") # Always sets recv_timeout to 10000 if not provided ``` -------------------------------- ### Streaming Response Handling Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/README.md Process large responses efficiently by streaming them. This example shows how to receive status, headers, chunks, and the end of the stream asynchronously. ```elixir {:ok, async_resp} = HTTPoison.get(url, [], stream_to: self()) receive do %HTTPoison.AsyncStatus{code: code} -> IO.puts("Status: #{code}") %HTTPoison.AsyncHeaders{headers: headers} -> IO.inspect(headers) %HTTPoison.AsyncChunk{chunk: chunk} -> IO.write(chunk) %HTTPoison.AsyncEnd{} -> :ok end ``` -------------------------------- ### Handle Async HTTP Chunks (Automatic Flow Control) Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/response-structures.md Example of receiving and processing AsyncChunk messages for streaming response bodies with automatic flow control. This method can flood the receiver if the data rate is high. ```elixir # Streaming with automatic chunks (floods receiver) {:ok, async_resp} = HTTPoison.get("https://example.com", [], stream_to: self()) defmodule Receiver do def loop do receive do %HTTPoison.AsyncChunk{chunk: chunk} -> IO.write(chunk) loop() %HTTPoison.AsyncEnd{} -> :ok end end end Receiver.loop() ``` -------------------------------- ### Override Default SSL Options Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Completely replace all default SSL options by using the `ssl_override` option instead of `ssl`. This example sets specific TLS versions and disables verification. ```elixir HTTPoison.get( "https://api.example.com", [], ssl_override: [versions: [:'tlsv1.2'], verify: :verify_none] ) ``` -------------------------------- ### Handle Async HTTP Chunks (Manual Flow Control) Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/response-structures.md Example of receiving and processing AsyncChunk messages for streaming response bodies with manual flow control. This method provides control over the data reception rate by calling HTTPoison.stream_next/1. ```elixir # Streaming with manual flow control {:ok, async_resp} = HTTPoison.get("https://example.com", [], stream_to: self(), async: :once) defmodule ManualReceiver do def loop(resp) do receive do %HTTPoison.AsyncChunk{chunk: chunk} -> IO.write(chunk) HTTPoison.stream_next(resp) loop(resp) %HTTPoison.AsyncEnd{} -> :ok end end end ManualReceiver.loop(async_resp) ``` -------------------------------- ### Process Response Chunk for Streaming Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison-base.md Override this function to process each chunk of a streaming response. This example writes each chunk to standard output. The default implementation returns the chunk unchanged. ```elixir defmodule API do use HTTPoison.Base def process_response_chunk(chunk) do IO.write(chunk) chunk end end API.get("https://example.com/large-file", [], stream_to: self()) # Each chunk is written to stdout as received ``` -------------------------------- ### Process Request URL with HTTPoison.Base Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison-base.md Customizes the request URL before it is sent. The default behavior prepends "http://" if no scheme is present. This example prepends a specific base URL for the GitHub API. ```elixir defmodule GitHub do use HTTPoison.Base def process_request_url(url) do "https://api.github.com" <> url end end GitHub.get("/users/octocat") # Requests: https://api.github.com/users/octocat ``` -------------------------------- ### Configure Client Certificates for SSL Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/errors.md Set up client certificates for SSL connections by providing the paths to your client certificate and private key files. ```elixir HTTPoison.get( "https://example.com", [], ssl: [certfile: "client.crt", keyfile: "client.key"] ) ``` -------------------------------- ### Basic Authentication with HTTPoison Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Demonstrates how to perform basic authentication over HTTPS and plain HTTP. For plain HTTP, explicit opt-in is required. ```elixir # Basic auth over HTTPS (recommended) HTTPoison.get( "https://api.example.com/data", [{"Authorization", "Basic " <> Base.encode64("user:pass")}] ) # Basic auth over plain HTTP requires explicit opt-in HTTPoison.get( "http://api.example.com/data", [{"Authorization", "Basic " <> Base.encode64("user:pass")}], insecure_basic_auth: true ) ``` -------------------------------- ### Client Certificate Authentication Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Configure client certificate authentication by providing paths to the client certificate, private key, and CA certificate using `certfile`, `keyfile`, and `cacertfile` options. ```elixir HTTPoison.get( "https://api.example.com", [], ssl: [ certfile: "client.crt", keyfile: "client.key", cacertfile: "ca.pem" ] ) ``` -------------------------------- ### Configure Proxy using Host/Port Tuple Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Use a tuple format to specify the proxy host and port. This offers an alternative to the URL string format for simple HTTP proxies. ```elixir HTTPoison.get(url, [], proxy: {"proxy.example.com", 8080}) ``` -------------------------------- ### Configure SSL for POST Request with Client Certificate Source: https://github.com/edgurgel/httpoison/blob/main/README.md Demonstrates how to configure SSL options for a POST request when the API requires a client certificate. ```elixir url = "https://example.org/api/endpoint_that_needs_client_cert" options = [ssl: [certfile: "certs/client.crt"]] {:ok, response} = HTTPoison.post(url, [], options) ``` -------------------------------- ### Set Connection Timeouts Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Configure TCP/SSL connection and socket receive timeouts in milliseconds. Use :infinity for no timeout. ```elixir HTTPoison.get( "https://api.example.com/data", [], timeout: 10000, recv_timeout: 15000 ) # With infinity (no timeout) HTTPoison.get(url, [], recv_timeout: :infinity) ``` -------------------------------- ### HTTPoison Request with Common Options Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/INDEX.md Demonstrates various configuration options for making an HTTPoison request, including timeouts, streaming, redirects, query parameters, SSL, and proxy settings. Use this for fine-grained control over request behavior. ```elixir HTTPoison.get(url, headers, [ # Timeouts timeout: 8000, # Connection timeout recv_timeout: 5000, # Response timeout # Streaming stream_to: pid, # Async stream to PID async: :once, # Manual flow control # Redirects follow_redirect: true, # Follow redirects max_redirect: 5, # Max redirect hops # Query params params: %{"key" => "value"}, # SSL ssl: [{:versions, [:'tlsv1.2']}], # Proxy proxy: "http://proxy.example.com:8080", proxy_auth: {"user", "pass"}, # Response max_body_length: 5_000_000, # Hackney hackney: [pool: :api_pool] ]) ``` -------------------------------- ### options/1, options/2, options/3 Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Issues an OPTIONS request to the given URL. Returns a tuple indicating success or failure. ```APIDOC ## OPTIONS /:url ### Description Issues an OPTIONS request to the given URL. ### Method OPTIONS ### Endpoint /:url ### Parameters #### Path Parameters - **url** (binary | any) - Required - Target URL #### Query Parameters None #### Headers - **headers** (list({atom, binary} | {binary, binary}) | map(binary => binary) | any) - Optional - HTTP headers #### Options - **options** (keyword | any) - Optional - Request options ### Response #### Success Response - **{:ok, Response.t() | AsyncResponse.t() | MaybeRedirect.t()}** #### Error Response - **{:error, Error.t()}** ### Request Example ```elixir HTTPoison.options("https://api.example.com") {:ok, %HTTPoison.Response{status_code: 200, ...}} ``` ``` -------------------------------- ### Custom Client with Processing Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/INDEX.md Shows how to define a custom HTTP client module that preprocesses URLs and response bodies. ```APIDOC ## Custom Client with Processing ### Description Shows how to define a custom HTTP client module that preprocesses URLs and response bodies. ### Usage Define a module that uses `HTTPoison.Base` and implements `process_request_url/1` and `process_response_body/1`. ### Example ```elixir defmodule GitHub do use HTTPoison.Base def process_request_url(url) do "https://api.github.com" <> url end def process_response_body(body) do Jason.decode!(body) end end GitHub.get("/users/octocat") # => %HTTPoison.Response{body: %{"login" => "octocat", ...}} ``` ``` -------------------------------- ### Configure Redirect Handling Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Automatically follow HTTP redirects by setting :follow_redirect to true and optionally specify the maximum number of redirects with :max_redirect. ```elixir HTTPoison.get( "https://example.com/redirect", [], follow_redirect: true, max_redirect: 10 ) ``` -------------------------------- ### URL Validation Errors in HTTPoison Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/errors.md HTTPoison validates URLs before sending requests. Examples show errors for missing schemes or hosts. ```elixir HTTPoison.get("not-a-valid-url") # {:error, %HTTPoison.Error{reason: "Invalid URL: not-a-valid-url (missing scheme e.g. http:// or https:// or http+unix://)"}} HTTPoison.get("https://") # {:error, %HTTPoison.Error{reason: "Invalid URL: https:// (missing host)"}} ``` -------------------------------- ### Request with Timeouts and SSL Options Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/INDEX.md Shows how to configure request timeouts and SSL options for secure connections. ```APIDOC ## Request with Timeouts and SSL Options ### Description Shows how to configure request timeouts and SSL options for secure connections. ### Parameters #### Query Parameters - `timeout` (integer) - Optional - Connection timeout in milliseconds. - `recv_timeout` (integer) - Optional - Receive timeout in milliseconds. #### Request Body #### SSL Options - `ssl` (list) - Optional - List of SSL options, e.g., `[versions: [:'tlsv1.2', :'tlsv1.3']]`. ### Example ```elixir HTTPoison.get( "https://api.example.com/data", [], timeout: 10000, recv_timeout: 15000, ssl: [versions: [:'tlsv1.2', :'tlsv1.3']] ) ``` ``` -------------------------------- ### Send Cookies in HTTP Request Source: https://github.com/edgurgel/httpoison/blob/main/README.md Shows how to include cookies in an HTTP GET request to postman-echo.com. The cookies are specified within the `hackney` options. ```elixir iex> HTTPoison.get!("https://postman-echo.com/cookies", %{}, hackney: [cookie: ["session=a933ec1dd923b874e691; logged_in=true"]]) %HTTPoison.Response{ status_code: 200, body: "{\n \"cookies\": {\n \"session\": \"a933ec1dd923b874e691\",\n \"logged_in\": \"true\"\n }\n}", headers: [ ... ] } ``` -------------------------------- ### HTTPoison.post with options Source: https://github.com/edgurgel/httpoison/blob/main/README.md Makes a POST request with a given body, headers, and custom options, such as SSL configurations. ```APIDOC ## POST / ### Description Makes a POST request to a specified URL with a request body, headers, and custom options. This is useful for APIs requiring client certificates or specific SSL configurations. ### Method POST ### Endpoint [URL] ### Parameters #### Path Parameters None explicitly listed for this function signature, but URL is required. #### Query Parameters None explicitly listed. #### Request Body - **body** (string): The request body. - **headers** (list of tuples): Custom headers to include in the request. - **options** (keyword list): A list of options to configure the request. Supported options include: - `:ssl`: Options for the SSL module, including `certfile` for client certificates (e.g., `[certfile: "certs/client.crt"]`). ### Request Example ```elixir url = "https://example.org/api/endpoint_that_needs_client_cert" options = [ssl: [certfile: "certs/client.crt"]] HTTPoison.post(url, [], options) ``` ### Response Returns `{:ok, response}` on success or `{:error, reason}` on failure. #### Success Response (200) `HTTPoison.Response` struct containing status code, body, and headers. #### Response Example ```elixir {:ok, response} ``` ``` -------------------------------- ### OPTIONS Request (Returns Tuple) Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Issues an OPTIONS request to the given URL. Returns an {:ok, Response.t()} on success or {:error, Error.t()} on failure. ```elixir def options(url, headers \ [], options \ []) ``` -------------------------------- ### Process Request Body with HTTPoison.Base Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison-base.md Customizes the request body before it is sent. The default behavior returns the body unchanged. This example encodes a map body to JSON. ```elixir defmodule API do use HTTPoison.Base def process_request_body(body) when is_map(body) do Jason.encode!(body) end def process_request_body(body) do body end end API.post("/users", %{"name" => "John"}) # Sends body as JSON: {"name":"John"} ``` -------------------------------- ### options!/1, options!/2, options!/3 Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison.md Issues an OPTIONS request, raising an exception on failure. It targets a specific URL with optional headers and request options. ```APIDOC ## OPTIONS /:url ### Description Issues an OPTIONS request, raising an exception on failure. ### Method OPTIONS ### Endpoint /:url ### Parameters #### Path Parameters - **url** (binary | any) - Required - Target URL #### Query Parameters None #### Headers - **headers** (list({atom, binary} | {binary, binary}) | map(binary => binary) | any) - Optional - HTTP headers #### Options - **options** (keyword | any) - Optional - Request options ### Response #### Success Response - **Response.t() | AsyncResponse.t() | MaybeRedirect.t()** #### Error Response **Throws:** `HTTPoison.Error` on failure. ``` -------------------------------- ### Handle Async HTTP Status Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/response-structures.md Example of receiving and processing an AsyncStatus message from an asynchronous HTTP request. This is useful for confirming the request completed successfully before processing further. ```elixir {:ok, async_resp} = HTTPoison.get("https://example.com", [], stream_to: self()) receive do %HTTPoison.AsyncStatus{id: id, code: code} -> IO.puts("Received status: #{code}") end ``` -------------------------------- ### Streaming with Flow Control Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/INDEX.md Illustrates how to handle streaming responses asynchronously, processing chunks as they arrive and controlling the stream. ```APIDOC ## Streaming with Flow Control ### Description Illustrates how to handle streaming responses asynchronously, processing chunks as they arrive and controlling the stream. ### Usage Initiate a streaming request with `async: :once` and then use `HTTPoison.stream_next/1` to fetch subsequent data chunks. ### Example ```elixir {:ok, async_resp} = HTTPoison.get( "https://example.com/large-file", [], stream_to: self(), async: :once ) receive do %HTTPoison.AsyncStatus{code: code} -> IO.puts("Status: #{code}") HTTPoison.stream_next(async_resp) %HTTPoison.AsyncChunk{chunk: chunk} -> process_chunk(chunk) HTTPoison.stream_next(async_resp) %HTTPoison.AsyncEnd{} -> :ok end ``` ``` -------------------------------- ### HTTPoison Request Query Parameters Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/types.md Illustrates how to specify query parameters for HTTP requests using different data structures like maps, keyword lists, or lists of tuples. These are appended to the URL. ```elixir @type params :: map | keyword | [{binary, binary}] | any ``` ```elixir HTTPoison.get("https://api.example.com/search", [], params: %{"q" => "elixir", "limit" => "10"}) # Results in: https://api.example.com/search?q=elixir&limit=10 ``` ```elixir HTTPoison.get("https://api.example.com/search", [], params: [q: "elixir", limit: "10"]) # Results in: https://api.example.com/search?q=elixir&limit=10 ``` -------------------------------- ### Process Response Body with JSON Decoding Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison-base.md Override this function to process the response body. This example decodes a JSON response body into a map. The default implementation returns the body unchanged. ```elixir defmodule GitHub do use HTTPoison.Base def process_response_body(body) do Jason.decode!(body) end end {:ok, response} = GitHub.get("/users/octocat") # response.body is now a map, not a string response.body["login"] # => "octocat" ``` -------------------------------- ### Configure Proxy with Authentication Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Specify proxy authentication credentials (username and password) alongside the proxy URL. This is for proxies that require basic authentication. ```elixir HTTPoison.get( url, [], proxy: "http://proxy.example.com:8080", proxy_auth: {"proxyuser", "proxypass"} ) ``` -------------------------------- ### Process Request Headers with HTTPoison.Base Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/httpoison-base.md Customizes request headers before they are sent. The default behavior converts map headers to list format. This example demonstrates converting map headers and adding a User-Agent. ```elixir defmodule API do use HTTPoison.Base def process_request_headers(headers) when is_map(headers) do Enum.into(headers, []) end def process_request_headers(headers) do [{"User-Agent", "MyApp/1.0"} | headers] end end ``` -------------------------------- ### Use Custom CA Certificate Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Provide a custom CA certificate file path using the `cacertfile` option within the `ssl` configuration. ```elixir HTTPoison.get( "https://api.example.com", [], ssl: [cacertfile: "/etc/ssl/certs/custom-ca.pem"] ) ``` -------------------------------- ### Handle Async HTTP Headers Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/api-reference/response-structures.md Example of receiving and processing an AsyncHeaders message from an asynchronous HTTP request. This snippet demonstrates how to extract specific headers, like 'content-type', from the received headers list. ```elixir receive do %HTTPoison.AsyncHeaders{id: id, headers: headers} -> content_type = Enum.find_value(headers, fn {"content-type", type} -> type {k, v} when String.downcase(k) == "content-type" -> v _ -> nil end) IO.puts("Content-Type: #{content_type}") end ``` -------------------------------- ### Automatic Streaming of Large Responses Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/advanced-usage.md Use this pattern to automatically receive all chunks of a large response as they arrive. Be aware that this can flood your process mailbox if not handled carefully. This example downloads a large file and saves it locally. ```elixir defmodule LargeFileDownloader do def download(url, output_file) do {:ok, async_resp} = HTTPoison.get(url, [], stream_to: self()) {:ok, file} = File.open(output_file, [:write, :binary]) result = receive_chunks(async_resp.id, file) File.close(file) result end defp receive_chunks(id, file) do receive do %HTTPoison.AsyncStatus{id: ^id, code: 200} -> receive_chunks(id, file) %HTTPoison.AsyncStatus{id: ^id, code: code} -> {:error, "Unexpected status: #{code}"} %HTTPoison.AsyncHeaders{id: ^id} -> receive_chunks(id, file) %HTTPoison.AsyncChunk{id: ^id, chunk: chunk} -> IO.binwrite(file, chunk) receive_chunks(id, file) %HTTPoison.AsyncEnd{id: ^id} -> :ok %HTTPoison.Error{id: ^id, reason: reason} -> {:error, reason} after 30000 -> {:error, :timeout} end end end LargeFileDownloader.download("https://example.com/large-file.bin", "local-file.bin") ``` -------------------------------- ### Implement Rate Limiting with GenServer Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/advanced-usage.md This snippet demonstrates how to control the request rate using a leaky bucket algorithm implemented with GenServer. It ensures a maximum number of requests per second. ```elixir defmodule RateLimiter do use GenServer def start_link(requests_per_second) do GenServer.start_link(__MODULE__, requests_per_second, name: __MODULE__) end def acquire do GenServer.call(__MODULE__, :acquire, :infinity) end def request(method, url, body \ "", headers \ [], options \ []) do acquire() HTTPoison.request(method, url, body, headers, options) end @impl true def init(requests_per_second) do interval_ms = div(1000, requests_per_second) {:ok, %{interval_ms: interval_ms, last_request_at: 0}} end @impl true def handle_call(:acquire, _from, state) do now = System.monotonic_time(:millisecond) time_since_last = now - state.last_request_at if time_since_last < state.interval_ms do wait_time = state.interval_ms - time_since_last Process.sleep(wait_time) end {:reply, :ok, %{state | last_request_at: System.monotonic_time(:millisecond)}} end end RateLimiter.start_link(10) # 10 requests per second RateLimiter.request(:get, "https://api.example.com/endpoint") ``` -------------------------------- ### Streaming Large Responses with Flow Control Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/INDEX.md Handle large responses by streaming them in chunks using asynchronous requests. This example demonstrates how to receive status, chunks, and end signals, and use `HTTPoison.stream_next/1` to control the stream. ```elixir {:ok, async_resp} = HTTPoison.get( "https://example.com/large-file", [], stream_to: self(), async: :once ) receive do %HTTPoison.AsyncStatus{code: code} -> IO.puts("Status: #{code}") HTTPoison.stream_next(async_resp) %HTTPoison.AsyncChunk{chunk: chunk} -> process_chunk(chunk) HTTPoison.stream_next(async_resp) %HTTPoison.AsyncEnd{} -> :ok end ``` -------------------------------- ### Configure Explicit SOCKS5 Proxy with Authentication Source: https://github.com/edgurgel/httpoison/blob/main/_autodocs/configuration.md Configure a SOCKS5 proxy with username and password authentication. This is useful for secure SOCKS5 proxy connections. ```elixir HTTPoison.get( url, [], proxy: {:socks5, "proxy.example.com", 1080}, socks5_user: "username", socks5_pass: "password" ) ```