HTTP Requests
Relevant source files
The following files were used as context for generating this wiki page:
Starlette provides a robust, high-level Request object that wraps the underlying ASGI scope and receive channel. It is designed to provide a convenient interface for accessing common HTTP request properties such as headers, query parameters, cookies, and body content. The Request class inherits from HTTPConnection, which shares common functionality with WebSockets, ensuring consistency across different protocol types.
Sources: starlette/requests.py:102-113, starlette/requests.py:175-182, README.md
Connection Architecture
The HTTP request handling starts with an HTTPConnection base class, which provides shared access to the ASGI scope. This base class handles metadata that is protocol-agnostic, such as the application state, URL information, and basic client details.
This diagram illustrates the inheritance hierarchy where Request extends the base connection logic.
Sources: starlette/requests.py:102-172, starlette/requests.py:175-184
Key Connection Components
| Property | Type | Description |
|---|---|---|
scope | Scope | The raw ASGI scope dictionary containing request metadata. |
app | Any | Reference to the Starlette application instance. |
url | URL | A URL object representing the full request URL. |
base_url | URL | The root URL of the application, accounting for root_path. |
headers | Headers | Immutable multi-dict of HTTP headers. |
query_params | QueryParams | Dictionary-like object containing URL query strings. |
state | StateT | A container for storing arbitrary request-local state. |
Sources: starlette/requests.py:115-161, starlette/requests.py:163-172
Request Lifecycle and Data Access
The Request object manages the lifecycle of the request body through the ASGI receive channel. Accessing the body is an asynchronous operation, as data may arrive in multiple chunks.
Data Flow for Request Body
The flow shows how Starlette iterates over ASGI messages to assemble or stream the request body.
Sources: starlette/requests.py:202-219
Body Access Methods
stream(): Returns anAsyncGeneratoryielding bytes. This is the most memory-efficient way to process large uploads.body(): Awaits the entire stream and returns a singlebytesobject. Once called, the result is cached.json(): Awaits the body and parses it usingjson.loads().form(): Parses the body as eithermultipart/form-dataorapplication/x-www-form-urlencoded. This requires thepython-multipartlibrary.
Sources: starlette/requests.py:202-270, tests/test_requests.py:65-150
Header and Cookie Parsing
Starlette implements custom parsing for cookies to ensure compatibility with real-world browser behavior, which often deviates from RFC 6265.
Cookie Parsing Logic
The cookie_parser function splits the Cookie header by semicolons and handles unquoting of values. It is adapted from Django's implementation to handle edge cases where browsers send malformed or unnamed cookies.
Sources: starlette/requests.py:54-82
Server Push
The Request object includes a send_push_promise method. If the ASGI server supports the http.response.push extension, Starlette will copy specific headers (like User-Agent and Accept) and send a push promise for the specified path.
Sources: starlette/requests.py:44-51, starlette/requests.py:293-301
Error Handling during Requests
When an error occurs during request processing, Starlette's ServerErrorMiddleware or ExceptionMiddleware catches the exception. If debug is enabled, Starlette can generate a detailed HTML traceback.
This diagram depicts how exceptions are intercepted and transformed into HTTP responses.
Sources: starlette/middleware/errors.py:151-189
Testing Requests
The TestClient facilitates testing by mocking the ASGI environment. It uses httpx to simulate requests and provides a websocket_connect method for testing WebSocket interactions within the same connection logic.
| Feature | Description |
|---|---|
| BlockingPortal | Used by TestClient to bridge synchronous test code with asynchronous ASGI apps. |
| ASGIPortalFactory | Manages the lifecycle of the async backend during a test. |
| Response Mocking | Captures http.response.start and http.response.body messages to build an httpx.Response. |
Sources: starlette/testclient.py:180-230, starlette/testclient.py:445-480
Conclusion
HTTP Requests in Starlette are represented by a high-level API that abstracts the complexities of the ASGI protocol. By providing a unified interface via HTTPConnection and specialized logic for body streaming, form parsing, and cookie handling, Starlette enables developers to interact with incoming data efficiently while maintaining high performance through asynchronous I/O.
Sources: starlette/requests.py, starlette/responses.py, starlette/testclient.py