Introducing a new way to review your PRs.

Read the announcement

appwrite / appwrite

The open-source cloud for agents & devs. Including Auth, Databases, Storage, Functions, Messaging, Hosting, Realtime, WAF and more

View on GitHub

59 documents · Updated Nov 20, 2026

docs / http-client-library

HTTP client library

The packages/client/ package is a reusable PSR-18 HTTP client for PHP. It gives application code one request and response contract while supporting cURL and Swoole coroutine transports, connection reuse, redirects, retries, TLS controls, optional trace propagation, and bounded-memory streaming. It builds on the PSR-7 HTTP message primitives package and fits into the wider reusable platform packages set.

Package role

Shared transport boundary

The client separates HTTP messages from the transport that sends them. Calling code works with PSR-7 requests and responses, while the selected adapter handles the network system. This lets a service choose a normal PHP transport or a coroutine transport without changing its HTTP contract.

The public surface has two related paths:

  • sendRequest() follows PSR-18 and returns a response with a buffered body.
  • stream() delivers body chunks to a caller while returning the response status and headers.

Client adds shared request preparation and configuration around an Adapter. Decorators such as retry handling also use the adapter contract, so transport behavior can be composed without changing callers.

References: packages/…/Adapter.php• L10-41 packages/…/Client.php• L16-29 packages/…/Client.php• L156-171 packages/…/Decorator.php• L11-17

Transport adapters

The package supports two transport choices. The cURL adapter is suitable for standard PHP runtimes. The Swoole coroutine adapter is suitable for code that runs inside a Swoole coroutine and can share that runtime's scheduling model.

Both adapters present the same high-level behavior. They map common settings such as timeouts, TLS, connection reuse, and redirect handling to their native transport. The package also normalizes transport failures into the same exception model.

AdapterRuntime needMain use
cURLPHP cURL extensionGeneral blocking HTTP requests and streams
Swoole coroutineSwoole extension and an active coroutineCoroutine-based concurrent HTTP work

References: packages/…/README.md• L6-14 packages/…/Client.php• L35-69 packages/…/Client.php• L38-103

Request lifecycle

Request preparation

Before the transport sees a request, Client creates the final request value from the caller's PSR-7 message. It resolves relative URIs against an optional base URI and adds configured headers only when the request does not already define them. The original message remains unchanged because PSR-7 messages are immutable.

The client can also add the active W3C traceparent value when trace propagation is enabled. It does not replace a trace header already present on the request. The transport then requires an absolute http or https URI. Request bodies remain streams, so the same request model can carry small data, files, multipart data, or a body that the transport reads in chunks.

References: packages/…/Client.php• L99-150 packages/…/Client.php• L156-181 packages/…/Client.php• L183-232 packages/…/Client.php• L207-224 packages/…/Client.php• L218-228

Transfer stages

The request lifecycle moves from a prepared message to a transport exchange and then to a normalized response or a typed exception. This diagram shows the main path shared by buffered and streamed requests.

flowchart LR
    A[PSR-7 request] --> B[Client preparation]
    B --> C[Adapter validation]
    C --> D[DNS and connection]
    D --> E[Request body transfer]
    E --> F[Response status and headers]
    F --> G{Body mode}
    G --> H[Buffered PSR-7 response]
    G --> I[Sink receives chunks]
    C --> J[Typed client exception]
    D --> J
    E --> J
    F --> J

The client returns a response when the peer sends a valid HTTP response, including 4xx and 5xx status codes. It throws only when it cannot send the request or cannot create a usable PSR-7 response.

References: packages/…/Client.php• L156-171 packages/…/Client.php• L207-257 packages/…/Client.php• L218-259 packages/…/error-handling.md• L3-18

Response handling

Buffered calls return a PSR-7 response with status, headers, and a body that can be read through the PSR-7 response helpers. The client does not turn an HTTP status into an exception, so the caller decides how to handle an application-level error.

The adapters can decode response compression before the response reaches the caller. When they do, they also remove headers that would describe the old encoded body. A caller that sets Accept-Encoding takes control of that negotiation.

References: packages/…/README.md• L101-121 packages/…/configuration.md• L88-113 packages/…/Client.php• L243-257 packages/…/Client.php• L406-429

Connection pooling

Connection reuse

Connection reuse keeps a transport connection available for later requests to the same origin. An origin is the scheme, host, and effective port, so a request to another origin uses a separate connection. Reuse is off by default because callers must choose when the longer-lived connection state is useful.

