Data Structures
Relevant source files
The following files were used as context for generating this wiki page:
Starlette utilizes a variety of specialized data structures to manage the complexities of HTTP and ASGI-based web development. These structures provide optimized ways to handle immutable and mutable headers, multi-value form data, URL manipulation, and application state. By encapsulating these common web patterns, Starlette ensures type safety and performance throughout the request-response lifecycle.
The primary goal of these structures is to abstract the underlying ASGI scope and message formats into developer-friendly objects. This includes handling case-insensitive header lookups and managing the specific requirements of multipart form parsing.
Header Management
Starlette provides two primary classes for handling HTTP headers: Headers and MutableHeaders. These classes handle the translation between raw ASGI byte tuples and high-level Python mappings.
Headers and MutableHeaders
Headers is an immutable multi-dict representation of HTTP headers. It allows for case-insensitive lookups and provides methods to access values as strings or raw bytes. MutableHeaders extends this functionality to allow modifications, which is frequently used when building responses.
The relationship between immutable Headers and the extended MutableHeaders class used for response modification.
| Feature | Description |
|---|---|
| Case-Insensitivity | Keys are normalized to lowercase for lookups. |
| Multi-Value Support | Can store multiple values for the same header key (e.g., Set-Cookie). |
| ASGI Compatibility | Can be initialized directly from an ASGI scope or a list of raw byte tuples. |
Sources: starlette/datastructures.py:1-10, starlette/responses.py:59-75
Form and Multipart Data
Handling user input requires structures that can represent both simple text fields and complex file uploads.
FormData and UploadFile
FormData is an immutable multidict that holds the parsed results of a form submission. When a submission includes files, they are encapsulated in the UploadFile class, which provides an async interface for file operations.
Data flow from parsers into the FormData structure, differentiating between fields and files.
UploadFile Attributes
The UploadFile structure includes metadata and a handle to the actual file content:
| Field | Type | Description |
|---|---|---|
filename | str | The original name of the file uploaded. |
content_type | str | The MIME type of the file. |
file | SpooledTemporaryFile | A file-like object stored in memory or on disk. |
size | int | The size of the file in bytes. |
headers | Headers | Headers specific to the multipart part. |
Sources: starlette/formparsers.py:38-46, starlette/datastructures.py
URL and Routing Structures
URL manipulation is handled through the URL and URLPath classes, which facilitate building, parsing, and making URLs absolute.
URL Manipulation
The URL class provides an interface to components like scheme, netloc, path, and query_string. It is used extensively in RedirectResponse and during reverse URL lookups.
# Example of URL structure usage in responses
class RedirectResponse(Response):
def __init__(self, url: str | URL, status_code: int = 307):
super().__init__(content=b"", status_code=status_code)
self.headers["location"] = quote(str(url))
Sources: starlette/responses.py:192-200, starlette/datastructures.py
Schema and Endpoint Metadata
For API documentation and discovery, Starlette uses structures to represent endpoint signatures and OpenAPI definitions.
EndpointInfo
EndpointInfo is a NamedTuple used during schema generation to aggregate metadata about application routes.
| Field | Description |
|---|---|
path | The URL path pattern (e.g., /users/{id}). |
http_method | The HTTP verb in lowercase (e.g., get). |
func | The actual endpoint handler function or method. |
Sources: starlette/schemas.py:27-30
Application State
The State class is a simple data structure used to store arbitrary information on the Starlette application instance or within a specific Request or WebSocket scope. It allows for attribute-style access to a dictionary-like storage.
The State object allows for sharing context across different parts of the application.
Sources: starlette/applications.py:46-55, starlette/datastructures.py
Summary
Starlette's data structures are designed to be lightweight and strictly typed. By separating concerns between immutable containers (like Headers and FormData) and operational objects (like UploadFile), the framework provides a robust foundation for building predictable async web services. These structures ensure that ASGI message specifics are abstracted away, allowing developers to interact with familiar Pythonic interfaces.