Core API
Core Messages and Errors
HTTP.Request — Type
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: anyAbstractBody; ownership stays with the request.host: optional authority used for HTTP/1Hostand HTTP/2:authority.content_length: exact byte length, or-1when 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.
HTTP.Response — Type
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=...).
HTTP.Headers — Type
HeadersOrdered, 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.
HTTP.RequestContext — Type
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, or0to 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.
HTTP.HTTPError — Type
HTTPErrorAbstract supertype for HTTP-specific exceptions raised by HTTP.jl.
HTTP.ParseError — Type
ParseErrorRaised 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.
HTTP.ProtocolError — Type
ProtocolErrorRaised 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.
HTTP.CanceledError — Type
CanceledErrorRaised when request processing is canceled explicitly through RequestContext. Unlike ParseError and ProtocolError, this usually reflects local control flow rather than a bad peer.
HTTP.TimeoutError — Type
TimeoutErrorRaised 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.0means the budget was unknown at the wrap site.elapsed_ns::Int64— best-effort elapsed time when the deadline fired, in nanoseconds.0means the elapsed time is unknown at the wrap site.
HTTP.HTTPTimeoutError — Type
HTTPTimeoutErrorPublic alias for TimeoutError, kept so code can catch timeout failures through the long-form HTTP-specific name.
HTTP.StatusError — Type
StatusErrorRaised when status_exception=true and the response status indicates failure.
Fields:
status::Int16— the response status code (mirrorsresponse.statusfor convenience so catch sites can writeerr.statusinstead oferr.response.status).response::Response— the full response that triggered the error.
HTTP.TooManyRedirectsError — Type
TooManyRedirectsErrorRaised when redirect following is enabled and the client exceeds the configured redirect limit. The final redirect response is attached for inspection.
HTTP.ConnectError — Type
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.
HTTP.DNSError — Type
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).
HTTP.TLSHandshakeError — Type
TLSHandshakeError(cause)Raised when a TLS handshake fails (other than a handshake timeout, which surfaces as TimeoutError with operation = "tls_handshake").
HTTP.AddressInUseError — Type
AddressInUseError(address)Raised when a server cannot bind because the requested address is already in use. address records the bind target (host:port).
Header and Context Helpers
HTTP.canonical_header_key — Function
canonical_header_key(key) -> StringCanonicalize 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.
HTTP.header — Function
Return the first value for key, or default if the header is absent.
HTTP.headers — Function
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.
HTTP.hasheader — Function
Return true when the first value for key is non-empty.
hasheader(headers, key, value) -> BoolReturn true when any stored header value for key matches value case-insensitively.
HTTP.headercontains — Function
headercontains(headers, key, token) -> BoolReturn 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.
HTTP.setheader — Function
setheader(headers, key => value) -> Headers
setheader(headers, key, value) -> HeadersReplace 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.
setheader(stream, key, value) -> nothing
setheader(stream, key => value) -> nothingSet a response header for a server-side Stream before response writing starts.
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.
HTTP.appendheader — Function
appendheader(headers, key => value) -> Headers
appendheader(headers, key, value) -> HeadersAppend 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.
HTTP.removeheader — Function
removeheader(headers, key) -> HeadersRemove every stored header for key and return the mutated headers.
HTTP.mkheaders — Function
mkheaders(headers_input) -> HeadersNormalize 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.
HTTP.get_request_context — Function
get_request_context(request) -> RequestContextReturn 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.
HTTP.set_deadline! — Function
set_deadline!(ctx, deadline_ns) -> RequestContextSet an absolute monotonic deadline in nanoseconds. Passing 0 clears any deadline. Throws ArgumentError when deadline_ns < 0.
HTTP.cancel! — Function
cancel!(ctx; message="request canceled") -> RequestContextMark 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.
HTTP.canceled — Function
Return true once cancel! has been called for ctx.
HTTP.expired — Function
expired(ctx, now_ns=time_ns()) -> BoolReturn 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.
Body Types and Streamed Payloads
HTTP.AbstractBody — Type
AbstractBodyAbstract streaming body interface used throughout the HTTP stack.
Concrete subtypes are expected to implement:
body_read!(body, dst)::Intbody_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.
HTTP.CallbackBody — Type
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.
HTTP.nobody — Constant
Shared empty byte-vector payload used for responses with no buffered body.
HTTP.body_read! — Function
body_read!(body, dst) -> IntRead 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.
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.
HTTP.body_closed — Function
body_closed(body) -> BoolReturn 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.
HTTP.read_request — Function
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:
ArgumentErrorfor invalid parser limitsParseErrorfor malformed syntax or truncated framed bodiesProtocolErrorfor invalid semantic combinations such as conflicting length metadata- any exception propagated by the underlying
IO
HTTP.write_request! — Function
write_request!(io, request)Serialize an HTTP/1 request to io, including body framing.
Behavior:
- injects
Hostfromrequest.hostwhen missing - normalizes connection-close signaling
- chooses between
Content-Lengthand 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.
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.
HTTP.trailers — Function
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.
Cookies, Forms, and Request Bodies
HTTP.Cookies.Cookie — Type
CookieHTTP 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.
HTTP.Cookies.CookieJar — Type
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.
HTTP.Cookies.cookies — Function
cookies(request_or_response) -> Vector{Cookie}Parse cookies from a request Cookie header or response Set-Cookie headers.
HTTP.Cookies.stringify — Function
stringify(cookie, isrequest=true) -> String
stringify(prefix, cookies, isrequest=true) -> StringSerialize 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.
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.
HTTP.Cookies.setcookies! — Function
setcookies!(jar, scheme, host, path, headers) -> NothingUpdate jar from response headers received for scheme://host/path.
HTTP.Cookies.addcookie! — Function
addcookie!(message, cookie) -> typeof(message)Append cookie to a request or response message in the appropriate header slot.
HTTP.Form — Type
Form(parts; boundary=_default_form_boundary()) <: IOStreaming 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.
HTTP.Multipart — Type
Multipart(filename, data, contenttype="", contenttransferencoding="", name="") <: IOOne parsed or programmatically constructed multipart body part.
HTTP.content_type — Function
content_type(form) -> StringReturn the multipart/form-data content type header for form, including its generated boundary.
HTTP.parse_multipart_form — Function
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.
Proxy Configuration
HTTP.ProxyConfig — Type
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.
HTTP.ProxyURL — Function
ProxyURL(url; no_proxy=nothing) -> ProxyConfigConvenience constructor for a single proxy URL applied to all outbound requests.
HTTP.ProxyFromEnvironment — Function
ProxyFromEnvironment() -> ProxyConfigLoad proxy configuration from the standard HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and NO_PROXY environment variables.
HTTP.NoProxy — Type
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.