Reuse avoids repeated TCP and TLS handshakes. It is most useful when one client sends many requests to one upstream. A dropped idle connection is detected by the transport and replaced on the next request.

References: packages/…/Adapter.php• L28-34 packages/…/configuration.md• L47-66 packages/…/pooling.md• L32-39 packages/…/Client.php• L266-284 packages/…/Client.php• L502-551

Borrowed client pools

Utopia\\Client\\Pool limits concurrent work by borrowing one configured client for each request and returning it when the request or stream ends. The pool therefore bounds the number of active connections while allowing callers to share them across sequential work.

The pool owns many clients rather than one adapter. Configure reuse, authentication, base URI, and retry behavior in the pool's client factory. The connection pools library page explains the shared pool resource model.

sequenceDiagram
    participant Caller
    participant HTTP Pool
    participant Connection Pool
    participant Upstream
    Caller->>HTTP Pool: sendRequest or stream
    HTTP Pool->>Connection Pool: borrow client
    Connection Pool->>Upstream: use configured connection
    Upstream-->>Connection Pool: response or chunks
    Connection Pool-->>HTTP Pool: completed operation
    HTTP Pool-->>Caller: response
    HTTP Pool->>Connection Pool: release client

References: packages/…/Pool.php• L14-51 packages/…/pooling.md• L1-6 packages/…/pooling.md• L72-84

Redirect handling

Redirect following

Redirect following is disabled by default. In that mode, the caller receives the 3xx response and its Location header. When enabled, the client follows the location until it receives a non-redirect response or reaches the hop limit.

Relative locations follow RFC 3986 path and query rules. For 301, 302, and 303 responses, a non-GET or non-HEAD request changes to GET and drops its request body. Other redirects preserve the method and rewind a seekable body when possible.

References: packages/…/Adapter.php• L36-41 packages/…/Redirect.php• L18-78 packages/…/Client.php• L352-363 packages/…/Client.php• L230-249 packages/…/Client.php• L453-490

Redirect credential scope

Sensitive headers stay on same-origin redirects because the target remains within the same authority and scheme. A change of host, scheme, or effective port removes Authorization, Cookie, Cookie2, and Proxy-Authorization before the next request. This also protects credentials during an HTTPS-to-HTTP downgrade.

The rule applies to both adapters even though the transports use different redirect mechanisms. It gives callers one predictable boundary for forwarding credentials.

References: packages/…/Redirect.php• L23-30 packages/…/Redirect.php• L120-141 packages/…/RedirectTest.php• L47-87

Retry behavior

Retry decisions

Retry is a decorator that repeats an adapter operation when a strategy says the outcome is safe and useful to retry. Its default strategy limits retries to idempotent methods and transient outcomes. Idempotent means that repeating the request should have the same intended effect as sending it once.

The default policy has these limits:

  • It retries GET, HEAD, PUT, DELETE, OPTIONS, and TRACE.
  • It retries network failures and status codes 429, 502, 503, and 504.
  • It uses exponential backoff with full jitter and honors a numeric Retry-After value.
  • It allows three attempts by default.

Custom strategies can change the method, outcome, delay, or attempt limit without changing the transport. A request exception is not a transient network outcome and is not retried by the default policy.

References: packages/…/Decorator.php• L11-17 packages/…/Retry.php• L16-61 packages/…/Backoff.php• L15-70 packages/…/retries.md• L17-27

Stream retry boundary

A streamed operation can retry only before it delivers any bytes to the sink. After the first byte reaches the caller, another attempt could duplicate data, so the decorator returns the result or surfaces the error instead of replaying the stream.

This boundary makes retries safe for partial delivery. Callers that need recovery after partial data must define that recovery at the stream format or application level.

References: packages/…/Retry.php• L64-100 packages/…/retries.md• L24-27

TLS and transport settings

TLS controls

TLS verification and certificate-chain checks are enabled by default. The client can trust a private CA, present a client certificate for mutual TLS, and set a minimum TLS version through transport-neutral helpers. These settings are cloned with the client, so one configured client does not change another.

Disabling verification disables certificate checks and is intended only for local development. A private CA should use withCustomCA() so verification stays enabled. The Swoole adapter checks the host from each HTTPS URI for certificate identity and does not support verified HTTPS requests to IP-literal URIs.

References: packages/…/Client.php• L48-78 packages/…/Client.php• L93-133 packages/…/Client.php• L127-167 packages/…/configuration.md• L22-45

