Form Parsing
Relevant source files
The following files were used as context for generating this wiki page:
Form parsing in Starlette is the process of converting raw HTTP request bodies into structured data. This system primarily supports two content types: application/x-www-form-urlencoded and multipart/form-data. The implementation relies on the python-multipart library to stream and process incoming data chunks efficiently without loading the entire payload into memory.
The parsing logic is encapsulated within specific parser classes that handle the state of the stream and trigger callbacks as data segments (fields or files) are identified. This is integrated into the Request object via the .form() method, which returns a FormData object containing both text fields and UploadFile instances.
Sources: starlette/formparsers.py:1-20, starlette/requests.py:228-255, README.md:85-90
Architecture and Components
The form parsing system is composed of several specialized classes that work together to transform an asynchronous byte stream into a high-level data structure.
Core Parsing Classes
| Class | Purpose |
|---|---|
FormParser | Handles application/x-www-form-urlencoded data using a QuerystringParser. |
MultiPartParser | Handles multipart/form-data, supporting both simple fields and file uploads. |
MultipartPart | A dataclass used by the MultiPartParser to track the state of the current part being parsed. |
UploadFile | A wrapper for file data that handles spooling to disk and provides an async interface for file operations. |
Sources: starlette/formparsers.py:65-180, starlette/datastructures.py:440-500
Parser Selection Logic
The Request object inspects the Content-Type header to determine which parser to instantiate. If the content type is not recognized, an empty FormData object is returned.
Sources: starlette/requests.py:228-251
MultiPart Parsing Logic
The MultiPartParser is the most complex component, as it must handle nested headers for each part and manage file handles.
Data Flow and Callbacks
The parser uses a set of callbacks (e.g., on_part_begin, on_header_field, on_part_data) to process the stream.
- Headers: When headers for a part are finished (
on_headers_finished), the parser determines if the part is a simple field or a file based on thefilenameparameter in theContent-Dispositionheader. - File Handling: If it is a file, a
SpooledTemporaryFileis created. This file stays in memory until it reachesspool_max_size(default 1MB), at which point it rolls over to disk. - Async Writing: Data chunks are written to the file using
await part.file.write(data), which ensures that blocking I/O operations (like writing to disk) are offloaded to a thread pool.
Security Constraints
The MultiPartParser enforces several limits to prevent resource exhaustion attacks.
| Parameter | Default | Description |
|---|---|---|
max_files | 1000 | Maximum number of files allowed in a single request. |
max_fields | 1000 | Maximum number of text fields allowed in a single request. |
max_part_size | 1MB | Maximum size for an individual part before raising MultiPartException. |
spool_max_size | 1MB | Threshold for rolling SpooledTemporaryFile from memory to disk. |
Sources: starlette/formparsers.py:113-125, tests/test_formparsers.py:654-680
Data Structures
FormData
The final result of the parsing process is a FormData object. It is an immutable multidict that supports retrieving multiple values for the same key via .getlist().
- Fields: Stored as strings.
- Files: Stored as
UploadFileinstances.
Sources: starlette/datastructures.py:503-518
UploadFile
UploadFile provides an asynchronous interface to the underlying spooled file.
class UploadFile:
def __init__(self, file, *, size=None, filename=None, headers=None):
self.filename = filename
self.file = file
self.size = size
self.headers = headers or Headers()
async def read(self, size: int = -1) -> bytes: ...
async def write(self, data: bytes) -> None: ...
async def seek(self, offset: int) -> None: ...
async def close(self) -> None: ...
Sources: starlette/datastructures.py:440-501
Error Handling
Form parsing can raise specific exceptions if the input is malformed or exceeds configured limits.
- MultiPartException: Raised by
MultiPartParserfor missing boundaries, missing field names, or exceeding limits (max_files,max_fields,max_part_size). - HTTPException (400): If form parsing is called within a Starlette application context, a
MultiPartExceptionis caught and re-raised as anHTTPExceptionwith a 400 status code to provide a clean error response to the client.
Sources: starlette/formparsers.py:59-62, starlette/requests.py:245-248
Integration in Starlette Applications
In a standard Starlette application, the Request object manages the lifecycle of form data. When await request.form() is called, the request body is consumed. Developers are encouraged to call await request.close() after processing the form to ensure that all temporary files associated with UploadFile instances are properly closed and deleted from disk.
async def my_endpoint(request: Request):
form = await request.form()
my_file = form["upload"] # UploadFile
content = await my_file.read()
await request.close() # Cleans up temporary files
return JSONResponse({"filename": my_file.filename})
Sources: starlette/requests.py:253-255, tests/test_formparsers.py:34-45, starlette/applications.py:100-110
Form parsing is an essential feature for handling user uploads and web forms, providing a memory-efficient, streaming implementation that integrates seamlessly with the Starlette request-response lifecycle.