dream_http_client/client
Type-safe HTTP client with recording + streaming support
Gleam doesn’t ship with an HTTPS client, so this module wraps
gun (a high-performance Erlang HTTP/1.1
and HTTP/2 client) and adds a friendly builder API, streaming helpers,
and optional record/playback via dream_http_client/recorder.
Quick Example — blocking request
Call an API with a token 
import dream_http_client/client.{add_header, host, path, port, scheme, send}
import gleam/http
import gleam/result
pub fn call_api(token: String) -> Result(BitArray, client.SendError) {
client.new()
|> scheme(http.Http)
|> host("localhost")
|> port(9876)
|> path("/text")
|> add_header("Authorization", "Bearer " <> token)
|> send()
|> result.map(fn(response) { response.body })
}
Execution modes
You can execute the same ClientRequest in four ways:
- Blocking:
send()returns the full response body. - Pull streaming:
stream_yielder()returns ayielder.Yielderof chunks. - Callback streaming:
start_stream()spawns a stream process and calls your callbacks (on_stream_*) as events arrive. - Message streaming:
stream_to()spawns a stream process that sends typedStreamMessagevalues to a subject, for OTP actors.
The “right” choice is mostly about concurrency:
- Use
send()for normal JSON APIs. - Use
stream_yielder()for scripts/one‑offs where blocking is fine. - Use
start_stream()when you need non‑blocking streaming in OTP code. - Use
stream_to()when an OTP actor must handle the stream as messages.
Recording and playback
Attach a recorder with recorder() to record real HTTP traffic to disk, or
to play back recordings without network calls. All four execution modes
(send(), stream_yielder(), start_stream(), stream_to()) fully
support both recording and playback. In playback mode, a request that no
recording matches fails with NoRecording(method, url, directory, nearest) and is not sent. The error names the nearest recordings and
the parts that differ.
Record a call 
import dream_http_client/client.{host, path, port, recorder, scheme, send}
import dream_http_client/recorder.{directory, mode, start}
import gleam/http
import gleam/result
import gleam/string
pub fn record_call(mocks_directory: String) -> Result(BitArray, String) {
use rec <- result.try(
recorder.new()
|> directory(mocks_directory)
|> mode(recorder.Record)
|> start(),
)
client.new()
|> scheme(http.Http)
|> host("localhost")
|> port(9876)
|> path("/text")
|> recorder(rec)
|> send()
|> result.map(fn(response) { response.body })
|> result.map_error(string.inspect)
}
Inspecting requests
ClientRequest is opaque to keep the public API stable; use the get_*
functions for logging/testing.
Read the target of a request 
import dream_http_client/client.{get_host, get_path, host, path}
pub fn describe_target() -> String {
let request = client.new() |> host("api.example.com") |> path("/users/123")
"Calling: " <> get_host(request) <> get_path(request)
}
Types
HTTP client request configuration
Represents a complete HTTP request with all its components. Use the builder
pattern with functions like host(), path(), method(), etc. to configure
the request, then execute it with send(), stream_yielder(), or
start_stream() depending on whether you want a
blocking, pull-streaming, or callback-streaming API.
Fields
method: The HTTP method (GET, POST, etc.)scheme: The protocol (HTTP or HTTPS)host: The server hostnameport: Optional port number (defaults to 80 for HTTP, 443 for HTTPS)path: The request path (e.g., “/api/users”)query: Optional query string (e.g., “?page=1&limit=10”)headers: List of header name-value pairsbody: The request body as a stringtimeout: Optional timeout in milliseconds (defaults to 30000ms)recorder: Optional recorder for request/response recording and playback
The type is opaque to ensure API stability. Use new with builder functions
to construct requests, and the getter functions to inspect request properties.
pub opaque type ClientRequest
A connection pool of its own for some requests.
Make one with new_pool(), keep it, and give it to requests with
pool(). Requests share connections only with requests that have the
same pool. The pool opens at most its max_connections connections to
each host.
The value is opaque. A pool has one limit, set when it is made, so two requests cannot give the same pool different limits.
Example
Give the model calls their own pool 
import dream_http_client/client
import gleam/option.{type Option}
pub fn model_pool() -> client.ConnectionPool {
client.new_pool(max_connections: 3)
}
pub fn model_request(
pool: client.ConnectionPool,
prompt: String,
) -> client.ClientRequest {
client.new()
|> client.host("api.llm.example")
|> client.path("/v1/chat")
|> client.body(prompt)
|> client.pool(pool)
}
pub fn pool_limit(request: client.ClientRequest) -> Option(Int) {
client.get_pool(request)
|> option.map(client.get_pool_max_connections)
}
pub opaque type ConnectionPool
HTTP header
Represents a single HTTP header with a name and value. Used throughout the module for type-safe header handling.
Fields
name: Header name (e.g., “Content-Type”, “Authorization”)value: Header value (e.g., “application/json”, “Bearer token”)
Usage
Headers are constructed automatically by builder functions like add_header(),
but you’ll work with this type when inspecting headers:
Read the first header 
import dream_http_client/client.{Header}
pub fn first_header(request: client.ClientRequest) -> String {
case client.get_headers(request) {
[Header(name, value), ..] -> name <> ": " <> value
[] -> "No headers"
}
}
Notes
- Header names are case-sensitive as stored, but HTTP treats them case-insensitively
- Duplicate header names are allowed (e.g., multiple Set-Cookie headers)
- Headers are stored in the order they were added
pub type Header {
Header(name: String, value: String)
}
Constructors
-
Header(name: String, value: String)
An HTTP/2 error code, as RFC 9113 section 7 defines them.
A server sends one in a RST_STREAM or a GOAWAY frame to say why it ends a
stream or a connection. StreamReset, Goaway and ConnectionError of
TransportError carry it.
Variants
NoError— No error. A server uses it for a graceful shutdown.ProtocolError— The peer broke the HTTP/2 protocol.InternalError— The peer had an internal error.FlowControlError— The peer broke the flow control rules.SettingsTimeout— A SETTINGS frame got no answer in time.StreamClosed— A frame arrived for a stream that was closed.FrameSizeError— A frame had a size that is not valid.RefusedStream— The server refused the stream before it did any work for it. The request is safe to send again.Cancel— The stream is no longer needed.CompressionError— The header compression state is broken.ConnectError— The connection for a CONNECT request failed.EnhanceYourCalm— The peer makes too much load.InadequateSecurity— The transport does not meet the security needs.Http11Required— The server needs HTTP/1.1 for this request.UnknownErrorCode— A code that is not one of these.nameis the name that gun gives it.
Example
Explain a transport error 
import dream_http_client/client.{
type TransportError, ConnectFailed, Goaway, NoError, RefusedStream,
StreamReset, TimedOut, transport_error_to_string,
}
import gleam/int
pub fn explain(error: TransportError) -> String {
case error {
ConnectFailed(reason: reason) -> "Cannot reach server: " <> reason
TimedOut(timeout_ms: ms) -> "Timed out after " <> int.to_string(ms) <> "ms"
StreamReset(code: RefusedStream, ..) -> "The server refused the request"
Goaway(code: NoError, ..) -> "The server is going away"
_ -> transport_error_to_string(error)
}
}
pub type Http2ErrorCode {
NoError
ProtocolError
InternalError
FlowControlError
SettingsTimeout
StreamClosed
FrameSizeError
RefusedStream
Cancel
CompressionError
ConnectError
EnhanceYourCalm
InadequateSecurity
Http11Required
UnknownErrorCode(name: String)
}
Constructors
-
NoError -
ProtocolError -
InternalError -
FlowControlError -
SettingsTimeout -
StreamClosed -
FrameSizeError -
RefusedStream -
Cancel -
CompressionError -
ConnectError -
EnhanceYourCalm -
InadequateSecurity -
Http11Required -
UnknownErrorCode(name: String)
Complete HTTP response with status code, headers, and body.
Returned by send() for successful HTTP responses (status < 400).
Also available inside ResponseError for HTTP error responses (status >= 400).
Fields
status: HTTP status code (e.g. 200, 301, 404, 500)headers: Response headers asList(Header)— includes Content-Type, Content-Length, Set-Cookie, and any other headers the server sentbody: The complete response body, as the exact bytes the server sent. A body is not always text: it can be an image, a PDF, or text in another encoding. Usebody_text()to read it as a UTF-8 string.
Example
Match on the response 
import dream_http_client/client.{HttpResponse}
import gleam/bit_array
import gleam/int
pub fn describe_response(request: client.ClientRequest) -> String {
case client.send(request) {
Ok(HttpResponse(status: 200, body: body, ..)) ->
"OK: " <> int.to_string(bit_array.byte_size(body)) <> " bytes"
Ok(HttpResponse(status: status, ..)) -> "Status " <> int.to_string(status)
Error(_) -> "Request failed"
}
}
pub type HttpResponse {
HttpResponse(
status: Int,
headers: List(Header),
body: BitArray,
)
}
Constructors
-
HttpResponse(status: Int, headers: List(Header), body: BitArray)
Minimum log level for dream_http_client’s own log output.
Every log line of the client goes through one Erlang module,
dream_http_client_log, and this setting is the OTP logger module level
of that module (logger:set_module_level/2). It changes only the lines of
the client: the primary logger level and the logging of the rest of your
application stay the same.
Variants
LogDebug— Every line. The client writes no debug lines, so this shows the same lines asLogInfo.LogInfo— Info lines and warnings. The info line is[dream_http] connection closed: ..., when a server closes an idle connection.LogWarning— Warnings only (default): a connection that went down while a request was on it, a body that the client cannot decompress, an unknown content encoding, a recorder that does not answer, a recording that cannot be read correctly, and a recorded stream that failed.LogError— Errors only. The client writes no error lines, so this shows nothing.LogNone— No lines.
Example
Show the info lines 
import dream_http_client/client.{LogInfo}
pub fn info_lines() -> Nil {
client.transport_config()
|> client.log_level(LogInfo)
|> client.configure_transport()
}
pub type LogLevel {
LogDebug
LogInfo
LogWarning
LogError
LogNone
}
Constructors
-
LogDebug -
LogInfo -
LogWarning -
LogError -
LogNone
Per-request protocol preference for HTTP connections.
Controls which HTTP protocol version gun negotiates when opening a connection.
The connection manager uses this to set gun’s protocols option and, for TLS
connections, to align ALPN advertisement accordingly.
Variants
-
Http1Only— HTTP/1.1 only. Maps to gunprotocols => [http]. -
Http2Only— HTTP/2 only. For cleartext (TCP) connections this enables h2c “prior knowledge” mode per RFC 7540 Section 3.4 — gun speaks HTTP/2 directly without an upgrade dance. For TLS connections this advertises onlyh2via ALPN. -
Http2Preferred— Prefer HTTP/2, fall back to HTTP/1.1. Maps to gunprotocols => [http2, http]. This is the default for TLS connections (ALPN negotiation). For TCP, this uses the HTTP/1.1 Upgrade mechanism which most servers do not support — useHttp2Onlyfor cleartext HTTP/2 instead.
Example
Use HTTP/2 only 
import dream_http_client/client.{Http2Only}
import gleam/http
pub fn http2_only_request() -> client.ClientRequest {
client.new()
|> client.scheme(http.Http)
|> client.host("internal-service.local")
|> client.protocols(Http2Only)
}
pub type Protocols {
Http1Only
Http2Only
Http2Preferred
}
Constructors
-
Http1Only -
Http2Only -
Http2Preferred
Identifies one stream that stream_to() started
stream_to() returns a RequestId, and every StreamMessage of that
stream carries the same value in its request_id field. Compare the two
with == to tell apart the messages of streams that send to one inbox.
Give it to cancel_stream() to stop the stream.
Notes
- The type is opaque. Only
stream_to()makes aRequestId, and its contents can change in any release. - Two streams never have the same
RequestIdin one VM. ARequestIdmeans nothing in another VM or after a restart.
Example
Match a message to its stream 
import dream_http_client/client
import gleam/erlang/process
import gleam/http
import gleam/result
pub fn first_message_is_ours() -> Result(Bool, String) {
let inbox = process.new_subject()
let request =
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/stream/fast")
use request_id <- result.try(client.stream_to(request, inbox))
let first_message = process.receive(inbox, 5000)
client.cancel_stream(request_id)
case first_message {
// Every message of the stream carries the id that stream_to returned
Ok(message) -> Ok(message.request_id == request_id)
Error(Nil) -> Error("No message within 5 seconds")
}
}
See Also
stream_to(): starts a stream and returns itsRequestIdcancel_stream(): stops the stream of aRequestId
pub opaque type RequestId
Error types returned by send().
Variants
-
ResponseError(response: HttpResponse)— the server responded with a 4xx or 5xx status code. The fullHttpResponseis available with status, headers, and body. The body typically contains error details (e.g. JSON error messages from an API, or HTML error pages). -
RequestError(error: TransportError)— the request could not be completed due to a transport-level failure. Pattern match on theTransportErrorfor the specific cause, or usetransport_error_to_stringfor logging.
Example
Handle every send error 
import dream_http_client/client.{
ConnectFailed, RequestError, ResponseError, transport_error_to_string,
}
import gleam/int
pub fn send_and_describe(request: client.ClientRequest) -> String {
case client.send(request) {
Ok(response) -> "Got " <> int.to_string(response.status)
Error(ResponseError(response: response)) ->
"HTTP " <> int.to_string(response.status)
Error(RequestError(error: ConnectFailed(reason: reason))) ->
"Cannot connect: " <> reason
Error(RequestError(error: error)) ->
"Failed: " <> transport_error_to_string(error)
}
}
pub type SendError {
ResponseError(response: HttpResponse)
RequestError(error: TransportError)
}
Constructors
-
ResponseError(response: HttpResponse) -
RequestError(error: TransportError)
Failure during streaming, distinguishing HTTP errors from transport errors.
When a streaming request (stream_yielder or start_stream) fails, the
failure is either an HTTP-level rejection (the server responded with a
non-2xx status) or a transport-level error (the connection broke).
Variants
-
HttpFailure— The server returned a non-2xx status code before streaming began. The fullHttpResponseis available including status, headers (useful forretry-after,x-request-id), and body. -
TransportFailure— A transport-level error occurred during connection or streaming. SeeTransportErrorfor the specific error variants.
Example
Explain a stream failure 
import dream_http_client/client.{
type StreamFailure, ConnectFailed, HttpFailure, TransportFailure,
transport_error_to_string,
}
import gleam/int
pub fn explain_failure(failure: StreamFailure) -> String {
case failure {
HttpFailure(response: response) -> "HTTP " <> int.to_string(response.status)
TransportFailure(error: ConnectFailed(reason: reason)) ->
"Cannot connect: " <> reason
TransportFailure(error: error) -> transport_error_to_string(error)
}
}
pub type StreamFailure {
HttpFailure(response: HttpResponse)
TransportFailure(error: TransportError)
}
Constructors
-
HttpFailure(response: HttpResponse) -
TransportFailure(error: TransportError)
Handle to a running HTTP stream
Opaque handle returned from start_stream() representing a stream running in
a dedicated BEAM process. Use this handle to control the stream lifecycle.
Lifecycle Management
await_stream(handle)- Wait for stream to completecancel_stream_handle(handle)- Stop the stream earlyis_stream_active(handle)- Check if still running
Process Isolation
Each stream runs in its own BEAM process, which means:
- Multiple streams run concurrently without blocking
- Stream crashes don’t affect your application
- Your process mailbox stays clean (HTTP messages go to stream process)
- Callbacks execute in the stream process, not your process
Example
Wait for a stream 
import dream_http_client/client
import gleam/http
import gleam/result
pub fn run_to_end() -> Result(Bool, String) {
let request =
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/stream/fast")
use stream <- result.map(client.start_stream(request))
// Wait for completion
client.await_stream(stream)
// False: the stream is done
client.is_stream_active(stream)
}
pub opaque type StreamHandle
A message that a stream of stream_to() sends to its inbox
A stream sends its messages to the inbox in this order:
StreamStart: once, when the response headers arriveChunk: zero or more times, one for each part of the body, in orderStreamEndorStreamError: exactly one of them, as the last message
A stream that fails before the response headers arrive, for example
because the connection is refused, sends only one StreamError. After
the last message, or after cancel_stream() returns, the stream sends
nothing more.
Every message carries the RequestId that stream_to() returned, so
message.request_id works on each message.
Example
Handle stream messages in an actor 
fn handle_stream_message(
state: State,
message: StreamMessage,
) -> actor.Next(State, StreamMessage) {
case message {
StreamStart(..) -> actor.continue(state)
Chunk(data: data, ..) ->
actor.continue(State(..state, body: bit_array.append(state.body, data)))
StreamEnd(..) -> {
process.send(state.done, Ok(state.body))
actor.stop()
}
StreamError(error: error, ..) -> {
process.send(state.done, Error(stream_failure_to_string(error)))
actor.stop()
}
}
}
See Also
stream_to(): starts a stream that sends these messagesstream_failure_to_string(): describes the failure of aStreamError
pub type StreamMessage {
StreamStart(request_id: RequestId, headers: List(Header))
Chunk(request_id: RequestId, data: BitArray)
StreamEnd(request_id: RequestId, headers: List(Header))
StreamError(request_id: RequestId, error: StreamFailure)
}
Constructors
-
The response headers arrived. Body chunks can follow.
-
Chunk(request_id: RequestId, data: BitArray)The next part of the response body.
-
The body is complete.
headersholds the trailing headers, and is empty when the response has none. -
StreamError(request_id: RequestId, error: StreamFailure)The stream failed: a non-2xx response (
HttpFailure), or a transport failure such as a refused connection, a dropped connection or a timeout (TransportFailure). No message follows it.
Configuration for the HTTP transport layer
Controls connection pool behavior, gun client options, and log verbosity.
These settings are global and affect all subsequent HTTP requests.
Gun negotiates HTTP/2 automatically for TLS connections via ALPN,
falling back to HTTP/1.1. For cleartext (TCP) connections, the default
is HTTP/1.1 only; use protocols(Http2Only) on ClientRequest for
h2c (HTTP/2 over cleartext) per-request.
Create with transport_config(), configure with builder functions,
and apply with configure_transport().
Example
Configure the pool 
import dream_http_client/client
pub fn configure_pool() -> Nil {
client.transport_config()
|> client.max_connections(200)
|> client.idle_timeout(120_000)
|> client.configure_transport()
}
pub opaque type TransportConfig
Transport-level error from the underlying gun HTTP client.
Each variant preserves ALL structured information that gun provides for that
error class. Use transport_error_to_string for human-readable log output,
or pattern match on variants for programmatic error handling (retry logic,
alerting, circuit breakers).
Variants
-
StreamReset— HTTP/2 RST_STREAM frame. Thecodefield is the HTTP/2 error code (e.g.InternalError,Cancel,RefusedStream,EnhanceYourCalm). Thedescriptionfield is gun’s human-readable explanation. -
Goaway— HTTP/2 GOAWAY frame. The server takes no new requests on the connection. The client sends the request once more on another connection, so this error comes back only when that also fails. Thecodefield is the HTTP/2 error code anddescriptionis gun’s human-readable explanation. -
ConnectionError— Connection-level protocol error. Thecodefield is the HTTP/2 error code anddescriptionis gun’s human-readable explanation. -
RemoteClosed— The remote peer closed the connection without sending an explicit error code. If it closed before the response head, the server can have processed the request. So the client sends a GET, HEAD, OPTIONS, TRACE, PUT or DELETE request once more on another connection, and this error comes back only when that also fails. It sends a POST, PATCH or other request only once (RFC 9110, section 9.2.2). -
TimedOut— No response was received within the configured timeout.timeout_msis the value that was configured. -
ProcessDown— The connection or stream owner process died unexpectedly.reasondescribes why the process exited. -
ConnectFailed— Could not establish a connection to the server. Common causes include connection refused (server not running), DNS resolution failure (NXDOMAIN), and TLS handshake errors. -
Unexpected— An error that doesn’t match any known pattern.rawcontains the Erlang term formatted as a string for debugging. -
NoRecording— The request has a recorder in playback mode, and no recording matches it. The client sends nothing to the network.methodis the method in upper case, for example"GET", andurlis the URL of the request after the recorder’s request transformer: the scheme, the host, the port when the request sets one, the path and the query.directoryis the directory that the recorder searched.nearestholds at most 3 recordings with the same method and path, nearest first: seerecorder.NearestRecordingand the recording guide for the rule.
Example
Explain a transport error 
import dream_http_client/client.{
type TransportError, ConnectFailed, Goaway, NoError, RefusedStream,
StreamReset, TimedOut, transport_error_to_string,
}
import gleam/int
pub fn explain(error: TransportError) -> String {
case error {
ConnectFailed(reason: reason) -> "Cannot reach server: " <> reason
TimedOut(timeout_ms: ms) -> "Timed out after " <> int.to_string(ms) <> "ms"
StreamReset(code: RefusedStream, ..) -> "The server refused the request"
Goaway(code: NoError, ..) -> "The server is going away"
_ -> transport_error_to_string(error)
}
}
pub type TransportError {
StreamReset(code: Http2ErrorCode, description: String)
Goaway(code: Http2ErrorCode, description: String)
ConnectionError(code: Http2ErrorCode, description: String)
RemoteClosed
TimedOut(timeout_ms: Int)
ProcessDown(reason: String)
ConnectFailed(reason: String)
Unexpected(raw: String)
NoRecording(
method: String,
url: String,
directory: String,
nearest: List(recorder.NearestRecording),
)
}
Constructors
-
StreamReset(code: Http2ErrorCode, description: String) -
Goaway(code: Http2ErrorCode, description: String) -
ConnectionError(code: Http2ErrorCode, description: String) -
RemoteClosed -
TimedOut(timeout_ms: Int) -
ProcessDown(reason: String) -
ConnectFailed(reason: String) -
Unexpected(raw: String) -
NoRecording( method: String, url: String, directory: String, nearest: List(recorder.NearestRecording), )
Values
pub fn add_header(
client_request: ClientRequest,
name: String,
value: String,
) -> ClientRequest
Add a header to the request
Adds a single header to the existing headers list without replacing them. The new header is prepended to the list, so it will take precedence if there’s a duplicate header name.
Parameters
client_request: The request to modifyname: The header name (e.g., “Authorization”, “Content-Type”)value: The header value
Returns
A new ClientRequest with the header added.
Example
Add headers one at a time 
import dream_http_client/client
pub fn json_api_request(token: String) -> client.ClientRequest {
client.new()
|> client.add_header("Authorization", "Bearer " <> token)
|> client.add_header("Content-Type", "application/json")
}
pub fn auto_redirect(
client_request: ClientRequest,
enabled: Bool,
) -> ClientRequest
Set whether HTTP redirects are followed automatically
When enabled (default), the client follows 3xx redirects automatically
and returns the final response. When disabled, the 3xx response is
returned as Ok(HttpResponse(...)) with the redirect status code and
Location header visible, allowing manual redirect handling.
Parameters
client_request: The request to modifyenabled: Whether to follow redirects automatically (default: True)
Example
Inspect a redirect 
import dream_http_client/client
import gleam/http
import gleam/result
pub fn redirect_status() -> Result(Int, client.SendError) {
// Disable auto-redirect to inspect the 3xx response
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/redirect/301")
|> client.auto_redirect(False)
|> client.send()
|> result.map(fn(response) { response.status })
}
pub fn await_stream(handle: StreamHandle) -> Nil
Wait for a stream to complete
Blocks until the stream process exits. Use this when you need to wait for the stream to finish before continuing.
Returns Ok(Nil) when stream completes.
For timeout behavior, use cancel_stream_handle() with a timer, or implement your own timeout logic.
Example
Wait for a stream 
import dream_http_client/client
import gleam/http
import gleam/result
pub fn run_to_end() -> Result(Bool, String) {
let request =
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/stream/fast")
use stream <- result.map(client.start_stream(request))
// Wait for completion
client.await_stream(stream)
// False: the stream is done
client.is_stream_active(stream)
}
pub fn body(
client_request: ClientRequest,
body_value: String,
) -> ClientRequest
Set the body for the request
Sets the request body as a string. Typically used for POST, PUT, and PATCH
requests. For JSON, serialize your data first. For a body that is not
text, such as a file, use body_bits().
Parameters
client_request: The request to modifybody_value: The request body as a string
Returns
A new ClientRequest with the body updated.
Example
Send a JSON body 
import dream_http_client/client
import gleam/http
import gleam/json
pub fn create_user_request() -> client.ClientRequest {
let json_body =
json.object([
#("name", json.string("Alice")),
#("email", json.string("alice@example.com")),
])
client.new()
|> client.method(http.Post)
|> client.body(json.to_string(json_body))
}
pub fn body_bits(
client_request: ClientRequest,
body_value: BitArray,
) -> ClientRequest
Set the body for the request as bytes
Sets the request body to the exact bytes of body_value. Use it for a
body that is not text: a file, an image, or text in an encoding that is
not UTF-8. For text, body() is shorter.
Parameters
client_request: The request to modifybody_value: The request body as bytes
Returns
A new ClientRequest with the body updated.
Example
Upload a file 
import dream_http_client/client
import gleam/http
pub fn upload_request(file: BitArray) -> client.ClientRequest {
client.new()
|> client.method(http.Put)
|> client.host("files.example.com")
|> client.path("/reports/2026.pdf")
|> client.add_header("Content-Type", "application/pdf")
|> client.body_bits(file)
}
pub fn body_text(response: HttpResponse) -> Result(String, Nil)
Read the body of a response as text
Parameters
response: The response to read
Returns
Ok(String): The body, when it is valid UTF-8Error(Nil): The body is not valid UTF-8. Readresponse.bodyfor the bytes.
Example
Read the body as text 
import dream_http_client/client
pub fn text_of(response: client.HttpResponse) -> String {
case client.body_text(response) {
Ok(text) -> text
Error(Nil) -> "The body is not text"
}
}
pub fn cancel_stream(request_id: RequestId) -> Nil
Stop a stream that stream_to() started
Stops the stream process of request_id and waits until it has stopped.
The request is cancelled: over HTTP/2 the server gets a stream reset,
and over HTTP/1.1 the pooled connection reads and drops the rest of the
body before it can serve another request. When cancel_stream()
returns, the stream sends no more messages to its inbox. Messages that the stream sent before the cancel can still wait in
the mailbox of the process that owns the inbox.
A cancel of a stream that has already ended, or a second cancel of the
same stream, does nothing and returns Nil. Any process can cancel a
stream, not only its owner. In record mode, a cancelled stream is not
saved.
Parameters
request_id: TheRequestIdthatstream_to()returned
Returns
Nil, after the stream has stopped.
Example
Cancel a stream 
import dream_http_client/client
import gleam/erlang/process
import gleam/http
import gleam/result
pub fn start_then_cancel() -> Result(Nil, String) {
let inbox = process.new_subject()
let request =
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/stream/fast")
use request_id <- result.map(client.stream_to(request, inbox))
// Later: no message of this stream comes after the cancel
client.cancel_stream(request_id)
}
See Also
stream_to(): starts a stream and returns itsRequestIdcancel_stream_handle(): stops a stream ofstart_stream()
pub fn cancel_stream_handle(handle: StreamHandle) -> Nil
Cancel a stream started with start_stream()
Stops the stream process and cancels the underlying HTTP request. Safe to call multiple times on the same handle.
Example
Cancel a stream 
import dream_http_client/client
import gleam/http
import gleam/result
pub fn start_then_cancel() -> Result(Nil, String) {
let request =
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/stream/slow")
use stream <- result.map(client.start_stream(request))
// Later:
client.cancel_stream_handle(stream)
}
pub fn certificate_authority_file(
client_request: ClientRequest,
path: String,
) -> ClientRequest
Trust only the certificate authorities in a PEM file for this request
Over HTTPS, the client checks the server’s certificate against the system
certificate authorities. With this setting, the request trusts the
certificate authorities in path in their place, the same as
curl --cacert. Use it for services with a private certificate
authority, and for test servers with their own certificate.
This setting wins over default_certificate_authority_file(). Requests
with different settings never share a connection. Plain HTTP requests
ignore it.
If the file cannot be read, the request fails with a transport error.
Example
Read the request settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn internal_request() -> client.ClientRequest {
client.new()
|> client.host("internal.example.com")
|> client.certificate_authority_file("certs/internal-ca.pem")
|> client.connect_timeout(2000)
|> client.auto_redirect(False)
}
pub fn request_settings(
request: client.ClientRequest,
) -> #(Option(String), Option(Int), Option(Bool)) {
#(
client.get_certificate_authority_file(request),
client.get_connect_timeout(request),
client.get_auto_redirect(request),
)
}
pub fn closing_timeout(
config: TransportConfig,
ms: Int,
) -> TransportConfig
Set graceful shutdown timeout in milliseconds
How long to wait for in-flight requests to complete when closing a connection.
Parameters
config: The transport config to modifyms: Shutdown wait in milliseconds (default: 15_000)
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn configure_transport(config: TransportConfig) -> Nil
Apply transport configuration to the HTTP client
Stores transport settings for use by all subsequent HTTP requests. Call this once during application startup. Can be called again to update settings at runtime.
Example
Allow more connections 
import dream_http_client/client
pub fn allow_more_connections() -> Nil {
client.transport_config()
|> client.max_connections(200)
|> client.configure_transport()
}
pub fn connect_timeout(
client_request: ClientRequest,
ms: Int,
) -> ClientRequest
Set TCP connection timeout in milliseconds
Controls how long to wait for the TCP connection to be established.
This is separate from the request timeout(), which controls the total
time for the entire HTTP request/response cycle.
Parameters
client_request: The request to modifyms: Connection timeout in milliseconds (default: 15000)
Example
Set a connect timeout 
import dream_http_client/client
import gleam/http
import gleam/result
pub fn fetch_with_connect_timeout() -> Result(BitArray, client.SendError) {
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/text")
|> client.connect_timeout(5000)
|> client.send()
|> result.map(fn(response) { response.body })
}
pub fn default_certificate_authority_file(
config: TransportConfig,
path: String,
) -> TransportConfig
Set the certificate authorities that every HTTPS request trusts
By default, the client checks servers’ certificates against the system
certificate authorities. With this setting, every request trusts the
certificate authorities in the PEM file at path in their place, unless
the request sets its own with certificate_authority_file().
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn default_connect_timeout(
config: TransportConfig,
ms: Int,
) -> TransportConfig
Set default TCP connection timeout in milliseconds
The default timeout for establishing a TCP connection when not
overridden per-request via connect_timeout().
Parameters
config: The transport config to modifyms: Connection timeout in milliseconds (default: 15_000)
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn domain_lookup_timeout(
config: TransportConfig,
ms: Int,
) -> TransportConfig
Set DNS resolution timeout in milliseconds
Parameters
config: The transport config to modifyms: DNS lookup timeout in milliseconds (default: 5_000)
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn get_auto_redirect(
client_request: ClientRequest,
) -> option.Option(Bool)
Get the configured auto-redirect setting
Returns None if the default (True) will be used.
Example
Read the request settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn internal_request() -> client.ClientRequest {
client.new()
|> client.host("internal.example.com")
|> client.certificate_authority_file("certs/internal-ca.pem")
|> client.connect_timeout(2000)
|> client.auto_redirect(False)
}
pub fn request_settings(
request: client.ClientRequest,
) -> #(Option(String), Option(Int), Option(Bool)) {
#(
client.get_certificate_authority_file(request),
client.get_connect_timeout(request),
client.get_auto_redirect(request),
)
}
pub fn get_body(client_request: ClientRequest) -> BitArray
Get the body from a request
Returns the request body as bytes. A body set with body() is the UTF-8
bytes of its string.
Example
Read the body 
import dream_http_client/client
pub fn request_body() -> BitArray {
let request = client.new() |> client.body("{\"name\": \"Alice\"}")
client.get_body(request)
}
pub fn get_certificate_authority_file(
client_request: ClientRequest,
) -> option.Option(String)
Get the certificate authority file for this request, if one is set
Returns None when the request uses the client-wide default.
Example
Read the request settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn internal_request() -> client.ClientRequest {
client.new()
|> client.host("internal.example.com")
|> client.certificate_authority_file("certs/internal-ca.pem")
|> client.connect_timeout(2000)
|> client.auto_redirect(False)
}
pub fn request_settings(
request: client.ClientRequest,
) -> #(Option(String), Option(Int), Option(Bool)) {
#(
client.get_certificate_authority_file(request),
client.get_connect_timeout(request),
client.get_auto_redirect(request),
)
}
pub fn get_closing_timeout(config: TransportConfig) -> Int
Get the configured graceful shutdown timeout in milliseconds
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_connect_timeout(
client_request: ClientRequest,
) -> option.Option(Int)
Get the configured TCP connection timeout
Returns None if the default (15000ms) will be used.
Example
Read the request settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn internal_request() -> client.ClientRequest {
client.new()
|> client.host("internal.example.com")
|> client.certificate_authority_file("certs/internal-ca.pem")
|> client.connect_timeout(2000)
|> client.auto_redirect(False)
}
pub fn request_settings(
request: client.ClientRequest,
) -> #(Option(String), Option(Int), Option(Bool)) {
#(
client.get_certificate_authority_file(request),
client.get_connect_timeout(request),
client.get_auto_redirect(request),
)
}
pub fn get_default_certificate_authority_file(
config: TransportConfig,
) -> option.Option(String)
Get the client-wide certificate authority file, if one is set
Returns None when requests trust the system certificate authorities.
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_default_connect_timeout(
config: TransportConfig,
) -> Int
Get the configured default TCP connection timeout in milliseconds
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_domain_lookup_timeout(config: TransportConfig) -> Int
Get the configured DNS resolution timeout in milliseconds
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_headers(client_request: ClientRequest) -> List(Header)
Get the headers from a request
Returns the list of headers configured for the request.
Example
Read the headers 
import dream_http_client/client
pub fn request_headers() -> List(client.Header) {
let request =
client.new()
|> client.add_header("Authorization", "Bearer token")
|> client.add_header("Content-Type", "application/json")
client.get_headers(request)
}
pub fn get_host(client_request: ClientRequest) -> String
pub fn get_idle_timeout(config: TransportConfig) -> Int
Get the configured idle connection timeout in milliseconds
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_initial_connection_window_size(
config: TransportConfig,
) -> Int
Get the configured HTTP/2 connection-level flow control window size
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_initial_stream_window_size(
config: TransportConfig,
) -> Int
Get the configured HTTP/2 per-stream flow control window size
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_keepalive(config: TransportConfig) -> Int
Get the configured HTTP/2 keepalive ping interval in milliseconds
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_keepalive_tolerance(config: TransportConfig) -> Int
Get the configured HTTP/2 keepalive tolerance
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_log_level(config: TransportConfig) -> LogLevel
Get the configured minimum log level
Returns the LogLevel that controls which internal log messages are emitted.
Only messages at this level or above are output. The default is
LogWarning.
Example
Read the log level 
import dream_http_client/client
pub fn default_log_level() -> client.LogLevel {
client.transport_config()
|> client.get_log_level()
}
pub fn get_max_concurrent_streams(config: TransportConfig) -> Int
Get the HTTP/2 SETTINGS_MAX_CONCURRENT_STREAMS value that the client sends
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_max_connections(config: TransportConfig) -> Int
Get the configured maximum TCP connections per host
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn get_method(client_request: ClientRequest) -> http.Method
Get the HTTP method from a request
Returns the HTTP method (GET, POST, etc.) configured for the request.
Example
Read the method 
import dream_http_client/client
import gleam/http.{Post}
pub fn request_method() -> http.Method {
let request = client.new() |> client.method(Post)
client.get_method(request)
}
pub fn get_path(client_request: ClientRequest) -> String
pub fn get_pool(
client_request: ClientRequest,
) -> option.Option(ConnectionPool)
Get the connection pool of the request
Parameters
client_request: The request to read
Returns
Some(ConnectionPool) when pool() set one, and None for a request
that uses the default pool.
Example
Give the model calls their own pool 
import dream_http_client/client
import gleam/option.{type Option}
pub fn model_pool() -> client.ConnectionPool {
client.new_pool(max_connections: 3)
}
pub fn model_request(
pool: client.ConnectionPool,
prompt: String,
) -> client.ClientRequest {
client.new()
|> client.host("api.llm.example")
|> client.path("/v1/chat")
|> client.body(prompt)
|> client.pool(pool)
}
pub fn pool_limit(request: client.ClientRequest) -> Option(Int) {
client.get_pool(request)
|> option.map(client.get_pool_max_connections)
}
pub fn get_pool_max_connections(pool: ConnectionPool) -> Int
Get the connection limit of a pool
Parameters
pool: The pool to read
Returns
The most connections the pool opens to one host.
Example
Give the model calls their own pool 
import dream_http_client/client
import gleam/option.{type Option}
pub fn model_pool() -> client.ConnectionPool {
client.new_pool(max_connections: 3)
}
pub fn model_request(
pool: client.ConnectionPool,
prompt: String,
) -> client.ClientRequest {
client.new()
|> client.host("api.llm.example")
|> client.path("/v1/chat")
|> client.body(prompt)
|> client.pool(pool)
}
pub fn pool_limit(request: client.ClientRequest) -> Option(Int) {
client.get_pool(request)
|> option.map(client.get_pool_max_connections)
}
pub fn get_port(
client_request: ClientRequest,
) -> option.Option(Int)
Get the port from a request
Returns the optional port number configured for the request. If None, the default port for the scheme will be used (80 for HTTP, 443 for HTTPS).
Example
Read the port 
import dream_http_client/client
import gleam/option.{type Option}
pub fn request_port() -> Option(Int) {
let request = client.new() |> client.port(8080)
client.get_port(request)
}
pub fn get_protocols(
client_request: ClientRequest,
) -> option.Option(Protocols)
Get the configured protocol preference for the connection.
Returns None if no explicit protocol preference has been set,
meaning transport-specific defaults will apply.
Read the protocols 
import dream_http_client/client.{Http2Only}
import gleam/option.{type Option}
pub fn request_protocols() -> Option(client.Protocols) {
let request = client.new() |> client.protocols(Http2Only)
client.get_protocols(request)
}
pub fn get_query(
client_request: ClientRequest,
) -> option.Option(String)
Get the query string from a request
Returns the optional query string configured for the request.
Example
Read the query string 
import dream_http_client/client
import gleam/option.{type Option}
pub fn request_query() -> Option(String) {
let request = client.new() |> client.query("page=1&limit=10")
client.get_query(request)
}
pub fn get_recorder(
client_request: ClientRequest,
) -> option.Option(recorder.Recorder)
Get the recorder from a request
Returns the optional recorder attached to the request for recording or playback.
Example
Check for a recorder 
import dream_http_client/client
import dream_http_client/recorder.{directory, mode, start}
import gleam/option
import gleam/result
pub fn has_recorder(mocks_directory: String) -> Result(Bool, String) {
use rec <- result.map(
recorder.new()
|> directory(mocks_directory)
|> mode(recorder.Record)
|> start(),
)
let request = client.new() |> client.recorder(rec)
option.is_some(client.get_recorder(request))
}
pub fn get_scheme(client_request: ClientRequest) -> http.Scheme
pub fn get_timeout(
client_request: ClientRequest,
) -> option.Option(Int)
Get the timeout from a request
Returns the optional timeout in milliseconds configured for the request. If None, the default timeout (30000ms) will be used.
Example
Read the timeout 
import dream_http_client/client
import gleam/option.{type Option}
pub fn request_timeout() -> Option(Int) {
let request = client.new() |> client.timeout(5000)
client.get_timeout(request)
}
pub fn get_tls_handshake_timeout(config: TransportConfig) -> Int
Get the configured TLS handshake timeout in milliseconds
Example
Read the transport settings 
import dream_http_client/client
import gleam/option.{type Option}
pub fn pool_settings(config: client.TransportConfig) -> List(Int) {
[
client.get_max_connections(config),
client.get_idle_timeout(config),
client.get_default_connect_timeout(config),
client.get_domain_lookup_timeout(config),
client.get_tls_handshake_timeout(config),
client.get_keepalive(config),
client.get_keepalive_tolerance(config),
client.get_max_concurrent_streams(config),
client.get_initial_connection_window_size(config),
client.get_initial_stream_window_size(config),
client.get_closing_timeout(config),
]
}
pub fn trusted_file(config: client.TransportConfig) -> Option(String) {
client.get_default_certificate_authority_file(config)
}
pub fn headers(
client_request: ClientRequest,
headers_value: List(Header),
) -> ClientRequest
Set the headers for the request
Replaces all existing headers with the provided list. Use add_header()
to add a single header without replacing existing ones.
Parameters
client_request: The request to modifyheaders_value: List of header tuples#(name, value)
Returns
A new ClientRequest with headers replaced.
Example
Set the headers 
import dream_http_client/client.{Header}
pub fn json_api_request(token: String) -> client.ClientRequest {
client.new()
|> client.headers([
Header("Authorization", "Bearer " <> token),
Header("Content-Type", "application/json"),
])
}
pub fn host(
client_request: ClientRequest,
host_value: String,
) -> ClientRequest
Set the host for the request
Sets the server hostname or IP address. This is required for all requests.
Parameters
client_request: The request to modifyhost_value: The hostname (e.g., “api.example.com” or “192.168.1.1”)
Returns
A new ClientRequest with the host updated.
Example
Set the host 
import dream_http_client/client
pub fn api_request() -> client.ClientRequest {
client.new()
|> client.host("api.example.com")
}
pub fn idle_timeout(
config: TransportConfig,
ms: Int,
) -> TransportConfig
Set idle connection timeout in milliseconds
Controls how long an idle connection is held open before being closed.
Longer timeouts improve connection reuse but consume resources. A
connection that serves a response, for example a long stream, is not
idle and stays open. The pool checks for idle connections once per
timeout, so an idle connection closes between one and two timeouts after
its last use. A new value applies at once: configure_transport makes
the pool replace the check that it scheduled with the old value.
Parameters
config: The transport config to modifyms: Idle timeout in milliseconds (default: 60_000)
Example
Keep idle connections longer 
import dream_http_client/client
pub fn keep_idle_connections() -> Nil {
client.transport_config()
|> client.idle_timeout(120_000)
|> client.configure_transport()
}
pub fn initial_connection_window_size(
config: TransportConfig,
size: Int,
) -> TransportConfig
Set HTTP/2 connection-level flow control window size
Parameters
config: The transport config to modifysize: Window size in bytes (default: 65_535)
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn initial_stream_window_size(
config: TransportConfig,
size: Int,
) -> TransportConfig
Set HTTP/2 per-stream flow control window size
Parameters
config: The transport config to modifysize: Window size in bytes (default: 65_535)
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn is_stream_active(handle: StreamHandle) -> Bool
Check if a stream is still active
Returns True if the stream process is still running, False otherwise.
Example
Check a running stream 
import dream_http_client/client
import gleam/http
import gleam/result
pub fn running_after_start() -> Result(Bool, String) {
let request =
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/stream/slow")
use stream <- result.map(client.start_stream(request))
let active = client.is_stream_active(stream)
client.cancel_stream_handle(stream)
active
}
pub fn keepalive(
config: TransportConfig,
ms: Int,
) -> TransportConfig
Set HTTP/2 keepalive ping interval in milliseconds
How often to send HTTP/2 PING frames to keep the connection alive and detect dead connections.
Parameters
config: The transport config to modifyms: Ping interval in milliseconds (default: 30_000)
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn keepalive_tolerance(
config: TransportConfig,
count: Int,
) -> TransportConfig
Set HTTP/2 keepalive tolerance
How many unacknowledged PING frames are allowed before the connection is considered dead and closed.
Parameters
config: The transport config to modifycount: Max unacknowledged pings (default: 3)
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn log_level(
config: TransportConfig,
level: LogLevel,
) -> TransportConfig
Set the minimum log level for dream_http_client’s own log output
Every log line of the client goes through one module, and this level
applies to all of them (see LogLevel for what each level shows). It is
the OTP logger module level of that module (logger:set_module_level/2),
so it does not change the logging of the rest of your application. The
level applies when configure_transport returns.
Parameters
config: The transport config to modifylevel: Minimum log level (default:LogWarning)
Example
Show the info lines 
import dream_http_client/client.{LogInfo}
pub fn info_lines() -> Nil {
client.transport_config()
|> client.log_level(LogInfo)
|> client.configure_transport()
}
pub fn max_concurrent_streams(
config: TransportConfig,
count: Int,
) -> TransportConfig
Set the HTTP/2 SETTINGS_MAX_CONCURRENT_STREAMS value that the client sends
gun sends this value to the server in the client’s SETTINGS frame: it is the number of streams that the server may open to the client at once. It does not limit the requests of the client. The pool puts requests on an HTTP/2 connection up to the limit that the server sends in its own SETTINGS frame.
Parameters
config: The transport config to modifycount: Max concurrent streams (default: 100)
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn max_connections(
config: TransportConfig,
count: Int,
) -> TransportConfig
Set maximum TCP connections per host
Controls how many simultaneous TCP connections can be open to a single host. With HTTP/2, a single connection supports multiplexed streams, so fewer connections are needed than with HTTP/1.1.
An HTTP/1.1 connection carries one request at a time. An HTTP/2
connection carries as many streams as the server allows with
SETTINGS_MAX_CONCURRENT_STREAMS. The pool opens a new connection only
when every connection to the host is full. When count connections are
full, a new request waits for room up to its timeout, and then fails
with TimedOut.
Parameters
config: The transport config to modifycount: Maximum connections per host (default: 50)
Example
Allow more connections 
import dream_http_client/client
pub fn allow_more_connections() -> Nil {
client.transport_config()
|> client.max_connections(200)
|> client.configure_transport()
}
pub fn method(
client_request: ClientRequest,
method_value: http.Method,
) -> ClientRequest
Set the HTTP method for the request
Configures the HTTP method (GET, POST, PUT, DELETE, etc.) for the request.
Parameters
client_request: The request to modifymethod_value: The HTTP method to use
Returns
A new ClientRequest with the method updated.
Example
Set the method 
import dream_http_client/client
import gleam/http
pub fn post_request() -> client.ClientRequest {
client.new()
|> client.method(http.Post)
}
pub fn new() -> ClientRequest
Default client request configuration
Creates a new ClientRequest with sensible defaults:
- Method: GET
- Scheme: HTTPS
- Host: “localhost”
- Port: None (uses default for scheme)
- Path: “” (empty)
- Query: None
- Headers: [] (empty)
- Body: “” (empty)
- Timeout: None (uses default 30000ms)
Use this as the starting point for building requests with the builder pattern.
Example
Build a request 
import dream_http_client/client.{host, method, new, path}
import gleam/http.{Get}
pub fn user_request() -> client.ClientRequest {
new()
|> host("api.example.com")
|> path("/users/123")
|> method(Get)
}
pub fn new_pool(
max_connections max_connections: Int,
) -> ConnectionPool
Make a connection pool
Make a pool one time, for example when the application starts, and keep the value with the other services of the application. Each call makes a new pool with its own connections, so a pool made for each request would never use a connection again.
Parameters
max_connections: The most connections the pool opens to one host
Returns
A new pool with no connections. The pool opens a connection when a request needs one.
Example
Give the model calls their own pool 
import dream_http_client/client
import gleam/option.{type Option}
pub fn model_pool() -> client.ConnectionPool {
client.new_pool(max_connections: 3)
}
pub fn model_request(
pool: client.ConnectionPool,
prompt: String,
) -> client.ClientRequest {
client.new()
|> client.host("api.llm.example")
|> client.path("/v1/chat")
|> client.body(prompt)
|> client.pool(pool)
}
pub fn pool_limit(request: client.ClientRequest) -> Option(Int) {
client.get_pool(request)
|> option.map(client.get_pool_max_connections)
}
pub fn on_stream_chunk(
client_request: ClientRequest,
callback: fn(BitArray) -> Nil,
) -> ClientRequest
Set callback for stream chunk event
Sets a function to be called for each data chunk received from the stream. This is where you process the actual response data.
The client reads the next chunk from the server only after the callback returns (at most 16 chunks wait in memory). A slow callback slows the server down and does not fill memory. The request timeout measures the server, not the callback.
Parameters
client_request: The request to modifycallback: Function called with each chunk of data
Example
Forward each chunk 
import dream_http_client/client
import gleam/bit_array
import gleam/erlang/process.{type Subject}
import gleam/http
import gleam/result
pub fn forward_chunks(
reply_to: Subject(String),
) -> Result(client.StreamHandle, String) {
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/stream/fast")
|> client.on_stream_chunk(fn(data) {
let text = bit_array.to_string(data) |> result.unwrap("<binary>")
process.send(reply_to, text)
})
|> client.start_stream()
}
pub fn on_stream_end(
client_request: ClientRequest,
callback: fn(List(Header)) -> Nil,
) -> ClientRequest
Set callback for stream end event
Sets a function to be called when a stream completes successfully. Optional - if not set, stream completion is ignored.
Parameters
client_request: The request to modifycallback: Function called with trailing headers when stream completes
Example
Report the end of a stream 
import dream_http_client/client
import gleam/erlang/process.{type Subject}
import gleam/http
pub fn report_end(
reply_to: Subject(String),
) -> Result(client.StreamHandle, String) {
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/stream/fast")
|> client.on_stream_end(fn(_headers) {
process.send(reply_to, "Stream completed")
})
|> client.start_stream()
}
pub fn on_stream_error(
client_request: ClientRequest,
callback: fn(StreamFailure) -> Nil,
) -> ClientRequest
Set callback for stream error event
Sets a function to be called if the stream fails with an error.
The callback receives a StreamFailure which distinguishes HTTP failures
(non-2xx response) from transport failures (connection errors, timeouts).
Parameters
client_request: The request to modifycallback: Function called with aStreamFailureif stream fails
Example
Report a stream failure 
import dream_http_client/client
import gleam/erlang/process.{type Subject}
import gleam/http
import gleam/int
pub fn report_failure(
reply_to: Subject(String),
) -> Result(client.StreamHandle, String) {
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/status/500")
|> client.on_stream_error(fn(failure) {
case failure {
client.HttpFailure(response: response) ->
process.send(reply_to, "HTTP " <> int.to_string(response.status))
client.TransportFailure(error: error) ->
process.send(
reply_to,
"Transport: " <> client.transport_error_to_string(error),
)
}
})
|> client.start_stream()
}
pub fn on_stream_start(
client_request: ClientRequest,
callback: fn(List(Header)) -> Nil,
) -> ClientRequest
Set callback for stream start event
Sets a function to be called when a stream starts and headers are received. Optional - if not set, stream start is ignored.
Parameters
client_request: The request to modifycallback: Function called with response headers when stream starts
Example
Count the response headers 
import dream_http_client/client
import gleam/erlang/process.{type Subject}
import gleam/http
import gleam/list
pub fn report_header_count(
reply_to: Subject(Int),
) -> Result(client.StreamHandle, String) {
client.new()
|> client.scheme(http.Http)
|> client.host("localhost")
|> client.port(9876)
|> client.path("/stream/fast")
|> client.on_stream_start(fn(headers) {
process.send(reply_to, list.length(headers))
})
|> client.start_stream()
}
pub fn path(
client_request: ClientRequest,
path_value: String,
) -> ClientRequest
Set the path for the request
Sets the request path. Should start with “/” for absolute paths.
Parameters
client_request: The request to modifypath_value: The path (e.g., “/api/users” or “/api/users/123”)
Returns
A new ClientRequest with the path updated.
Example
Set the path 
import dream_http_client/client
pub fn user_request() -> client.ClientRequest {
client.new()
|> client.path("/api/users/123")
}
pub fn pool(
client_request: ClientRequest,
pool: ConnectionPool,
) -> ClientRequest
Send this request through a connection pool of its own
Without this setting, every request uses the default pool, and
max_connections() of the transport config limits the connections to
each host. With it, the request shares connections only with requests
that have the same pool, and that pool opens at most its own
max_connections connections to each host. A busy caller with a pool of
its own does not use up the connections of other callers, and a small
limit holds one caller back without a change for the others.
When every connection of the pool is full, the request waits for room up
to its timeout, and then fails with TimedOut. On HTTP/2, one
connection carries as many requests as the server allows, so the limit
is on connections, not on requests.
Parameters
client_request: The request to modifypool: A pool fromnew_pool()
Returns
The request with the pool set.
Example
Give the model calls their own pool 
import dream_http_client/client
import gleam/option.{type Option}
pub fn model_pool() -> client.ConnectionPool {
client.new_pool(max_connections: 3)
}
pub fn model_request(
pool: client.ConnectionPool,
prompt: String,
) -> client.ClientRequest {
client.new()
|> client.host("api.llm.example")
|> client.path("/v1/chat")
|> client.body(prompt)
|> client.pool(pool)
}
pub fn pool_limit(request: client.ClientRequest) -> Option(Int) {
client.get_pool(request)
|> option.map(client.get_pool_max_connections)
}
pub fn port(
client_request: ClientRequest,
port_value: Int,
) -> ClientRequest
Set the port for the request
Sets a custom port number. If not set, defaults to 80 for HTTP and 443 for HTTPS. Only set this if you’re using a non-standard port.
Parameters
client_request: The request to modifyport_value: The port number (e.g., 8080, 3000)
Returns
A new ClientRequest with the port updated.
Example
Set the port 
import dream_http_client/client
pub fn local_request() -> client.ClientRequest {
client.new()
|> client.host("localhost")
|> client.port(3000)
}
pub fn protocols(
client_request: ClientRequest,
preference: Protocols,
) -> ClientRequest
Set the protocol preference for the connection.
Controls which HTTP protocol version gun negotiates when opening a connection. When not set, defaults to HTTP/2 preferred (via ALPN) for HTTPS connections and HTTP/1.1 only for HTTP connections.
For HTTP/2 over cleartext (h2c), use Http2Only with scheme(http.Http):
Use HTTP/2 only 
import dream_http_client/client.{Http2Only}
import gleam/http
pub fn http2_only_request() -> client.ClientRequest {
client.new()
|> client.scheme(http.Http)
|> client.host("internal-service.local")
|> client.protocols(Http2Only)
}
pub fn query(
client_request: ClientRequest,
query_value: String,
) -> ClientRequest
Set the query string for the request
Sets the query string portion of the URL. Do not include the leading “?”.
Parameters
client_request: The request to modifyquery_value: The query string (e.g., “page=1&limit=10”)
Returns
A new ClientRequest with the query string updated.
Example
Set the query string 
import dream_http_client/client
pub fn first_page_request() -> client.ClientRequest {
client.new()
|> client.path("/api/users")
|> client.query("page=1&limit=10")
}
pub fn recorder(
client_request: ClientRequest,
recorder_value: recorder.Recorder,
) -> ClientRequest
Set the recorder for the request
Attaches a recorder to the request for recording or playback.
The recorder must be started with recorder.start() before use.
Parameters
client_request: The request to modifyrecorder_value: The recorder to attach
Returns
A new ClientRequest with the recorder attached.
Example
Attach a recorder 
import dream_http_client/client.{host, recorder}
import dream_http_client/recorder.{directory, mode, start}
import gleam/result
pub fn recorded_request(
mocks_directory: String,
) -> Result(client.ClientRequest, String) {
use rec <- result.map(
recorder.new()
|> directory(mocks_directory)
|> mode(recorder.Record)
|> start(),
)
client.new() |> host("api.example.com") |> recorder(rec)
}
pub fn scheme(
client_request: ClientRequest,
scheme_value: http.Scheme,
) -> ClientRequest
Set the scheme (protocol) for the request
Configures whether to use HTTP or HTTPS. Defaults to HTTPS for security.
Parameters
client_request: The request to modifyscheme_value: The protocol scheme (http.Httporhttp.Https)
Returns
A new ClientRequest with the scheme updated.
Example
Set the scheme 
import dream_http_client/client
import gleam/http
pub fn plain_http_request() -> client.ClientRequest {
client.new()
|> client.scheme(http.Http)
}
pub fn send(
client_request: ClientRequest,
) -> Result(HttpResponse, SendError)
Make a blocking HTTP request and get the complete response
Sends an HTTP request and collects all response chunks, returning the complete response with status code, headers, and body. This is ideal for:
- JSON API responses
- Small files or documents
- Any case where you need the full response before processing
For large responses or when you need non-blocking streaming, use
stream_yielder() or start_stream() instead.
Recording and Playback
When a recorder is attached (via recorder()), this function fully supports
both recording and playback. In record mode, the real response is persisted
to disk. In playback mode, the recorded response is returned without making
a network call. A request that no recording matches returns
Error(RequestError(NoRecording(method, url, directory, nearest))) and is not sent.
Parameters
client_request: The configured HTTP request
Returns
Ok(HttpResponse): Successful response (status < 400) with status, headers, and bodyError(ResponseError(response)): HTTP error response (status >= 400) with full responseError(RequestError(error: transport_error)): Connection failure, timeout, or other transport error
Example
Send and handle errors 
import dream_http_client/client.{
RequestError, ResponseError, host, path, port, scheme, send,
transport_error_to_string,
}
import gleam/http
import gleam/int
import gleam/result
pub fn fetch_text() -> Result(String, String) {
let result =
client.new()
|> scheme(http.Http)
|> host("localhost")
|> port(9876)
|> path("/text")
|> send()
case result {
Ok(response) ->
client.body_text(response)
|> result.replace_error("The body is not text")
Error(ResponseError(response: response)) ->
Error("HTTP error " <> int.to_string(response.status))
Error(RequestError(error: error)) -> Error(transport_error_to_string(error))
}
}
pub fn start_stream(
request: ClientRequest,
) -> Result(StreamHandle, String)
Start an HTTP stream with callback handlers
Spawns a dedicated process to handle HTTP streaming and calls your callbacks as messages arrive. This is the recommended API for streaming in OTP applications and concurrent contexts.
Returns a StreamHandle immediately (non-blocking). The stream runs in a
separate process, and your callbacks execute in that process.
Recording and Playback
When a recorder is attached (via recorder()), this function fully supports
both recording and playback:
- Record mode: Streams from the real server and records chunks to disk. The recorded fixture captures each chunk along with timing information.
- Playback mode: Replays recorded chunks via your callbacks:
on_stream_start, thenon_stream_chunkfor each chunk after its recorded delay, thenon_stream_end. The timeout of the request limits each wait, as in a live stream: a longer delay callson_stream_errorwith aTimedOutfailure. A recording with a status outside 2xx calls onlyon_stream_error, with anHttpFailurethat holds the recorded status, headers and body. No network calls are made. A request that no recording matches calls onlyon_stream_error, withTransportFailure(NoRecording(method, url, directory, nearest)), and is not sent.
The same StreamingResponse fixture format is shared with stream_yielder(),
so recordings made with either function can be played back by both.
Parameters
request: The configured HTTP request with callbacks set via builder pattern
Returns
Ok(StreamHandle): Stream started successfullyError(String): Failed to start stream
Example
Stream with callbacks 
import dream_http_client/client.{
type Header, type StreamFailure, await_stream, host, on_stream_chunk,
on_stream_end, on_stream_error, on_stream_start, path, port, scheme,
start_stream, stream_failure_to_string,
}
import gleam/bit_array
import gleam/http
import gleam/io
pub fn stream_and_print() -> Result(Nil, String) {
let stream_result =
client.new()
|> scheme(http.Http)
|> host("localhost")
|> port(9876)
|> path("/stream/fast")
|> on_stream_start(print_stream_start)
|> on_stream_chunk(print_chunk)
|> on_stream_end(print_stream_end)
|> on_stream_error(print_stream_error)
|> start_stream()
case stream_result {
Error(reason) -> Error(reason)
Ok(stream_handle) -> {
// Wait for the stream to complete
await_stream(stream_handle)
Ok(Nil)
}
}
}
fn print_stream_start(_headers: List(Header)) -> Nil {
io.println("Stream started")
}
fn print_chunk(data: BitArray) -> Nil {
case bit_array.to_string(data) {
Ok(text) -> io.print(text)
Error(Nil) -> io.print("<binary>")
}
}
fn print_stream_end(_headers: List(Header)) -> Nil {
io.println("\nStream completed")
}
fn print_stream_error(failure: StreamFailure) -> Nil {
io.println_error("Stream error: " <> stream_failure_to_string(failure))
}
pub fn stream_failure_to_string(failure: StreamFailure) -> String
Convert a StreamFailure to a human-readable string for logging.
Produces a single-line summary suitable for log messages. For programmatic
error handling, pattern match on the StreamFailure variants instead.
Example
Describe a stream failure 
import dream_http_client/client.{
TimedOut, TransportFailure, stream_failure_to_string,
}
pub fn timeout_message() -> String {
stream_failure_to_string(TransportFailure(error: TimedOut(timeout_ms: 5000)))
}
pub fn stream_to(
request: ClientRequest,
inbox: process.Subject(StreamMessage),
) -> Result(RequestId, String)
Start an HTTP stream that sends typed messages to an inbox
Starts the stream in its own process and returns its RequestId at once
(non-blocking). The stream sends StreamMessage values to inbox:
StreamStart, then a Chunk for each part of the body, then exactly one
StreamEnd or StreamError. Each message carries the returned
RequestId. Only inbox gets messages: no untyped message reaches the
mailbox of your process.
Use this in an OTP actor. Add inbox to the selector of the actor with
process.select, and handle the stream messages like any other actor
message. Use start_stream() when callbacks that run in the stream
process are enough. stream_to() does not call the on_stream_*
callbacks of request.
Ownership
The process that calls stream_to() owns the stream. When that process
stops, the stream stops too and sends nothing more. A start_stream()
stream is different: it keeps running after the process that started it
stops.
Recording and Playback
When a recorder is attached (via recorder()), stream_to() works like
start_stream():
- Record mode: Streams from the real server, sends the messages, and
saves the stream in the
StreamingResponsefixture format thatstart_stream()andstream_yielder()use. The stream is saved before itsStreamEndorStreamErrormessage is sent. A cancelled stream is not saved. - Playback mode: Sends
StreamStartwith the recorded headers, aChunkfor each recorded chunk after its recorded delay, thenStreamEnd(request_id, []). A blocking recording is sent as one chunk. The timeout of the request limits each wait, as in a live stream: a longer delay sendsStreamErrorwith aTimedOutfailure. A recording with a status outside 2xx sends onlyStreamError, with anHttpFailurethat holds the recorded status, headers and body. No network calls are made. A request that no recording matches sends onlyStreamErrorwithTransportFailure(NoRecording(method, url, directory, nearest)), and is not sent.
Parameters
request: The configured HTTP requestinbox: The subject that gets the stream messages. The process that created it receives them.
Returns
Ok(RequestId): The stream started. Every message of the stream carries thisRequestId.Error(String): The same shape asstart_stream(). It is not returned today: a stream that cannot connect, or that gets an error response, sends aStreamErrortoinbox.
Example
Stream into an actor 
import dream_http_client/client.{
type StreamMessage, Chunk, StreamEnd, StreamError, StreamStart, host, path,
port, scheme, stream_failure_to_string, stream_to,
}
import gleam/bit_array
import gleam/erlang/process.{type Subject}
import gleam/http
import gleam/otp/actor
import gleam/result
pub type State {
State(body: BitArray, done: Subject(Result(BitArray, String)))
}
pub fn download_body() -> Result(BitArray, String) {
let done = process.new_subject()
use _started <- result.try(
actor.new_with_initialiser(1000, fn(_self) { start_download(done) })
|> actor.on_message(handle_stream_message)
|> actor.start
|> result.map_error(describe_start_error),
)
case process.receive(done, 10_000) {
Ok(body_result) -> body_result
Error(Nil) -> Error("The download did not end within 10 seconds")
}
}
fn start_download(
done: Subject(Result(BitArray, String)),
) -> Result(actor.Initialised(State, StreamMessage, Nil), String) {
let inbox = process.new_subject()
let request =
client.new()
|> scheme(http.Http)
|> host("localhost")
|> port(9876)
|> path("/stream/fast")
// The actor owns the stream: the stream stops when the actor stops
use _request_id <- result.map(stream_to(request, inbox))
let selector = process.new_selector() |> process.select(inbox)
actor.initialised(State(body: <<>>, done: done))
|> actor.selecting(selector)
}
fn handle_stream_message(
state: State,
message: StreamMessage,
) -> actor.Next(State, StreamMessage) {
case message {
StreamStart(..) -> actor.continue(state)
Chunk(data: data, ..) ->
actor.continue(State(..state, body: bit_array.append(state.body, data)))
StreamEnd(..) -> {
process.send(state.done, Ok(state.body))
actor.stop()
}
StreamError(error: error, ..) -> {
process.send(state.done, Error(stream_failure_to_string(error)))
actor.stop()
}
}
}
fn describe_start_error(error: actor.StartError) -> String {
case error {
actor.InitTimeout -> "The download actor did not start in time"
actor.InitFailed(reason) -> reason
actor.InitExited(_reason) -> "The download actor stopped while it started"
}
}
See Also
cancel_stream(): stops the streamStreamMessage: the messages and their orderstart_stream(): a stream with callbacks
pub fn stream_yielder(
client_request: ClientRequest,
) -> yielder.Yielder(Result(bytes_tree.BytesTree, StreamFailure))
Stream HTTP response chunks using a yielder
Sends an HTTP request and returns a yielder that produces chunks of the response body as they arrive from the server. This allows you to process large responses incrementally without loading the entire response into memory.
Use this for simple sequential streaming:
- AI/LLM inference endpoints (stream tokens)
- Simple file downloads
- Scripts or one-off operations
For OTP actors with concurrency, use start_stream() instead.
Recording and Playback
When a recorder is attached (via recorder()), this function fully supports
both recording and playback:
- Record mode: Streams from the real server and records chunks to disk, capturing timing information between chunks for realistic replay. The recording has the status that the server sent. A stream that fails is not saved, because playback would show its first part as a whole response.
- Playback mode: Yields recorded chunks from the fixture file, each
after its recorded delay. The timeout of the request limits each wait,
as in a live stream: a longer delay yields a
TimedOutfailure. A recording with a status outside 2xx yields oneHttpFailurewith the recorded status, headers and body, as a live stream does. No network calls are made. A request that no recording matches yields oneTransportFailure(NoRecording(method, url, directory, nearest)), and is not sent.
The same StreamingResponse fixture format is shared with start_stream(),
so recordings made with either function can be played back by both.
Flow Control
The client reads the response from the server only as fast as you take chunks from the yielder. At most 16 chunks wait in memory. The rest of the response waits in the network, so a slow reader of a large response does not fill memory.
Error Semantics
The yielder produces Result(BytesTree, StreamFailure) for each chunk:
Ok(chunk)- Successful chunk, more may followError(failure)- Terminal error, stream is done
After an Error, the yielder returns Done on the next call. It does not
send the request again, and the connection goes back to the pool. So
yielder.to_list and yielder.fold return on a stream that fails, and
the list ends with the one Error. HTTP stream errors (timeouts,
connection drops, etc.) are not recoverable - you cannot continue
reading from a broken stream.
Normal stream completion: When the stream finishes successfully, the yielder
returns Done (no more items). The stream does NOT yield an error for normal completion.
Errors are structured as StreamFailure:
HttpFailure(response)- Server returned non-2xx (status, headers, body available)TransportFailure(error)- Transport-level failure (timeout, connection drop, etc.)
Parameters
client_request: The configured HTTP request
Returns
A Yielder that produces Result(BytesTree, StreamFailure). Always check each
result - errors are terminal and mean the stream has ended.
Examples
Streaming and processing chunks as they arrive:
Count the bytes of a stream 
import dream_http_client/client.{
type StreamFailure, host, path, port, scheme, stream_yielder,
}
import gleam/bytes_tree.{type BytesTree}
import gleam/http
import gleam/result
import gleam/yielder
pub fn count_stream_bytes() -> Result(Int, StreamFailure) {
client.new()
|> scheme(http.Http)
|> host("localhost")
|> port(9876)
|> path("/stream/fast")
|> stream_yielder()
|> yielder.try_fold(0, add_chunk_size)
}
fn add_chunk_size(
total: Int,
chunk_result: Result(BytesTree, StreamFailure),
) -> Result(Int, StreamFailure) {
use chunk <- result.map(chunk_result)
total + bytes_tree.byte_size(chunk)
}
Collecting all chunks into a list:
Collect a stream into a string 
import dream_http_client/client.{host, path, port, scheme, stream_yielder}
import gleam/bit_array
import gleam/bytes_tree
import gleam/http
import gleam/list
import gleam/result
import gleam/string
import gleam/yielder
pub fn stream_to_string() -> Result(String, String) {
// The stream ends by itself: no need for take()
let chunks =
client.new()
|> scheme(http.Http)
|> host("localhost")
|> port(9876)
|> path("/stream/fast")
|> stream_yielder()
|> yielder.to_list()
case list.try_map(chunks, fn(chunk) { chunk }) {
Ok(chunk_list) ->
chunk_list
|> list.map(bytes_tree.to_bit_array)
|> list.map(fn(data) { bit_array.to_string(data) |> result.unwrap("") })
|> string.join("")
|> Ok
Error(failure) -> Error(client.stream_failure_to_string(failure))
}
}
pub fn timeout(
client_request: ClientRequest,
timeout_ms: Int,
) -> ClientRequest
Set the timeout for the request in milliseconds
Sets how long to wait for a response before timing out. If not set, defaults to 30000ms (30 seconds).
Parameters
timeout_ms: Timeout duration in milliseconds
Example
Set a timeout 
import dream_http_client/client.{host, timeout}
pub fn slow_request() -> client.ClientRequest {
client.new()
|> host("slow-api.example.com")
|> timeout(60_000)
}
pub fn tls_handshake_timeout(
config: TransportConfig,
ms: Int,
) -> TransportConfig
Set TLS handshake timeout in milliseconds
Parameters
config: The transport config to modifyms: TLS negotiation timeout in milliseconds (default: 10_000)
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn transport_config() -> TransportConfig
Create a transport configuration with default values
Returns a TransportConfig with sensible defaults:
- max_connections: 50 (TCP connections per host)
- idle_timeout: 60_000ms (close idle connections after 60s)
- default_connect_timeout: 15_000ms (TCP connection timeout)
- domain_lookup_timeout: 5_000ms (DNS resolution timeout)
- tls_handshake_timeout: 10_000ms (TLS negotiation timeout)
- keepalive: 30_000ms (HTTP/2 ping interval)
- keepalive_tolerance: 3 (unack’d pings before disconnect)
- max_concurrent_streams: 100 (the HTTP/2 SETTINGS_MAX_CONCURRENT_STREAMS value that the client sends to the server)
- initial_connection_window_size: 65_535 (HTTP/2 connection flow control)
- initial_stream_window_size: 65_535 (HTTP/2 per-stream flow control)
- closing_timeout: 15_000ms (graceful shutdown wait)
- log_level: LogWarning (minimum severity for dream log output: warnings only. The application starts with this level, and a server that closes an idle connection writes no line)
- default_certificate_authority_file: None (trust the system certificate authorities over TLS)
Example
Tune the transport 
import dream_http_client/client
pub fn tuned_transport() -> client.TransportConfig {
client.transport_config()
|> client.max_connections(100)
|> client.idle_timeout(30_000)
|> client.default_connect_timeout(5000)
|> client.domain_lookup_timeout(2000)
|> client.tls_handshake_timeout(5000)
|> client.keepalive(10_000)
|> client.keepalive_tolerance(3)
|> client.max_concurrent_streams(200)
|> client.initial_connection_window_size(1_048_576)
|> client.initial_stream_window_size(262_144)
|> client.closing_timeout(5000)
|> client.default_certificate_authority_file("certs/ca.pem")
}
pub fn transport_error_to_string(error: TransportError) -> String
Convert a TransportError to a human-readable string for logging.
Produces a single-line summary suitable for log messages. For programmatic
error handling, pattern match on the TransportError variants instead.
NoRecording is the one error with more lines. The first line names the
request. Then each nearest recording shows its path and the parts that
differ, with the recorded value on a - line and the requested value on
a + line. With no nearest recording, the second line names the
directory that the recorder searched.
Example
Describe a transport error 
import dream_http_client/client.{ConnectFailed, transport_error_to_string}
pub fn connect_failed_message() -> String {
transport_error_to_string(ConnectFailed(reason: "Connection refused"))
}