Timeout and adapter settings

The client exposes separate total-transfer and connection timeouts. Adapter constructors also accept native cURL options or Swoole settings for transport features not covered by the shared helpers. The shared helpers remain the preferred choice when the same behavior must work across both adapters.

The Swoole adapter requires an active coroutine. An unbounded stream also needs an explicit no-limit transfer timeout when the caller expects it to remain open until the sink stops it.

References: packages/…/Adapter.php• L14-26 packages/…/configuration.md• L8-20 packages/…/configuration.md• L115-170 packages/…/streaming.md• L42-49

Streaming

Response streams

The streaming interface sends each response body chunk to a sink as the transport receives it. The returned response keeps the status and headers but has an empty body because the body already went to the sink. This keeps memory bounded for large downloads, server-sent events, and token streams.

The sink also controls backpressure: the transport does not continue reading while the sink is still handling a chunk. A sink can stop an operation by throwing. For an unbounded stream, the caller must set a suitable timeout and define the condition that ends the stream.

References: packages/…/StreamingClientInterface.php• L11-27 packages/…/Client.php• L161-171 packages/…/Client.php• L182-193 packages/…/Client.php• L199-205 packages/…/streaming.md• L3-23

Server response streams

The Swoole server response uses the same response boundary for normal output and incremental output. It sends headers once, writes chunks as they arrive, and can apply incremental compression when the client accepts a supported encoding. Large responses are split into chunks instead of being sent as one unbounded write.

For slow clients, the Swoole adapter watches the connection's queued bytes when it has a server handle and runs inside a coroutine. It pauses until the queue drains, returns failure when the connection is gone, and closes a connection that stays stalled beyond the send timeout. This keeps producer memory bounded and lets the application stop work when the client disconnects.

The Swoole server also gives each request its own context. Coroutine requests use coroutine-local context, while non-coroutine requests use a temporary worker context that is cleared after the callback. Runtime and server metrics are exposed through the configured telemetry adapter so the surrounding service can observe worker, coroutine, connection, memory, and scheduler state.

References: packages/…/Response.php• L601-672 packages/…/Response.php• L697-797 packages/…/Response.php• L19-190 packages/…/Server.php• L81-145 packages/…/Server.php• L152-235

Upload streams

Request bodies can come from streams or file-backed multipart parts. The transport reads these bodies as needed instead of requiring the whole payload in memory. A known body size can produce a content length; an unknown size uses chunked transfer where the transport supports it.

File parts stay bounded on both adapters. Raw file-backed bodies stream through cURL, while Swoole uses its native multipart upload path for supported multipart shapes. A raw body on Swoole can be buffered, so multipart file parts are the portable choice for large Swoole uploads.

Seekable request bodies can be rewound before a retry or a redirect that preserves the method. A non-seekable body cannot safely be replayed after the transport has consumed it.

References: packages/…/streaming.md• L51-71 packages/…/streaming.md• L73-102 packages/…/Client.php• L317-345 packages/…/Client.php• L348-380 packages/…/Client.php• L776-845

Exception model

Response and exception outcomes

The client has two top-level outcomes: a usable response or a PSR-18 client exception. HTTP status codes are data, not transport failure, so a 4xx or 5xx response is returned for the caller to inspect. An exception means that no usable response was produced.

Every client exception carries the request that failed. Code that only needs a retry or handling decision should catch the PSR interfaces instead of transport-specific classes.

References: packages/…/error-handling.md• L3-20 packages/…/NetworkException.php• L12-27 packages/…/RequestException.php• L12-27 packages/…/Client.php• L376-447 packages/…/Client.php• L633-709

Exception branches

The exception hierarchy separates a bad request or unusable response from a transport failure. This distinction tells retry logic whether another attempt could help.

BranchMeaningExamples
RequestExceptionInterfaceThe request is invalid or the response cannot be parsedInvalid URI, missing adapter precondition, adapter setup failure, malformed response
NetworkExceptionInterfaceThe request could not complete because of the networkDNS, timeout, connection, proxy, protocol, or TLS failure

More specific classes such as TlsException retain their broad PSR interface, so callers can choose either precise handling or portable handling. When catching concrete classes, catch a specific subclass before its parent.

References: packages/…/error-handling.md• L45-67 packages/…/ExceptionTest.php• L23-43 packages/…/TlsException.php• L7-9

