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 / psr7-http-primitives

PSR-7 HTTP message primitives

The PSR-7 HTTP message primitives package gives PHP code a shared model for HTTP requests, server requests, responses, bodies, URIs, headers, and uploaded files. It implements PSR-7 message interfaces and PSR-17 factories so clients, servers, transports, and adapters can exchange the same message values without depending on one transport. See the reusable platform packages page for the wider package map.

Package role

The package is a low-level boundary between HTTP data and application code. It turns common payload types into PSR-7 messages, keeps message changes isolated through immutable with* operations, and offers helpers for reading structured response bodies.

The main relationships are:

  • Request and ServerRequest carry method, URI, headers, body, and request context.
  • Response carries status, headers, and body and can decode common response formats.
  • Stream represents message bytes and can wrap in-memory content, files, or resources.
  • Uri, UploadedFile, and multipart values model common HTTP parts.
  • PSR-17 factories create these values through standard interfaces.

Message model

Message state

Message provides the shared PSR-7 state for a protocol version, case-insensitive headers, and a StreamInterface body. Header names keep the spelling used when they are added, while lookups do not depend on case. withHeader, withAddedHeader, withoutHeader, withBody, and withProtocolVersion return a changed message and leave the original message unchanged.

The body is a stream rather than a plain string. This lets a caller pass the same message shape to a transport whether the content is small, comes from a resource, or must be read in chunks.

References: packages/…/Message.php• L11-23 packages/…/Message.php• L25-35 packages/…/Message.php• L38-133

Request messages

Client requests

Request models an outgoing HTTP request with a method, target URI, headers, and body. Its request target comes from the URI path and query. When the URI has a host, changing the URI also sets Host unless the caller asks to preserve an existing non-empty host value.

The request factory provides the usual body forms for client code:

Request formBody and headers
JSONEncoded JSON with application/json and a default JSON Accept header
FormRFC-style query encoding with application/x-www-form-urlencoded
TextPlain text with text/plain
XMLCaller-supplied XML with application/xml
Raw bodyCaller-supplied bytes and content type
QueryParameters added to the URI without creating a body
MultipartForm fields and file or body parts with a generated boundary

Caller headers take precedence for typed request bodies. Multipart requests are different: the factory creates the body and then writes its generated boundary into Content-Type, so the header always describes the actual body.

References: packages/…/Request.php• L11-69 packages/…/Factory.php• L29-141 packages/…/FactoryTest.php• L16-123

Server requests

ServerRequest extends the request model with data that a server gathers around an incoming message. It carries server parameters, cookies, query parameters, parsed body data, uploaded files, and application attributes. Attributes provide a place for routing or middleware data without changing the wire request.

Server requests accept uploaded files as a tree of UploadedFileInterface values. The tree can mirror nested form fields, but arbitrary values are rejected. All server-request changes remain immutable, including changes to query data, parsed data, cookies, files, and attributes.

References: packages/…/ServerRequest.php• L13-41 packages/…/ServerRequest.php• L100-217 packages/…/ServerRequest.php• L230-268

Response messages

Response state

Response models an HTTP result with a status code, reason phrase, headers, and body. It accepts only status codes from 100 through 599. The contentType() helper returns a lower-case media type without parameters, which gives callers a simple value for format selection.

Response bodies can be read through format-specific helpers:

  • json() decodes JSON and reports decode errors.
  • text() returns the body as a string.
  • xml() parses XML and rejects invalid XML.
  • form() parses URL-encoded form data.
  • multipart() returns structured response parts.

These helpers read the body through the same stream used by the transport. They do not change the response status or headers.

References: packages/…/Response.php• L15-123 packages/…/ResponseTest.php• L14-85

Multipart responses

Response::multipart() turns a boundary-delimited response body into an ordered list of response parts. Each Response\Multipart\Part exposes part headers, body text, content type, form name, and filename. Repeated field names stay as separate parts, so callers can preserve the order and multiplicity sent by the peer.

The response Content-Type must include a boundary. The parser recognizes quoted or unquoted boundaries and ignores preamble and epilogue text. A response without a boundary cannot be split into parts and raises an argument error.

References: packages/…/Response.php• L104-223 packages/…/Part.php• L7-84 packages/…/ResponseTest.php• L87-212

Stream values

Message streams

Stream is the package's PSR-7 stream value for readable and writable bytes. It starts with a temporary stream for string content and can also wrap an existing PHP resource. The stream supports seeking, rewinding, size checks, metadata, detaching, and closing.

Resource-backed streams let callers keep large content outside a copied string. A detached or closed stream no longer provides read, write, or seek operations, so ownership of a detached resource moves to the caller.

References: packages/…/Stream.php• L11-45 packages/…/Stream.php• L48-77 packages/…/Stream.php• L80-187 packages/…/FactoriesTest.php• L50-77

URI values

URI components

Uri is a PSR-7 URI value for scheme, user information, host, port, path, query, and fragment. Uri::parse() creates it from a string, and with* methods return a new URI with one component changed. String conversion rebuilds the complete URI with encoded path, query, and fragment data. It also keeps authority-based paths valid by adding a leading slash when needed and prevents an authority-less path from becoming an unintended network-path reference.

Default HTTP and HTTPS ports are omitted from the authority and returned as no explicit port. This keeps equivalent default-port URIs in a stable form while retaining non-default ports for request routing and the Host header.

References: packages/…/Uri.php• L10-45 packages/…/Uri.php• L48-165 packages/…/Uri.php• L168-190 packages/…/MessageTest.php• L47-87

Header vocabulary

Protocol constants

Method, Header, and ContentType provide shared names for common HTTP methods, header fields, and media types. They reduce spelling drift at call sites while the message model still permits other valid methods, headers, and content types.

