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.response

import http.response

http lifts part of this module out to its own top level; each name below is shown with the path that reaches it. Anything still spelled http.response.* needs import http.response.

HttpResponse: one response, whether it is being built by a handler or read back from a server.

It carries the status, the headers and the body, and the helpers on it cover what a handler nearly always wants: JSON, a file, a redirect, or a stream written a chunk at a time.

Classes

HttpResponse

class http.HttpResponse

An HTTP response, in both directions: the thing a server builds and sends, and the thing a client receives and reads.

On the server side the useful surface is the writers - text(), json(), html(), file(), redirect(), render() - each of which sets a sensible Content-Type alongside the body, plus set_cookie() and the caching helpers.

On the client side it is as_text(), as_dict(), is_ok() and raise_for_status().

A body can be bytes held in memory, a file streamed from disk, or a callback that produces bytes as it goes. The last two matter for a server that has to serve something larger than it would like to hold in memory; see file() and stream().

  • printable — has a @to_string(), so echo and print() show something useful
  • serializable — has a @to_json(), so it can be handed straight to json.encode()

Fields

FieldTypeDescription
statusnumberThe status code.
reason?stringThe reason phrase.
versionstringThe protocol version this response was received over, or will be sent with: '1.0', '1.1', '2' or '3'.
headersHeadersThe response header fields.
bodybytesThe body, as bytes.
cookieslistCookies to be sent with this response.
time_takennumberHow long the request that produced this response took, in milliseconds.
redirectsnumberHow many redirects were followed to reach it.
responder?stringThe URL that finally answered, which differs from the requested one whenever a redirect was followed.
certificate?PeerCertificateThe peer’s TLS certificate, on a response received over HTTPS.
body_reader?BodyReaderThe reader for the body, when the client was asked to stream the response rather than materialise it.
request_method?stringThe method of the request this answers.

Constructor

http.HttpResponse(body, status, headers)

Parameters

  • body (?any) — bytes or a string to start the body with
  • status (?number) — defaults to 200
  • headers (?Headers)

HttpResponse.write()

http.HttpResponse.write(data)

Appends to the response body.

Parameters

  • data (string|bytes)

Returns — HttpResponse: this same instance, for chaining

HttpResponse.text()

http.HttpResponse.text(content: string, status: ?number)

Replaces the body with content and sets Content-Type to text/plain; charset=utf-8.

Parameters

  • content (string)
  • status (?number)

Returns — HttpResponse: this same instance, for chaining

HttpResponse.html()

http.HttpResponse.html(content: string, status: ?number)

Replaces the body with content and sets Content-Type to text/html; charset=utf-8.

Parameters

  • content (string)
  • status (?number)

Returns — HttpResponse: this same instance, for chaining

HttpResponse.json()

http.HttpResponse.json(data, status: ?number)

Replaces the body with the JSON encoding of data and sets Content-Type to application/json.

Parameters

  • data (any)
  • status (?number)

Returns — HttpResponse: this same instance, for chaining

HttpResponse.xml()

http.HttpResponse.xml(content: string, status: ?number)

Replaces the body with content and sets Content-Type to application/xml; charset=utf-8.

Parameters

  • content (string)
  • status (?number)

Returns — HttpResponse: this same instance, for chaining

HttpResponse.file()

http.HttpResponse.file(path: string, offset: ?number, length: ?number)

Serves the file at path, streamed from disk rather than read into memory, with Content-Type guessed from the extension.

offset and length serve part of the file, which is what a Range request needs; the caller is responsible for setting the 206 status and Content-Range header that go with it.

Parameters

  • path (string)
  • offset (?number) — byte offset to start from; defaults to 0
  • length (?number) — how many bytes to send; defaults to the rest of the file

Returns — HttpResponse: this same instance, for chaining

Raises HttpError if the file does not exist or cannot be read

HttpResponse.download()

http.HttpResponse.download(path: string, name: ?string)

Serves the file at path as an attachment, so a browser saves it rather than displaying it.

Parameters

  • path (string)
  • name (?string) — the filename to offer; defaults to the file’s own base name

Returns — HttpResponse: this same instance, for chaining

HttpResponse.stream()

http.HttpResponse.stream(handler)

Produces the body from a callback instead of holding it in memory.

handler is called with a writer that has write(data) and flush(). Anything it writes goes out as it is written, which is what makes server-sent events, a progress feed, or a large generated export possible without buffering the whole thing first.

Unless a Content-Length is set beforehand, the body is framed with chunked transfer encoding on HTTP/1.1 and as an ordinary DATA stream on HTTP/2.

server.handle('GET', '/export', @(request, response) {
  response.content_type('text/csv')
  response.stream(@(writer) {
    for row in rows {
      writer.write(row.join(',') + '\n')
    }
  })
})

Parameters

  • handler (function(1))

Returns — HttpResponse: this same instance, for chaining

HttpResponse.render()

http.HttpResponse.render(path: string, variables: ?dict)

Renders a Wire template and appends the result to the body, setting Content-Type to HTML if it is not already set.

Templates are resolved against Wire’s shared instance, whose root defaults to a templates directory beside the working directory. Use wire.shared().set_root() to point it elsewhere.

Parameters

  • path (string) — the template path, without the .html extension
  • variables (?dict)

Returns — HttpResponse: this same instance, for chaining

HttpResponse.redirect()

http.HttpResponse.redirect(location: string, status: ?number)

Sends the client to location, setting both the Location header and a 3xx status.

The default is 302 Found, which browsers follow with a GET regardless of the original method. Use 307 or 308 when the method and body must be preserved, and 303 after a form submission that should not be replayed on refresh.

Parameters

  • location (string)
  • status (?number) — must be a 3xx; defaults to 302

Returns — HttpResponse: this same instance, for chaining

