HTTP.Response (http_fetch v0.2.0)

Represents an HTTP response with status, headers, body, and URL information.

Summary

Functions

Parses the Content-Type header to extract media type and parameters.

Gets a response header value by name (case-insensitive).

Parses the response body as JSON using Elixir's built-in JSON module (available in Elixir 1.18+).

Reads the response body as text.

Types

t()

@type t() :: %HTTP.Response{
  body: String.t(),
  headers: HTTP.Headers.t(),
  status: integer(),
  url: String.t()
}

Functions

content_type(response)

@spec content_type(t()) :: {String.t(), map()}

Parses the Content-Type header to extract media type and parameters.

Examples

iex> response = %HTTP.Response{headers: HTTP.Headers.new([{"Content-Type", "application/json; charset=utf-8"}])}
iex> HTTP.Response.content_type(response)
{"application/json", %{"charset" => "utf-8"}}

iex> response = %HTTP.Response{headers: HTTP.Headers.new([{"Content-Type", "text/plain"}])}
iex> HTTP.Response.content_type(response)
{"text/plain", %{}}

get_header(response, name)

@spec get_header(t(), String.t()) :: String.t() | nil

Gets a response header value by name (case-insensitive).

Examples

iex> response = %HTTP.Response{headers: HTTP.Headers.new([{"Content-Type", "application/json"}])}
iex> HTTP.Response.get_header(response, "content-type")
"application/json"

iex> response = %HTTP.Response{headers: HTTP.Headers.new([{"Content-Type", "application/json"}])}
iex> HTTP.Response.get_header(response, "missing")
nil

json(response)

@spec json(t()) :: {:ok, map() | list()} | {:error, term()}

Parses the response body as JSON using Elixir's built-in JSON module (available in Elixir 1.18+).

Returns:

  • {:ok, map | list} if the body is valid JSON.

  • {:error, reason} if the body cannot be parsed as JSON.

text(response)

@spec text(t()) :: String.t()

Reads the response body as text.