The constants are vocabulary only. Header storage and validation remain the responsibility of Message, while request factories use content-type constants to describe generated bodies.

References: packages/…/Method.php• L7-29 packages/…/Header.php• L7-52 packages/…/ContentType.php• L7-30 packages/…/ConstantsTest.php• L12-47

Uploaded files

Uploaded file lifecycle

UploadedFile adapts a PHP upload record to UploadedFileInterface. It exposes the upload size, error, client filename, and client media type. The file stream opens when requested, while moveTo() transfers the file to a target path.

An uploaded file has a one-way move state. A file with an upload error cannot be read or moved, and a file that was moved cannot be read or moved again. normalizeFiles() converts nested PHP upload arrays into the same tree of uploaded-file values accepted by ServerRequest.

References: packages/…/UploadedFile.php• L12-45 packages/…/UploadedFile.php• L48-114 packages/…/UploadedFile.php• L116-190 packages/…/ServerRequestTest.php• L54-66

PSR-17 factories

Factory interfaces

The factory classes implement PSR-17 interfaces for URI, stream, request, server request, and response creation. They give framework or transport code a standard construction seam and allow a caller to provide a different URI or stream factory to request creation.

The request factory adds higher-level payload helpers on top of the standard createRequest() method. The other factories stay focused on creating one primitive kind:

FactoryMain responsibility
Uri\FactoryParse a string into a URI
Stream\FactoryCreate streams from strings, files, and resources
Request\FactoryCreate client requests and common payload forms
ServerRequest\FactoryCreate incoming-request values with server parameters
Response\FactoryCreate status-bearing responses

References: packages/…/Factory.php• L11-17 packages/…/Factory.php• L12-33 packages/…/Factory.php• L21-35 packages/…/Factory.php• L14-30 packages/…/Factory.php• L11-16 packages/…/FactoriesTest.php• L17-48

Multipart payloads

Request multipart bodies

Request multipart support represents a multipart/form-data upload as named parts and a boundary-aware body. A Request\Multipart\Part can be a normal field, in-memory body, or file reference. The Request\Multipart\Body combines those parts into the wire format and exposes the same boundary used in the request header.

File parts are read from disk as the body is consumed. This allows a transport to send large files without first building the complete multipart payload in memory. The body can be read in chunks and rewound for a retry or a second consumer, but it is read-only.

References: packages/…/Part.php• L9-101 packages/…/Body.php• L12-25 packages/…/Body.php• L37-172 packages/…/BodyTest.php• L12-56

Multipart part semantics

Multipart parts keep field names in order and support repeated names. File and body parts can add a filename, media type, and extra part headers. The body adds the standard form-data disposition and closes the message with the terminating boundary.

The multipart request flow connects the high-level factory to the transport body:

flowchart LR
    A[Fields and file parts] --> B[Request factory]
    B --> C[Generated boundary]
    C --> D[Multipart body]
    D --> E[Request Content-Type]
    D --> F[Transport reads chunks]
    E --> G[Peer parses matching boundary]

References: packages/…/Factory.php• L126-174 packages/…/Body.php• L185-241 packages/…/FactoryTest.php• L100-194

Package relationships

This package supplies the HTTP value layer used by higher-level reusable packages. The AI agent provider integration may use request and response primitives when it calls external providers. The event bus and distributed locking pages describe other shared boundaries that can use the same factory and stream conventions, but they are separate protocols with separate contracts.

Change checklist

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

  • Keep Request\Factory multipart boundary generation aligned with both Request\Multipart\Body::boundary() and the final Content-Type value.
  • Keep URI host and port rules aligned with automatic Host updates in Request and ServerRequest.
  • Keep the accepted uploaded-file tree shape aligned between UploadedFile::normalizeFiles() and server-request validation.
  • Keep response multipart boundary parsing aligned with the part delimiter rules and quoted boundary syntax.
  • Keep typed request helper defaults aligned with ContentType constants while preserving explicit caller header overrides.
  • Keep PSR-7 and PSR-17 interface compatibility aligned with the package's PHP and dependency versions.

Important failure modes

TriggerConsequenceGuard
A multipart response has no boundary parameterResponse::multipart() cannot identify part edges and throwsCheck the response Content-Type before parsing multipart data
A request changes to a new URI without preserving a valid existing hostThe request gets a Host value derived from the new URIUse the preserveHost option only when the old host is part of the request contract
A multipart file path is missing when the part is createdMultipart part creation throws instead of producing an incomplete uploadValidate the source path before building the request
An uploaded file has an upload error or was already movedReading or moving it throwsCheck the upload error and perform the move once
A stream is detached or closed before a consumer finishesRead, write, seek, or metadata calls failKeep resource ownership clear and consume the stream before detaching it
JSON or XML response content is invalidJSON decoding or XML parsing reports an errorSelect the decoder from the trusted content type and handle its exception

Key files

FileWhy to read it
packages/…/README.mdPackage purpose, install name, and a short request/response example
packages/…/Message.phpShared immutable message and header behavior
packages/…/Request.phpOutgoing request contract and URI-to-host rules
packages/…/ServerRequest.phpIncoming request context and uploaded-file tree contract
packages/…/Response.phpStatus-bearing response and body decoding behavior
packages/…/Stream.phpCommon byte-stream behavior and resource ownership
packages/…/Uri.phpURI parsing, normalization, and reconstruction
packages/…/UploadedFile.phpUpload normalization and one-way file lifecycle
packages/…/Factory.phpHigh-level request creation and payload choices
packages/…/Body.phpMultipart wire body and streamed file handling
packages/…/Part.phpStructured view of one parsed response part
packages/…/composer.jsonPSR-7, PSR-17, PHP, and optional XML dependencies