HTTP Responses
Relevant source files
The following files were used as context for generating this wiki page:
HTTP Responses in Starlette are represented by a hierarchy of classes designed to handle various content types, from simple plain text to complex streaming and file delivery. These classes encapsulate the logic for status codes, headers, and body rendering, providing a consistent interface for ASGI applications to send data back to clients.
The response system is highly modular, allowing developers to return specialized responses like JSONResponse for APIs, HTMLResponse for web pages, or StreamingResponse for large datasets. It also includes built-in support for standard HTTP features such as cookie management, range requests for files, and CORS preflight handling.
Sources: starlette/responses.py:32-330, README.md:1-85
Core Response Architecture
The base Response class serves as the foundation for all HTTP responses. It handles the initial setup of status codes, header population, and the conversion of content into bytes via the render method. Every response object is a callable that follows the ASGI signature, enabling it to interact directly with the ASGI send channel.
The Response Lifecycle
When a response is called, it sends an http.response.start message containing the status and headers, followed by an http.response.body message containing the actual content.
The diagram shows the sequence from object initialization to the final transmission of messages over the ASGI interface.
Sources: starlette/responses.py:32-132
Implementation Classes
| Class | Purpose | Default Media Type |
|---|---|---|
Response | Base class for all responses. | None |
HTMLResponse | Returns HTML content. | text/html |
PlainTextResponse | Returns raw text. | text/plain |
JSONResponse | Automatically serializes data to JSON. | application/json |
RedirectResponse | Redirects to a new URL. | None |
StreamingResponse | Streams content using an async or sync iterator. | None |
FileResponse | Efficiently streams files with Range and ETag support. | Guessed from path/filename |
OpenAPIResponse | Returns a YAML-encoded OpenAPI schema. | application/vnd.oai.openapi |
Sources: starlette/responses.py:135-231, starlette/schemas.py:18-24
Specialized Response Logic
JSON and Schema Responses
JSONResponse overrides the render method to use json.dumps with specific settings like ensure_ascii=False and compact separators. Similarly, OpenAPIResponse uses yaml.dump to provide API documentation.
Sources: starlette/responses.py:143-162, starlette/schemas.py:18-24
Redirects
RedirectResponse sets a 307 status code by default and handles URL quoting for the location header to ensure compatibility with non-ASCII characters in paths.
Sources: starlette/responses.py:165-175
Streaming Responses
StreamingResponse is designed for large bodies. It can consume both synchronous iterables (by running them in a threadpool) and asynchronous iterables. It monitors for http.disconnect messages to stop streaming if the client closes the connection.
The sequence diagram illustrates how a StreamingResponse sends multiple body chunks over the ASGI connection.
Sources: starlette/responses.py:182-228
File Handling and Range Requests
FileResponse provides optimized file delivery. It includes logic for:
- Header Generation: Automatically calculates
content-length,last-modified, and anetagbased on file statistics. - Range Requests: Supports the
Rangeheader, allowing clients to request specific byte segments of a file (Standard or Multipart). - Pathsend Extension: If the ASGI server supports the
http.response.pathsendextension, Starlette delegates the file reading to the server for maximum performance.
Sources: starlette/responses.py:234-323
Range Request Processing
When a Range header is present, the response calculates the requested offsets and verifies they are satisfiable against the file size.
This flow represents how FileResponse decides between sending the whole file or specific byte ranges.
Sources: starlette/responses.py:257-291
Cookie and Header Management
The base Response class provides utilities for manipulating HTTP headers and cookies before the response is sent.
- Headers: Initialized via a mapping and exposed through a
MutableHeadersinterface. - Cookies: The
set_cookiemethod useshttp.cookies.SimpleCookieto formatSet-Cookieheaders. It supports standard attributes:max_age,expires,path,domain,secure,httponly, andsamesite. - Partitioned Cookies: Supported for Python 3.14+ to comply with privacy standards.
Sources: starlette/responses.py:59-122
Error Responses
Starlette includes middleware to generate standardized error responses. The ServerErrorMiddleware can produce:
- Debug HTML Responses: Rich HTML traceback pages for development, including source code snippets and formatted exception details.
- Plain Text Errors: A simple "Internal Server Error" for production environments.
Sources: starlette/middleware/errors.py:144-245
Status Codes
Starlette provides a comprehensive list of HTTP and WebSocket status codes in starlette.status. These constants follow the IANA and RFC 9110 registries.
| Category | Range | Examples |
|---|---|---|
| Informational | 1xx | HTTP_101_SWITCHING_PROTOCOLS |
| Success | 2xx | HTTP_200_OK, HTTP_204_NO_CONTENT |
| Redirection | 3xx | HTTP_301_MOVED_PERMANENTLY, HTTP_307_TEMPORARY_REDIRECT |
| Client Error | 4xx | HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND |
| Server Error | 5xx | HTTP_500_INTERNAL_SERVER_ERROR |
| WebSocket | 1xxx | WS_1000_NORMAL_CLOSURE, WS_1011_INTERNAL_ERROR |
Sources: starlette/status.py:1-125
HTTP Responses in Starlette provide a robust, type-annotated toolkit for handling diverse web communication needs. By abstracting the complexities of the ASGI protocol and HTTP specifications (like ranges and content-type guessing), it allows for the efficient and safe delivery of both structured data and static assets.