Package relationships

The HTTP client consumes the PSR-7 HTTP message primitives for request, response, URI, and stream values. It can use the connection pools library to limit concurrent upstream work and share configured clients. Retry behavior can also sit beside the circuit breaker library when an application needs both repeated-attempt control and upstream health protection. The reusable platform packages page places these packages in the wider platform map.

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep both adapters aligned with the Adapter contract for shared timeout, TLS, reuse, redirect, buffered, and streaming behavior.
  • Keep redirect URI resolution aligned with method changes, body rewind rules, hop limits, and sensitive-header stripping.
  • Keep retry strategy outcomes aligned with the PSR exception branches and with the rule that streamed bytes cannot be replayed.
  • Keep pooled clients configured in the pool factory so reuse, base URI, headers, authentication, retry policy, and trace propagation apply to every borrowed client.
  • Keep decoded response headers consistent with the body bytes when compression negotiation changes.
  • Keep TLS host identity checks aligned with each redirect hop and each reused connection origin.
  • Keep the PSR-18 response-versus-exception boundary intact when transport error mapping changes.
  • Keep trace propagation opt-in and do not overwrite a request trace context supplied by the caller.
  • Keep Swoole server writes bounded by the connection queue and preserve the disconnect and stall timeout outcomes.
  • Keep response compression headers and incremental encoder state aligned across send(), chunk(), and stream().
  • Keep request context isolated between coroutine and non-coroutine Swoole requests.
  • Keep worker-scoped and server-scoped Swoole telemetry emitted at the correct scope.

Important failure modes

TriggerConsequenceGuard
Swoole request runs outside a coroutineThe adapter cannot perform the requestRun the Swoole client and its pool inside a coroutine
Redirect changes origin or downgrades HTTPS to HTTPSensitive credentials are removed from the next requestTreat cross-origin redirects as a new trust boundary
A retry begins after stream bytes reach the sinkA second attempt could duplicate dataStop retrying after the first delivered byte
A large raw body uses the Swoole adapterThe body can be buffered instead of streamedUse a file-backed multipart part for bounded uploads
TLS verification is disabled to trust a private certificateCertificate and host checks are bypassedInstall or pass the private CA and keep verification enabled
A request uses a verified HTTPS IP literal with SwooleThe adapter raises a TLS exception before sendingUse a DNS name matching the certificate or use cURL
A reused connection belongs to another originThe transport must establish a new connectionTreat reuse as origin-scoped rather than global
Trace propagation is enabled without an active spanNo traceparent header is addedStart a span before the outbound request when trace context is required
A Swoole client stops reading while the server keeps writingQueued response bytes can grow until memory pressure or disconnectLet the response drain the connection queue and close stalled clients
A Swoole response is sent after its connection has been replacedWrites can target a different session or fail unpredictablyBind queue checks to the connection identity observed by the response
A streamed response uses an unsupported incremental encodingThe body is sent without that encodingNegotiate only encodings with a supported incremental encoder
Non-coroutine request context is not clearedData from one request can be visible to a later requestClear the worker context in the request cleanup path

Key files

FileWhy to read it
packages/…/README.mdPackage purpose, public entry points, and normal client usage
packages/…/Adapter.phpShared contract for transports and decorators
packages/…/Client.phpRequest preparation, trace propagation, and transport-neutral client configuration
packages/…/Decorator.phpComposition boundary for retry and other adapter behavior
packages/…/Client.phpcURL lifecycle, buffering, streaming, and error mapping
packages/…/Client.phpCoroutine lifecycle, native streaming, redirects, and origin reuse
packages/…/Redirect.phpShared redirect resolution and credential boundary
packages/…/Retry.phpRetry loop and the stream replay boundary
packages/…/Backoff.phpDefault retry safety and delay policy
packages/…/Pool.phpBorrow-and-release behavior for pooled HTTP clients
packages/…/StreamingClientInterface.phpStreaming response contract
packages/client/src/Exception/PSR-18 exception branches and transport-specific failure types
packages/…/configuration.mdShared settings, TLS behavior, reuse, redirects, and adapter choices
packages/…/streaming.mdResponse and upload streaming limits
packages/…/error-handling.mdException meaning and handling choices
packages/…/Response.phpShared server response lifecycle, compression, and chunked output
packages/…/Response.phpSwoole response writes, queue backpressure, disconnects, and aborts
packages/…/Server.phpSwoole request context and runtime telemetry boundary