Raises ValueError if status is not a redirect status

HttpResponse.content_type()

http.HttpResponse.content_type(mimetype: string)

Sets the Content-Type.

Parameters

  • mimetype (string)

Returns — HttpResponse: this same instance, for chaining

HttpResponse.header()

http.HttpResponse.header(name: string, value)

Sets a response header.

Parameters

  • name (string)
  • value (string|number|bool)

Returns — HttpResponse: this same instance, for chaining

http.HttpResponse.set_cookie(name: string, value: string, attributes: ?dict)

Adds a cookie to the response.

http_only defaults to true and same_site to 'Lax', which are the settings a session cookie should have; pass them explicitly to opt out. secure defaults to true for any cookie whose name carries the __Secure- or __Host- prefix.

Parameters

  • name (string)
  • value (string)
  • attributes (?dict) — domain, path, expires, max_age, secure, http_only, same_site, partitioned

Returns — HttpResponse: this same instance, for chaining

http.HttpResponse.clear_cookie(name: string, attributes: ?dict)

Expires a cookie on the client by re-sending it empty with a past expiry.

The domain and path must match the ones the cookie was set with, or the client will keep the original and simply store a second, differently-scoped, empty one.

Parameters

  • name (string)
  • attributes (?dict) — domain and path

Returns — HttpResponse: this same instance, for chaining

HttpResponse.cache_for()

http.HttpResponse.cache_for(seconds: number, public_cache: ?bool)

Marks the response as cacheable for seconds, for both private and shared caches.

Parameters

  • seconds (number)
  • public_cache (?bool) — whether shared caches (a CDN, a proxy) may store it too; defaults to true

Returns — HttpResponse: this same instance, for chaining

HttpResponse.no_cache()

http.HttpResponse.no_cache()

Tells every cache, including the browser’s, not to store this response. The three headers below are the combination that actually works across the caches still in service.

Returns — HttpResponse: this same instance, for chaining

HttpResponse.as_text()

http.HttpResponse.as_text() -> string

The body decoded as UTF-8 text, or '' for an empty body.

Returns string

HttpResponse.as_dict()

http.HttpResponse.as_dict() -> any

The body parsed as JSON.

Returns any

Raises HttpError if the body is empty or is not valid JSON

HttpResponse.as_bytes()

http.HttpResponse.as_bytes() -> bytes

The raw body bytes.

Returns bytes

HttpResponse.media_type()

http.HttpResponse.media_type() -> ?string

The media type from Content-Type, without its parameters, e.g. 'application/json' for 'application/json; charset=utf-8'.

Returns ?string

HttpResponse.charset()

http.HttpResponse.charset() -> ?string

The charset named by Content-Type, or nil.

Returns ?string

HttpResponse.is_ok()

http.HttpResponse.is_ok() -> bool

Whether the status is a 2xx.

Returns bool

HttpResponse.is_redirect()

http.HttpResponse.is_redirect() -> bool

Whether the status is a 3xx.

Returns bool

HttpResponse.is_error()

http.HttpResponse.is_error() -> bool

Whether the status is a 4xx or 5xx.

Returns bool

HttpResponse.raise_for_status()

http.HttpResponse.raise_for_status() -> HttpResponse

Raises StatusError when the status is a 4xx or 5xx, and returns the response otherwise, so it can be used inline:

var data = http.get(url).raise_for_status().as_dict()

The response stays reachable on the raised error, so the body - where an API usually explains what went wrong - is not lost.

Returns HttpResponse

Raises StatusError

HttpResponse.reason_phrase()

http.HttpResponse.reason_phrase() -> string

The reason phrase, either the one received or the canonical one for the status code.

Returns string

HttpResponse.is_bodiless()

http.HttpResponse.is_bodiless() -> bool

Whether the response is defined to carry no body: a 1xx, 204 or 304 status, or any response to a HEAD request.

Returns bool

HttpResponse.source()

http.HttpResponse.source() -> ?list

The body source, when the body is not held in body: ['file', path, offset, length] or ['stream', handler]. nil for an ordinary in-memory body.

Returns ?list

HttpResponse.set_carrier()

http.HttpResponse.set_carrier(carrier)

Records the connection a streamed response is still being read from. Set by HttpClient; hand the response to HttpClient.finish() when you are done reading it.

Parameters

  • carrier (?list)

HttpResponse.carrier()

http.HttpResponse.carrier() -> ?list

The connection a streamed response is still being read from, or nil.

Returns ?list

HttpResponse.is_committed()

http.HttpResponse.is_committed() -> bool

Whether the head has already been written to the wire, after which changing a header or the status has no effect.

Returns bool

HttpResponse.commit()

http.HttpResponse.commit()

Marks the response as committed. Called by the protocol writer; applications have no reason to.

HttpResponse.on_finish()

http.HttpResponse.on_finish(callback: function)

Registers callback to run once the response is final: after the handler, every middleware and any error handling have had their say, so status, the headers and the body are what the client receives.

Middleware that reports on a response, such as an access log, registers here rather than reading the response when its next() returns. A failure further in never returns there, and the status the client is sent for it is only decided afterwards.

Callbacks run once each, in the order they were registered. One that raises is skipped over, so a broken reporter never costs the client its response.

Parameters

  • callback (function) — called with no arguments.

HttpResponse.finish()

http.HttpResponse.finish()

Runs every callback on_finish() registered, once. Called by the server when the response is final; applications have no reason to.

HttpResponse.cookie_headers()

http.HttpResponse.cookie_headers() -> list

Every Set-Cookie field value this response will send.

Returns list

HttpResponse.to_string()

http.HttpResponse.to_string()

HttpResponse.to_json()

http.HttpResponse.to_json()

2026, Richard Ore and Zuri contributors