Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

http

import http

A complete HTTP stack: a client, a server, and the pieces both are built from.

The server is meant to face the internet directly. Everything that is normally the reverse proxy’s job - TLS, static files with byte ranges and conditional requests, response compression, keep-alive, request size limits, timeouts, forwarding-header handling - is here rather than assumed to be somewhere in front.

Making a request

import http

echo http.get('https://example.com').as_text()

The module-level get(), post(), put(), patch(), delete(), head(), options() and trace() all go through one shared client, which keeps its connections open between calls. For anything that needs its own settings - a base URL, an authorization header, a cookie jar, a custom certificate authority

  • build a client of your own:
var api = http.client('https://api.example.com', {
  headers: { 'Authorization': 'Bearer ' + token },
})

var user = api.get('/users/me').raise_for_status().as_dict()
api.post('/posts', { title: 'Hello', body: 'World' })

Serving requests

import http

var server = http.server(3000)

server.get('/', @(request, response) {
  response.html('<h1>Hello</h1>')
})

server.get('/users/:id', @(request, response) {
  response.json({ id: request.param('id') })
})

server.serve_files('/static', './public', { cache_age: 86400 })

server.listen()

Routes match literal segments, :name parameters, and a trailing catch-all, with the most specific pattern winning regardless of registration order. use() adds middleware, which runs outermost first and controls whether the rest of the chain runs at all:

server.use(@(request, response, next) {
  if request.header('x-api-key') != key {
    response.json({ error: 'unauthorized' }, 401)
    return
  }
  next()
})

Serving over TLS

var server = http.server(443, '0.0.0.0')
server.load_certs('/etc/certs/site.crt', '/etc/certs/site.key')
server.listen()

Using more than one core

listen() serves connections on the calling thread. serve() runs the same pipeline across a pool of isolates instead, one accept loop handing connections to workers:

# app.zu
import http

def setup(server) {
  server.get('/', @(request, response) {
    response.text('hello from a worker')
  })
}
# main.zu
import http
import .app

http.serve(app.setup, { port: 3000, workers: 8 })

setup runs inside each worker, so everything it reaches for has to be something an isolate can be handed. A module is not: a setup that names an imported module belongs in a module itself, which the isolate resolves by name and whose own imports are resolved again on that side.

What the module handles for you

Requests are parsed strictly: a header name with whitespace before its colon, two disagreeing Content-Length values, a Transfer-Encoding alongside a Content-Length, an obsolete folded header line - each of these is a way to make a proxy and an origin server disagree about where one message ends and the next begins, and each is refused rather than guessed at.

Bodies are decompressed on the way in and compressed on the way out, cookies are parsed and rendered per RFC 6265, dates are read in all three formats HTTP allows and written in the one it requires, and content negotiation follows the quality weights the client actually sent.

Sessions

http.session keeps per-visitor state on the server and finds it again by a cookie:

import http.session

server.use(http.session.session())

server.get('/', @(request, response) {
  var seen = request.session().get('seen', 0)

  request.session().set('seen', seen + 1)
  response.text('visit ${seen + 1}')
})

Sessions are kept in files by default, in a database through http.session.sql, or anywhere else a SessionStore can reach.

The http API

Every public name in http, wherever it is declared. Each links to the page that documents it.

