Core API

    Core Messages and Errors

    HTTP.RequestType
    Request(method, target; headers=Headers(), trailers=Headers(), body=EmptyBody(), host=nothing,
            content_length=-1, proto_major=1, proto_minor=1, close=false,
            context=RequestContext())

    HTTP request object shared by the client and server stacks.

    Keyword arguments:

    • headers, trailers: copied into the request.
    • body: any AbstractBody; ownership stays with the request.
    • host: optional authority used for HTTP/1 Host and HTTP/2 :authority.
    • content_length: exact byte length, or -1 when unknown.
    • proto_major, proto_minor: protocol version metadata.
    • close: request/connection-close hint.
    • context: cancellation/deadline metadata consulted by higher layers.

    Returns a new Request{B} where B is the concrete body type. Throws ArgumentError for invalid protocol numbers, empty method/target, or content_length < -1.

    For migration from HTTP.jl 1.x, common positional forms such as Request(method, target, headers) and Request(method, target, headers, body) are still accepted. New code should use the keyword form above so body, trailers, protocol metadata, and context ownership are explicit.

    source
    HTTP.ResponseType
    Response(status, body=EmptyBody(); reason="", headers=Headers(), trailers=Headers(),
             content_length=-1, proto_major=1, proto_minor=1, close=false,
             request=nothing)

    HTTP response object shared by the client and server stacks.

    Keyword arguments mirror Request closely. request optionally links the response back to the originating request, which is especially useful in client redirect flows and server handler pipelines.

    Returns a new Response{B} where B is the exact body field type. The optional body positional argument determines the response body type for dispatch and storage. request_url is optional client metadata used by high-level request helpers.

    Throws ArgumentError for invalid status or protocol metadata.

    For migration from HTTP.jl 1.x, common forms such as Response(status, headers, body) and Response(status, headers; body=...) are still accepted. New code should prefer Response(status; headers=..., body=..., content_length=...).

    source
    HTTP.HeadersType
    Headers

    Ordered, case-canonicalized collection of header pairs.

    Headers deliberately behaves like Vector{Pair{String, String}} so code written against the long-standing pair-vector header representation can reuse the same helper functions. Keys are canonicalized on insertion, but pair order is preserved.

    source
    HTTP.RequestContextType
    RequestContext(; deadline_ns=0)

    Per-request cancellation, deadline, timeout, and metadata state shared across client, server, middleware, and transport code.

    Arguments:

    • deadline_ns: absolute monotonic deadline in nanoseconds, or 0 to disable deadline tracking.

    The context itself does not schedule timers; it is a passive state container that HTTP.jl consults before or during blocking operations. For migration from HTTP.jl 1.x, RequestContext also supports dict-like metadata access with symbol keys:

    ctx = HTTP.RequestContext()
    ctx[:request_id] = "abc"
    get(ctx, :request_id, nothing)

    New code should prefer typed fields and helper functions for cancellation and deadlines, and reserve dict-like access for application metadata.

    source
    HTTP.HTTPErrorType
    HTTPError

    Abstract supertype for HTTP-specific exceptions raised by HTTP.jl.

    source
    HTTP.ParseErrorType
    ParseError

    Raised when byte-level HTTP syntax cannot be parsed. This is used for malformed request/status lines, invalid header syntax, truncated framed bodies, and other wire-format failures where the peer did not send valid HTTP.

    source
    HTTP.ProtocolErrorType
    ProtocolError

    Raised when the bytes are syntactically valid but violate higher-level HTTP rules. Examples include mismatched Content-Length values, impossible frame ordering, or unsupported control-flow states in the client/server stacks.

    source
    HTTP.CanceledErrorType
    CanceledError

    Raised when request processing is canceled explicitly through RequestContext. Unlike ParseError and ProtocolError, this usually reflects local control flow rather than a bad peer.

    source
    HTTP.TimeoutErrorType
    TimeoutError

    Raised when an HTTP-layer deadline expires. This is intentionally separate from lower-level socket timeout exceptions so higher layers can distinguish "request context expired" from transport-specific readiness or handshake failures.

    Fields:

    • operation::String — short label identifying which deadline fired. Common values are "connect", "tls_handshake", "request", "response_header", "read_idle", "write_idle", and "expect_continue".
    • timeout_ns::Int64 — the budget that fired, in nanoseconds. 0 means the budget was unknown at the wrap site.
    • elapsed_ns::Int64 — best-effort elapsed time when the deadline fired, in nanoseconds. 0 means the elapsed time is unknown at the wrap site.
    source
    HTTP.StatusErrorType
    StatusError

    Raised when status_exception=true and the response status indicates failure.

    Fields:

    • status::Int16 — the response status code (mirrors response.status for convenience so catch sites can write err.status instead of err.response.status).
    • response::Response — the full response that triggered the error.
    source
    HTTP.TooManyRedirectsErrorType
    TooManyRedirectsError

    Raised when redirect following is enabled and the client exceeds the configured redirect limit. The final redirect response is attached for inspection.

    source
    HTTP.ConnectErrorType
    ConnectError(address, cause)

    Raised when a low-level connect attempt fails before any HTTP exchange begins. address records the target the client tried to reach (host:port) and cause is the underlying transport exception. This wraps Reseau-internal types like HostResolvers.OpError so callers can pattern-match on HTTP.ConnectError without depending on Reseau internals.

    source
    HTTP.DNSErrorType
    DNSError(hostname, cause)

    Raised when host resolution fails before any connect attempt. hostname is the name that could not be resolved and cause is the underlying transport exception (typically Reseau.HostResolvers.LookupError).

    source
    HTTP.AddressInUseErrorType
    AddressInUseError(address)

    Raised when a server cannot bind because the requested address is already in use. address records the bind target (host:port).

    source

    Header and Context Helpers

    HTTP.canonical_header_keyFunction
    canonical_header_key(key) -> String

    Canonicalize a header field name into standard MIME-style form: the first character and every character after - is uppercased; other ASCII letters are lowercased.

    Returns a newly owned String unless key is already in canonical form, in which case a cached common-header string may be reused. This function does not validate that key is a legal HTTP token; callers are still responsible for protocol validation where needed.

    source
    HTTP.headerFunction

    Return the first value for key, or default if the header is absent.

    source
    HTTP.headersFunction
    headers(headers, key) -> Vector{String}

    Return a freshly allocated vector containing all values for key in stored order. Returns String[] when the header is absent.

    source
    HTTP.hasheaderFunction

    Return true when the first value for key is non-empty.

    source
    hasheader(headers, key, value) -> Bool

    Return true when any stored header value for key matches value case-insensitively.

    source
    HTTP.headercontainsFunction
    headercontains(headers, key, token) -> Bool

    Return true when a comma-separated header field contains token case-insensitively after trimming optional whitespace.

    This is the helper used for semantics like Connection: close and Transfer-Encoding: chunked, where RFCs define one header line as a list of tokens rather than one opaque string.

    source
    HTTP.setheaderFunction
    setheader(headers, key => value) -> Headers
    setheader(headers, key, value) -> Headers

    Replace all stored values for key with value, preserving the first matching position if the key already exists and appending it otherwise. Returns the mutated headers.

    source
    setheader(stream, key, value) -> nothing
    setheader(stream, key => value) -> nothing

    Set a response header for a server-side Stream before response writing starts.

    source
    HTTP.defaultheader!Function
    defaultheader!(headers, key => value) -> Headers
    defaultheader!(message, key => value) -> typeof(message)

    Append key => value only when key is not already present.

    This is useful for applying defaults like User-Agent or Accept-Encoding without overwriting caller-specified headers.

    source
    HTTP.appendheaderFunction
    appendheader(headers, key => value) -> Headers
    appendheader(headers, key, value) -> Headers

    Append a header value to headers.

    If the previous stored header has the same name and the key is not Set-Cookie, the value is merged into the previous entry with a comma. Otherwise a new pair is appended.

    source
    HTTP.removeheaderFunction
    removeheader(headers, key) -> Headers

    Remove every stored header for key and return the mutated headers.

    source
    HTTP.mkheadersFunction
    mkheaders(headers_input) -> Headers

    Normalize a header-like input into a mutable Headers collection.

    headers_input may be nothing, an existing Headers, a dictionary, or an iterable of Pairs/2-tuples. Vector-valued entries are expanded into repeated header values using the same merge rules as appendheader.

    source
    HTTP.get_request_contextFunction
    get_request_context(request) -> RequestContext

    Return the typed request context stored on request.

    Use this helper when middleware or low-level code needs cancellation, deadline, or timeout state. The legacy request.context property returns the dict-like metadata view for compatibility with HTTP.jl 1.x code.

    source
    HTTP.set_deadline!Function
    set_deadline!(ctx, deadline_ns) -> RequestContext

    Set an absolute monotonic deadline in nanoseconds. Passing 0 clears any deadline. Throws ArgumentError when deadline_ns < 0.

    source
    HTTP.cancel!Function
    cancel!(ctx; message="request canceled") -> RequestContext

    Mark ctx canceled and store a human-readable message for higher layers. This does not throw on its own; callers typically check canceled(ctx) or turn the state into a CanceledError.

    source
    HTTP.expiredFunction
    expired(ctx, now_ns=time_ns()) -> Bool

    Return true when ctx.deadline_ns is non-zero and less than or equal to now_ns. now_ns is injectable so tests and higher-level schedulers can reuse an already-sampled monotonic timestamp.

    source

    Body Types and Streamed Payloads

    HTTP.AbstractBodyType
    AbstractBody

    Abstract streaming body interface used throughout the HTTP stack.

    Concrete subtypes are expected to implement:

    • body_read!(body, dst)::Int
    • body_close!(body)
    • body_closed(body)::Bool

    body_read! must return the number of bytes written into dst, with 0 signaling EOF. Implementations may throw transport-specific exceptions.

    source
    HTTP.CallbackBodyType
    CallbackBody(read_cb, close_cb)

    Callback-driven streaming body. read_cb(dst) must return the number of bytes written into dst, and close_cb() is invoked once when the body is closed. This is the escape hatch for non-buffered request or response bodies.

    source
    HTTP.nobodyConstant

    Shared empty byte-vector payload used for responses with no buffered body.

    source
    HTTP.body_read!Function
    body_read!(body, dst) -> Int

    Read up to length(dst) bytes into dst. Returns 0 on EOF.

    Concrete body types may throw ProtocolError, transport errors, or body- specific exceptions if the stream is malformed or the backing connection fails.

    source
    HTTP.body_close!Function
    body_close!(body)

    Release any resources held by body. Implementations should be idempotent so callers can safely close in finally blocks.

    source
    HTTP.body_closedFunction
    body_closed(body) -> Bool

    Return true once body has been fully consumed or explicitly closed.

    For immutable in-memory bodies this tracks whether the read cursor reached EOF; for streaming bodies it reports whether the underlying producer has been closed.

    source
    HTTP.read_requestFunction
    read_request(io; max_line_bytes=..., max_header_bytes=...)

    Parse one HTTP/1 request from io.

    Returns a Request whose body is one of EmptyBody, FixedLengthBody, or ChunkedBody depending on the incoming framing headers.

    Throws:

    • ArgumentError for invalid parser limits
    • ParseError for malformed syntax or truncated framed bodies
    • ProtocolError for invalid semantic combinations such as conflicting length metadata
    • any exception propagated by the underlying IO
    source
    HTTP.write_request!Function
    write_request!(io, request)

    Serialize an HTTP/1 request to io, including body framing.

    Behavior:

    • injects Host from request.host when missing
    • normalizes connection-close signaling
    • chooses between Content-Length and chunked transfer-coding
    • serializes trailers only for chunked bodies

    Returns nothing. May throw ProtocolError for inconsistent framing or propagate exceptions from io and the request body.

    source
    HTTP.write_response!Function
    write_response!(io, response)

    Serialize an HTTP/1 response to io, including body framing.

    Body suppression rules for status codes like 1xx, 204, and 304 are enforced here so callers can hand the function a regular Response object and let the serializer apply wire-level HTTP/1 rules.

    source
    HTTP.trailersFunction
    trailers(body)

    Return parsed trailer headers for a chunked body; empty headers for other body types.

    The returned Headers object is copied so callers can inspect or mutate it without racing the body reader.

    source

    Cookies, Forms, and Request Bodies

    HTTP.Cookies.CookieType
    Cookie

    HTTP cookie model used for both request Cookie headers and response Set-Cookie headers.

    Construct a cookie with Cookie(name, value; kwargs...) and mutate additional fields such as path, domain, secure, or httponly when needed.

    source
    HTTP.Cookies.CookieJarType
    CookieJar()

    Create an in-memory cookie jar suitable for attaching to Client.

    The jar applies standard domain/path/expiry rules when storing cookies from responses and when selecting cookies for future requests.

    source
    HTTP.Cookies.cookiesFunction
    cookies(request_or_response) -> Vector{Cookie}

    Parse cookies from a request Cookie header or response Set-Cookie headers.

    source
    HTTP.Cookies.stringifyFunction
    stringify(cookie, isrequest=true) -> String
    stringify(prefix, cookies, isrequest=true) -> String

    Serialize cookies back to HTTP header text.

    When isrequest=true, the output matches a request Cookie header. When false, response-only attributes such as Path, Domain, and HttpOnly are included for Set-Cookie serialization.

    source
    HTTP.Cookies.getcookies!Function
    getcookies!(jar, scheme, host, path[, now]) -> Vector{Cookie}

    Return the cookies from jar that should be attached to a request for scheme://host/path.

    source
    HTTP.Cookies.setcookies!Function
    setcookies!(jar, scheme, host, path, headers) -> Nothing

    Update jar from response headers received for scheme://host/path.

    source
    HTTP.Cookies.addcookie!Function
    addcookie!(message, cookie) -> typeof(message)

    Append cookie to a request or response message in the appropriate header slot.

    source
    HTTP.FormType
    Form(parts; boundary=_default_form_boundary()) <: IO

    Streaming multipart/form-data request body assembled from name => value pairs.

    Values may be ordinary data or IO objects. Use content_type to populate the corresponding Content-Type request header.

    source
    HTTP.MultipartType
    Multipart(filename, data, contenttype="", contenttransferencoding="", name="") <: IO

    One parsed or programmatically constructed multipart body part.

    source
    HTTP.content_typeFunction
    content_type(form) -> String

    Return the multipart/form-data content type header for form, including its generated boundary.

    source
    HTTP.parse_multipart_formFunction
    parse_multipart_form(content_type_header, body) -> Union{Vector{Multipart}, Nothing}
    parse_multipart_form(request) -> Union{Vector{Multipart}, Nothing}

    Parse a multipart/form-data payload using the boundary from content_type_header.

    The Request overload reads the Content-Type header and request body bytes out of the incoming request — use it from inside an HTTP.serve! handler to inspect file uploads and form fields without re-implementing the header/body extraction.

    Returns nothing when either input is missing or the content type is not a multipart form body.

    source

    Proxy Configuration

    HTTP.ProxyConfigType
    ProxyConfig(url; no_proxy=nothing)
    ProxyConfig(; http=nothing, https=nothing, all=nothing, no_proxy=nothing, env=false)

    HTTP client proxy configuration.

    Use this to route plain HTTP, HTTPS, or all traffic through explicit proxy targets, optionally with NoProxy exclusions or environment-driven defaults.

    source
    HTTP.ProxyURLFunction
    ProxyURL(url; no_proxy=nothing) -> ProxyConfig

    Convenience constructor for a single proxy URL applied to all outbound requests.

    source
    HTTP.ProxyFromEnvironmentFunction
    ProxyFromEnvironment() -> ProxyConfig

    Load proxy configuration from the standard HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and NO_PROXY environment variables.

    source
    HTTP.NoProxyType
    NoProxy(spec)
    NoProxy()

    Matcher for NO_PROXY-style bypass rules.

    spec may be a comma-separated string or vector-like collection containing hostnames, domain suffixes, IP literals, CIDR ranges, or host:port entries.

    source