NameKindSummary
http.BodyReaderclassReads a message body off a connection according to whichever of HTTP/1.1’s framings applies.
http.ByteRangeclassOne byte range asked for by a Range header, already resolved against the size of the representation.
http.ConnectionclassA buffered, message-oriented view of a connected socket.
http.ConnectionErrorclassRaised when a connection could not be established, or when an established connection failed or was closed…
http.CookieclassA single cookie, in either direction: the name/value pair a client sends back in a Cookie header, or the…
http.CookieJarclassA client-side cookie store: keeps the cookies a server set, decides which of them a later request is entitled…
http.HeadersclassAn ordered, case-insensitive, multi-value collection of HTTP header fields.
http.HttpClientclassAn HTTP client.
http.HttpErrorclassBase class for every error the http module raises.
http.HttpRequestclassAn HTTP request, in both directions.
http.HttpResponseclassAn HTTP response, in both directions: the thing a server builds and sends, and the thing a client receives…
http.HttpServerclassAn HTTP/1.1 server.
http.LoadBalancerclassBalances requests across several upstreams.
http.MultipartBuilderclassBuilds a multipart/form-data request body.
http.MultipartDataclassThe result of parsing a multipart/form-data body.
http.ProtocolErrorclassRaised when a peer sends something that isn’t a well-formed HTTP message: a broken request line or status…
http.ReverseProxyclassA reverse proxy: takes a request this server received and passes it to an upstream, then passes the…
http.RouteclassOne registered route.
http.RouterclassMatches request paths to handlers.
http.StaticFilesclassServes files from a directory, with the conditional-request, range-request and caching behaviour a browser…
http.StatusErrorclassRaised by HttpResponse.raise_for_status() when the response carries a 4xx or 5xx status.
http.TimeoutErrorclassRaised when an operation exceeded its configured deadline: a connect, a read, a write, or the total time…
http.TooLargeErrorclassRaised when a message exceeds one of the configured size limits - request line, header block, or body.
http.TooManyRedirectsErrorclassRaised by the client when a redirect chain exceeds HttpClient.max_redirects, which usually means the chain…
http.UnsupportedProtocolErrorclassRaised when a URL names a scheme this module cannot speak, or when a peer insists on a protocol version that…
http.UploadedFileclassOne file received in a multipart/form-data body.
http.WebSocketclassAn open WebSocket connection (RFC 6455).
http.body.DEFAULT_BROTLI_QUALITYconstantThe brotli quality this module compresses a response with when the caller names no quality of its own.
http.body.decode_contentfunctionReverses the content codings named in a Content-Encoding field, innermost last, as RFC 9110 §8.4 requires.
http.body.encode_chunkfunctionWraps data as a single HTTP/1.1 chunk: the size in hexadecimal, a CRLF, the data, and a CRLF.
http.body.encode_contentfunctionApplies a content coding to data.
http.body.encode_last_chunkfunctionThe terminating 0\r\n chunk plus a trailer section.
http.body.parse_chunk_sizefunctionParses a chunk-size line, ignoring any chunk extensions after the ;.
http.body.parse_content_lengthfunctionParses a Content-Length field value.
http.body.reader_forfunctionWorks out how a message’s body is framed and returns a reader for it.
http.build_query_stringfunctionEncodes parameters as an application/x-www-form-urlencoded string.
http.clientfunctionBuilds a new HttpClient.
http.cookies.format_cookie_headerfunctionRenders a dictionary of name to value as a request Cookie header value.
http.cookies.is_valid_valuefunctionWhether value can be sent as a cookie value without quoting.
http.cookies.parse_cookie_headerfunctionParses a request’s Cookie header into a dictionary of name to value.
http.cookies.parse_set_cookiefunctionParses one Set-Cookie field value into a Cookie.
http.deletefunctionSends a DELETE request through the shared client.
http.files.etag_matchesfunctionWhether an If-None-Match value matches etag.
http.files.parse_rangefunctionParses a Range header against a representation of size bytes.
http.files.weak_etagfunctionA weak validator derived from a file’s size and modification time.
http.getfunctionSends a GET request through the shared client.
http.h1.ChunkWriterclassThe writer handed to a streaming response body.
http.h1.DEFAULT_LIMITSconstant
http.h1.SERVER_NAMEconstant
http.h1.USER_AGENTconstant
http.h1.parse_versionfunctionParses HTTP/1.1 into '1.1', rejecting anything that is not a version this module understands the framing…
http.h1.read_requestfunctionReads one request off a connection: the request line, the header section, and enough framing information to…
http.h1.read_responsefunctionReads a response off a connection.
http.h1.send_continuefunctionSends a 100 Continue interim response, telling a client that asked with Expect: 100-continue to go ahead…
http.h1.should_keep_alivefunctionWhether the connection should be kept open after this exchange.
http.h1.write_requestfunctionWrites a request to a connection.
http.h1.write_responsefunctionWrites a response to a connection and returns whether the connection is still usable afterwards.
http.h2.Http2ConnectionclassAn HTTP/2 connection, in either role.
http.h2.Http2StreamclassOne HTTP/2 stream: a request and its response, multiplexed with others over a single connection.
http.h2.Http2WriterclassThe writer a streaming response body gets on an HTTP/2 connection.
http.h2.frames.CANCELconstantCANCEL.
http.h2.frames.COMPRESSION_ERRORconstantCOMPRESSION_ERROR.
http.h2.frames.CONNECT_ERRORconstantCONNECT_ERROR.
http.h2.frames.CONTINUATIONconstantCONTINUATION frame.
http.h2.frames.DATAconstantDATA frame.
http.h2.frames.ENHANCE_YOUR_CALMconstantENHANCE_YOUR_CALM.
http.h2.frames.FLAG_ACKconstantACK flag, on SETTINGS and PING.
http.h2.frames.FLAG_END_HEADERSconstantEND_HEADERS flag, on HEADERS, PUSH_PROMISE and CONTINUATION.
http.h2.frames.FLAG_END_STREAMconstantEND_STREAM flag, on DATA and HEADERS.
http.h2.frames.FLAG_PADDEDconstantPADDED flag, on DATA, HEADERS and PUSH_PROMISE.
http.h2.frames.FLAG_PRIORITYconstantPRIORITY flag, on HEADERS.
http.h2.frames.FLOW_CONTROL_ERRORconstantFLOW_CONTROL_ERROR.
http.h2.frames.FRAME_SIZE_ERRORconstantFRAME_SIZE_ERROR.
http.h2.frames.FrameclassOne frame, as read off the wire.
http.h2.frames.GOAWAYconstantGOAWAY frame.
http.h2.frames.HEADERSconstantHEADERS frame.
http.h2.frames.HTTP_1_1_REQUIREDconstantHTTP_1_1_REQUIRED.
http.h2.frames.INADEQUATE_SECURITYconstantINADEQUATE_SECURITY.
http.h2.frames.INTERNAL_ERRORconstantINTERNAL_ERROR.
http.h2.frames.NO_ERRORconstantNO_ERROR.
http.h2.frames.PINGconstantPING frame.
http.h2.frames.PREFACEconstantThe connection preface every HTTP/2 client sends before anything else.
http.h2.frames.PRIORITYconstantPRIORITY frame; deprecated by RFC 9113 and ignored here.
http.h2.frames.PROTOCOL_ERRORconstantPROTOCOL_ERROR.
http.h2.frames.PUSH_PROMISEconstantPUSH_PROMISE frame.
http.h2.frames.REFUSED_STREAMconstantREFUSED_STREAM.
http.h2.frames.RST_STREAMconstantRST_STREAM frame.
http.h2.frames.SETTINGSconstantSETTINGS frame.
http.h2.frames.SETTINGS_ENABLE_PUSHconstantSETTINGS_ENABLE_PUSH.
http.h2.frames.SETTINGS_HEADER_TABLE_SIZEconstantSETTINGS_HEADER_TABLE_SIZE.
http.h2.frames.SETTINGS_INITIAL_WINDOW_SIZEconstantSETTINGS_INITIAL_WINDOW_SIZE.
http.h2.frames.SETTINGS_MAX_CONCURRENT_STREAMSconstantSETTINGS_MAX_CONCURRENT_STREAMS.
http.h2.frames.SETTINGS_MAX_FRAME_SIZEconstantSETTINGS_MAX_FRAME_SIZE.
http.h2.frames.SETTINGS_MAX_HEADER_LIST_SIZEconstantSETTINGS_MAX_HEADER_LIST_SIZE.
http.h2.frames.SETTINGS_TIMEOUTconstantSETTINGS_TIMEOUT.
http.h2.frames.STREAM_CLOSEDconstantSTREAM_CLOSED.
http.h2.frames.WINDOW_UPDATEconstantWINDOW_UPDATE frame.
http.h2.frames.decode_settingsfunctionParses a SETTINGS payload into a dictionary.
http.h2.frames.encode_errorfunctionBuilds an RST_STREAM payload.
http.h2.frames.encode_goawayfunctionBuilds a GOAWAY payload.
http.h2.frames.encode_settingsfunctionBuilds a SETTINGS payload from a dictionary of identifier to value.
http.h2.frames.read_framefunctionReads one frame off a connection.
http.h2.frames.read_u24functionReads a 24-bit big-endian integer from data at offset.
http.h2.frames.read_u32functionReads a 32-bit big-endian integer from data at offset.
http.h2.frames.write_framefunctionWrites one frame to a connection.
http.h2.frames.write_u32functionAppends a 32-bit big-endian integer to out.
http.h2.hpack.DecoderclassDecodes header blocks for one direction of one connection.
http.h2.hpack.DynamicTableclassThe dynamic table half of an HPACK context: the most recently inserted fields, evicted from the far end when…
http.h2.hpack.EncoderclassEncodes header blocks for one direction of one connection.
http.h2.hpack.decode_integerfunctionDecodes an integer with an prefix_bits-wide prefix, starting at offset.
http.h2.hpack.decode_stringfunctionDecodes a string literal starting at offset.
http.h2.hpack.encode_integerfunctionEncodes an integer with an prefix_bits-wide prefix, per RFC 7541 §5.1.
http.h2.hpack.encode_stringfunctionEncodes a string literal, Huffman-coding it when that comes out shorter.
http.h2.huffman.EOSconstantThe number of the symbol HPACK uses to pad the final byte of a Huffman-encoded string, and which must never…
http.h2.huffman.decodefunctionDecodes a Huffman-encoded string.
http.h2.huffman.encodefunctionHuffman-encodes data, padding the final byte with the leading bits of the EOS code (which are all ones) as…
http.h2.huffman.encoded_lengthfunctionThe number of bytes data would occupy once Huffman-encoded.
http.headfunctionSends a HEAD request through the shared client.
http.headers.canonical_namefunctionThe conventional spelling of a field name, e.g. 'content-type' becomes 'Content-Type' and 'etag'…
http.headers.is_never_foldedfunctionWhether a field with this name must be repeated rather than folded into one comma-separated value when…
http.headers.is_valid_namefunctionWhether name is a syntactically valid HTTP field name, i.e. a non-empty RFC 9110 token.
http.headers.is_valid_valuefunctionWhether value is a legal HTTP field value.
http.headers.parsefunctionParses a raw header block - everything between a start line and the blank line that ends the head - into a…
http.middleware.basic_authfunctionRequires HTTP Basic authentication.
http.middleware.bearer_authfunctionRequires a bearer token.
http.middleware.corsfunctionAnswers CORS preflights and adds the cross-origin headers a browser needs before it will let script read a…
http.middleware.etagfunctionComputes a weak ETag over a finished response body and answers 304 Not Modified when the client already…
http.middleware.force_httpsfunctionSends every request that arrived over cleartext to the same URL over HTTPS.
http.middleware.jwt_authfunctionRequires a valid JSON Web Token, verified by the jwt module.
http.middleware.loggerfunctionWrites one line per request once the response is finished.
http.middleware.parse_basicfunctionParses an HTTP Basic Authorization header into a username and password.
http.middleware.parse_bearerfunctionParses a Bearer Authorization header into its token.
http.middleware.rate_limitfunctionLimits how many requests one client may make in a window of time.
http.middleware.request_idfunctionAttaches a unique identifier to every request, echoing back one the client supplied so a trace can be…
http.middleware.security_headersfunctionAdds the response headers a browser acts on to harden a page.
http.multipart.parsefunctionParses a multipart/form-data body (RFC 7578).
http.negotiate.AcceptEntryclassOne entry of an Accept-style header: the value, its quality weight, and any other parameters it carried.
http.negotiate.best_matchfunctionPicks the entry of available the client would most like, or nil when it would accept none of them.
http.negotiate.names_explicitlyfunctionWhether header names value outright rather than covering it with a wildcard.
http.negotiate.parse_acceptfunctionParses an Accept, Accept-Encoding, Accept-Language or Accept-Charset header into entries, most…
http.negotiate.preferred_encodingfunctionPicks a content coding for a response, given the request’s Accept-Encoding.
http.negotiate.preferred_languagefunctionPicks a language from available using the request’s Accept-Language.
http.negotiate.quality_offunctionThe quality weight header assigns to candidate, honouring wildcards.
http.optionsfunctionSends an OPTIONS request through the shared client.
http.parse_query_stringfunctionDecodes an application/x-www-form-urlencoded string - a query string, or a form body - into `name ->…
http.patchfunctionSends a PATCH request through the shared client.
http.postfunctionSends a POST request through the shared client.
http.putfunctionSends a PUT request through the shared client.
http.router.RouteMatchclassThe result of asking a router about a request.
http.servefunctionRuns a server across a pool of isolates, one per core by default.
http.serverfunctionBuilds an HttpServer.
http.session.FORMATconstantThe payload format this module writes and reads.
http.session.FileStoreclassKeeps each session in its own file, named after the session’s storage key.
http.session.ID_LENGTHconstantHow many characters a session identifier has.
http.session.MemoryStoreclassKeeps sessions in a dictionary, for as long as the isolate that made the store lives.
http.session.SessionclassOne visitor’s session.
http.session.SessionErrorclassRaised when a session cannot be read, written or configured: a storage directory that cannot be created or is…
http.session.SessionStoreclassWhat every session store implements.
http.session.default_directoryfunctionThe directory sessions are kept in when a FileStore is not told where to put them: a private subdirectory…
http.session.file.DIRECTORY_MODEconstant
http.session.file.FILE_MODEconstant
http.session.file.SUFFIXconstant
http.session.sessionfunctionMiddleware that finds each request’s session and writes it back when the response goes out.
http.session.sql.DEFAULT_TABLEconstant
http.session.sql.SqlStoreclassKeeps sessions in one table of a relational database.
http.session.storage_keyfunctionThe key a store files a session under: the SHA-256 of the session identifier, as 64 lowercase hex characters.
http.set_headersfunctionSets the default headers on the shared client and returns it, so a call can be chained straight onto it.
http.shared_clientfunctionThe shared client the module-level request functions use.
http.sse.EventStreamclassThe writer a server-sent event stream hands to its producer.
http.sse.last_event_idfunctionThe Last-Event-ID a reconnecting client sent, or nil.
http.sse.parsefunctionParses a text/event-stream body into a list of events, each a dictionary with event, data, id and…
http.sse.streamfunctionTurns response into a server-sent event stream and runs producer against it.
http.status.ACCEPTEDconstant202 Accepted.
http.status.ALREADY_REPORTEDconstant208 Already Reported (WebDAV, RFC 5842).
http.status.BAD_GATEWAYconstant502 Bad Gateway.
http.status.BAD_REQUESTconstant400 Bad Request.
http.status.CONFLICTconstant409 Conflict.
http.status.CONTENT_TOO_LARGEconstant413 Content Too Large.
http.status.CONTINUEconstant100 Continue.
http.status.CREATEDconstant201 Created.
http.status.EARLY_HINTSconstant103 Early Hints (RFC 8297).
http.status.EXPECTATION_FAILEDconstant417 Expectation Failed.
http.status.FAILED_DEPENDENCYconstant424 Failed Dependency (WebDAV, RFC 4918).
http.status.FORBIDDENconstant403 Forbidden.
http.status.FOUNDconstant302 Found.
http.status.GATEWAY_TIMEOUTconstant504 Gateway Timeout.
http.status.GONEconstant410 Gone.
http.status.HTTP_VERSION_NOT_SUPPORTEDconstant505 HTTP Version Not Supported.
http.status.IM_A_TEAPOTconstant418 I’m a teapot (RFC 2324).
http.status.IM_USEDconstant226 IM Used (RFC 3229).
http.status.INSUFFICIENT_STORAGEconstant507 Insufficient Storage (WebDAV, RFC 4918).
http.status.INTERNAL_SERVER_ERRORconstant500 Internal Server Error.
http.status.LENGTH_REQUIREDconstant411 Length Required.
http.status.LOCKEDconstant423 Locked (WebDAV, RFC 4918).
http.status.LOOP_DETECTEDconstant508 Loop Detected (WebDAV, RFC 5842).
http.status.METHOD_NOT_ALLOWEDconstant405 Method Not Allowed.
http.status.MISDIRECTED_REQUESTconstant421 Misdirected Request.
http.status.MOVED_PERMANENTLYconstant301 Moved Permanently.
http.status.MULTIPLE_CHOICESconstant300 Multiple Choices.
http.status.MULTI_STATUSconstant207 Multi-Status (WebDAV, RFC 4918).
http.status.NETWORK_AUTHENTICATION_REQUIREDconstant511 Network Authentication Required (RFC 6585).
http.status.NON_AUTHORITATIVE_INFORMATIONconstant203 Non-Authoritative Information.
http.status.NOT_ACCEPTABLEconstant406 Not Acceptable.
http.status.NOT_EXTENDEDconstant510 Not Extended (RFC 2774).
http.status.NOT_FOUNDconstant404 Not Found.
http.status.NOT_IMPLEMENTEDconstant501 Not Implemented.
http.status.NOT_MODIFIEDconstant304 Not Modified.
http.status.NO_CONTENTconstant204 No Content.
http.status.OKconstant200 OK.
http.status.PARTIAL_CONTENTconstant206 Partial Content.
http.status.PAYMENT_REQUIREDconstant402 Payment Required.
http.status.PERMANENT_REDIRECTconstant308 Permanent Redirect.
http.status.PRECONDITION_FAILEDconstant412 Precondition Failed.
http.status.PRECONDITION_REQUIREDconstant428 Precondition Required (RFC 6585).
http.status.PROCESSINGconstant102 Processing (WebDAV, RFC 2518).
http.status.PROXY_AUTHENTICATION_REQUIREDconstant407 Proxy Authentication Required.
http.status.RANGE_NOT_SATISFIABLEconstant416 Range Not Satisfiable.
http.status.REQUEST_HEADER_FIELDS_TOO_LARGEconstant431 Request Header Fields Too Large (RFC 6585).
http.status.REQUEST_TIMEOUTconstant408 Request Timeout.
http.status.RESET_CONTENTconstant205 Reset Content.
http.status.SEE_OTHERconstant303 See Other.
http.status.SERVICE_UNAVAILABLEconstant503 Service Unavailable.
http.status.SWITCHING_PROTOCOLSconstant101 Switching Protocols.
http.status.TEMPORARY_REDIRECTconstant307 Temporary Redirect.
http.status.TOO_EARLYconstant425 Too Early (RFC 8470).
http.status.TOO_MANY_REQUESTSconstant429 Too Many Requests (RFC 6585).
http.status.UNAUTHORIZEDconstant401 Unauthorized.
http.status.UNAVAILABLE_FOR_LEGAL_REASONSconstant451 Unavailable For Legal Reasons (RFC 7725).
http.status.UNPROCESSABLE_CONTENTconstant422 Unprocessable Content.
http.status.UNSUPPORTED_MEDIA_TYPEconstant415 Unsupported Media Type.
http.status.UPGRADE_REQUIREDconstant426 Upgrade Required.
http.status.URI_TOO_LONGconstant414 URI Too Long.
http.status.USE_PROXYconstant305 Use Proxy.
http.status.VARIANT_ALSO_NEGOTIATESconstant506 Variant Also Negotiates (RFC 2295).
http.status.is_bodilessfunctionWhether a response carrying code is defined to have no body at all, regardless of what headers say.
http.status.is_client_errorfunctionWhether code is a 4xx client error.
http.status.is_errorfunctionWhether code is any kind of error, client or server.
http.status.is_informationalfunctionWhether code is a 1xx interim status.
http.status.is_redirectfunctionWhether code is a 3xx redirection status.
http.status.is_registeredfunctionWhether code is a registered status code with a canonical reason phrase of its own.
http.status.is_server_errorfunctionWhether code is a 5xx server error.
http.status.is_successfunctionWhether code is a 2xx success status.
http.status.preserves_methodfunctionWhether a redirect with code must keep the original method and body when followed.
http.status.reasonfunctionThe canonical reason phrase for code, e.g. 'Not Found' for 404.
http.stream.acceptfunctionTurns a freshly accepted TcpStream into a Connection, running a server-side TLS handshake first when…
http.stream.connectfunctionOpens a connection to host on port, optionally wrapping it in TLS.
http.stream.is_timeout_errorfunctionWhether a transport error message describes a timeout (or a would-block, which a socket with a receive…
http.stream.tunnelfunctionOpens a connection to host:port through an HTTP proxy’s CONNECT tunnel, running a TLS handshake with…
http.tls_serverfunctionBuilds an HttpServer already configured for TLS.
http.tracefunctionSends a TRACE request through the shared client.
http.util.find_bytesfunctionFinds the first occurrence of the byte sequence needle in haystack, at or after from, or -1 when it…
http.util.format_datefunctionFormats a Unix timestamp as an IMF-fixdate, the one date format RFC 9110 §5.6.7 requires every HTTP sender to…
http.util.is_valid_methodfunctionWhether value is a valid HTTP method: a non-empty token, per RFC 9110 §9.
http.util.normalize_pathfunctionResolves the . and .. segments of a path and collapses repeated slashes, returning a path that cannot…
http.util.parse_basicfunctionParses an HTTP Basic Authorization field value into a username and password.
http.util.parse_bearerfunctionParses a Bearer Authorization field value into its token.
http.util.parse_datefunctionParses any of the three date formats RFC 9110 §5.6.7 requires a recipient to accept, and returns the Unix…
http.util.parse_parametersfunctionSplits a header value that carries parameters - a media type, a Content-Disposition, a challenge - into its…
http.util.percent_decodefunctionPercent-decodes a URI component, turning + into a space only when plus_as_space is set - which is right…
http.util.percent_encodefunctionPercent-encodes every character of text that is not an RFC 3986 unreserved character, over the UTF-8…
http.util.quotefunctionWraps value in double quotes, escaping any quote or backslash it contains, so it can be used as an RFC 9110…
http.util.random_tokenfunctionA random lowercase-hex token of length characters, drawn from the platform’s cryptographically secure…
http.util.secure_equalsfunctionCompares two strings without leaking, through how long the comparison takes, where they first differ.
http.util.to_hexfunctionn as lowercase hexadecimal, with no 0x prefix and no padding.
http.util.unquotefunctionRemoves the surrounding double quotes from a header value and resolves its backslash escapes.
http.websocket.CLOSE_GOING_AWAYconstantThe endpoint is going away.
http.websocket.CLOSE_INTERNAL_ERRORconstantAn unexpected condition on the server.
http.websocket.CLOSE_INVALID_PAYLOADconstantA text message that was not valid UTF-8.
http.websocket.CLOSE_NORMALconstantNormal closure.
http.websocket.CLOSE_POLICY_VIOLATIONconstantA message that violates a policy.
http.websocket.CLOSE_PROTOCOL_ERRORconstantA protocol error was detected.
http.websocket.CLOSE_TOO_LARGEconstantA message too large to process.
http.websocket.CLOSE_UNSUPPORTEDconstantA message of a kind this endpoint cannot accept.
http.websocket.MessageclassOne complete WebSocket message, with any fragmentation already reassembled.
http.websocket.OPCODE_BINARYconstantBinary frame.
http.websocket.OPCODE_CLOSEconstantClose frame.
http.websocket.OPCODE_CONTINUATIONconstantContinuation frame.
http.websocket.OPCODE_PINGconstantPing frame.
http.websocket.OPCODE_PONGconstantPong frame.
http.websocket.OPCODE_TEXTconstantText frame.
http.websocket.acceptfunctionCompletes a WebSocket handshake and takes over the connection.
http.websocket.accept_keyfunctionThe value a server must return in Sec-WebSocket-Accept for a given client key.
http.websocket.connectfunctionOpens a WebSocket connection to target.
http.websocket.is_handshakefunctionWhether request is a well-formed WebSocket handshake.
http.worker.servefunctionBinds a listening socket and serves it across a pool of worker isolates.
http.worker.worker_mainfunctionThe loop each worker isolate runs: build a server of its own from setup, then serve whatever connections…

Submodules

ModuleReached asSummary
http.bodyhttp.body.*A request or response body, in whatever shape the wire delivered it: a fixed Content-Length, a chunked…
http.clienthttp.client.*HttpClient: the connection-pooling, redirect-following, cookie-aware side of the module.
http.cookieshttp.cookies.*Cookies, both halves of them: Cookie is one cookie with its attributes, CookieJar is a store that applies…
http.errorshttp.*Every error the HTTP stack raises, under one root.
http.fileshttp.files.*Serving files off disk, with the parts that make it correct rather than merely working: conditional requests,…
http.h1http.h1.*HTTP/1.1 on the wire (RFC 9110 and RFC 9112): reading a request line and its headers, writing a status line…
http.h2http.h2.*HTTP/2 (RFC 9113) and the header compression it uses (RFC 7541).
http.headershttp.headers.*Headers: a case-insensitive, order-preserving multimap, because HTTP header names do not compare…
http.middlewarehttp.middleware.*The middleware every public HTTP service ends up needing: CORS, access logging, the security headers a…
http.multiparthttp.multipart.*multipart/form-data, in both directions.
http.negotiatehttp.negotiate.*Content negotiation: choosing what to send when the client has said what it prefers.
http.proxyhttp.proxy.*ReverseProxy forwards a request to another server and streams the response back; LoadBalancer spreads…
http.requesthttp.request.*HttpRequest: one inbound request, with its method, target, headers and body, plus the query string and…
http.responsehttp.response.*HttpResponse: one response, whether it is being built by a handler or read back from a server.
http.routerhttp.router.*Matching a request to a handler.
http.serverhttp.server.*HttpServer: the server end of the module.
http.sessionhttp.session.*Server-side sessions: a small amount of state that belongs to one visitor, kept on the server and found again…
http.ssehttp.sse.*Server-sent events (the WHATWG text/event-stream format): a one-way stream of named, identified messages…
http.statushttp.status.*The HTTP status codes registered with IANA, their canonical reason phrases, and a handful of predicates for…
http.streamhttp.stream.*The transport underneath everything else: a byte stream with buffering, timeouts and optional TLS.
http.utilhttp.util.*The small, exact pieces of the HTTP specifications that several parts of the module need: date formatting,…
http.websockethttp.websocket.*WebSocket (RFC 6455), both ends of it.
http.workerhttp.worker.*The multi-process side of HttpServer: a pool of isolates, each accepting and serving connections from the…

Functions

shared_client()

http.shared_client() -> HttpClient

The shared client the module-level request functions use.

Reach for this to change a setting that should apply to every casual http.get() in a program - a proxy-wide certificate authority, a longer timeout - and build your own client() for anything more specific than that.

Returns HttpClient

client()

http.client(base_url: ?string, options: ?dict) -> HttpClient

Builds a new HttpClient.

Parameters

  • base_url (?string) — prefixed to any relative request target
  • options (?dict) — any HttpClient field, plus headers

Returns HttpClient

set_headers()

http.set_headers(values: dict) -> HttpClient

Sets the default headers on the shared client and returns it, so a call can be chained straight onto it.

echo http.set_headers({ 'Authorization': 'Bearer ' + token })
  .get('https://example.com/me')
  .as_dict()

Parameters

  • values (dict)

Returns HttpClient

get()

http.get(url: string, options: ?dict) -> HttpResponse

Sends a GET request through the shared client.

Parameters

  • url (string)
  • options (?dict) — see HttpClient.request()

Returns HttpResponse

post()

http.post(url: string, data, options: ?dict) -> HttpResponse

Sends a POST request through the shared client.

Parameters

  • url (string)
  • data (?any) — a string or bytes sent as-is, a dictionary or list sent as JSON, or a MultipartBuilder
  • options (?dict)

Returns HttpResponse

put()

http.put(url: string, data, options: ?dict) -> HttpResponse

Sends a PUT request through the shared client.

Parameters

  • url (string)
  • data (?any)
  • options (?dict)

Returns HttpResponse

patch()

http.patch(url: string, data, options: ?dict) -> HttpResponse

Sends a PATCH request through the shared client.

Parameters

  • url (string)
  • data (?any)
  • options (?dict)

Returns HttpResponse

delete()

http.delete(url: string, options: ?dict) -> HttpResponse

Sends a DELETE request through the shared client.

Parameters

  • url (string)
  • options (?dict)

Returns HttpResponse

http.head(url: string, options: ?dict) -> HttpResponse

Sends a HEAD request through the shared client. Redirects are not followed unless options says to.

Parameters

  • url (string)
  • options (?dict)

Returns HttpResponse

options()

http.options(url: string, options: ?dict) -> HttpResponse

Sends an OPTIONS request through the shared client.

Parameters

  • url (string)
  • options (?dict)

Returns HttpResponse

trace()

http.trace(url: string, options: ?dict) -> HttpResponse

Sends a TRACE request through the shared client.

Parameters

  • url (string)
  • options (?dict)

Returns HttpResponse

server()

http.server(port: ?number, host: ?string) -> HttpServer

Builds an HttpServer.

Parameters

  • port (?number) — defaults to 8000
  • host (?string) — defaults to '127.0.0.1'

Returns HttpServer

tls_server()

http.tls_server(port: number, cert_chain: string, private_key: string, host: ?string) -> HttpServer

Builds an HttpServer already configured for TLS.

Parameters

  • port (number)
  • cert_chain (string) — the PEM certificate chain, leaf first
  • private_key (string) — the PEM private key
  • host (?string)

Returns HttpServer

serve()

http.serve(setup, options: ?dict)

Runs a server across a pool of isolates, one per core by default.

setup is called once inside each worker with that worker’s own HttpServer, and registers the routes, middleware and settings the worker should serve with. It may be defined in the main script or in a module, and may use whatever it imports; an imported module is reloaded inside the worker rather than shared with it, so the worker gets its own copy of that module’s top-level state.

The calling isolate binds the socket and accepts connections, handing each one to a worker. It does not return until the server is stopped.

Parameters

  • setup (function(1)) — receives the worker’s HttpServer
  • options (?dict) — port (default 8000), host (default '127.0.0.1'), workers (default: the number of CPUs), backlog (how many accepted connections may wait for a free worker), plus cert_chain/private_key for TLS

Raises HttpError if the socket cannot be bound


2026, Richard Ore and Zuri contributors