Starlette Overview
Relevant source files
The following files were used as context for generating this wiki page:
Starlette is a lightweight ASGI (Asynchronous Server Gateway Interface) framework and toolkit designed for building high-performance asynchronous web services in Python. It provides a modular set of components that can be used either as a full-featured framework or as an independent toolkit for ASGI-based development.
The project emphasizes low complexity, high performance, and 100% type annotation and test coverage. Key capabilities include WebSocket support, in-process background tasks, and a robust routing system compatible with both asyncio and trio backends.
Sources: README.md:1-35
Core Architecture
Starlette operates on the ASGI specification, where the application is an asynchronous callable that accepts scope, receive, and send arguments. The architecture is centered around a recursive middleware stack that wraps the core routing logic.
The Starlette Application Class
The Starlette class serves as the primary entry point. It manages the configuration of routes, middleware, and exception handlers. Upon the first request, the application builds its middleware stack, which is then cached for subsequent calls.
The diagram shows the request flow through the Starlette application and its middleware layers.
Sources: starlette/applications.py:46-85
Middleware Stack Composition
Starlette automatically wraps every application in two essential middleware layers:
- ServerErrorMiddleware: The outermost layer, ensuring that any unhandled exception in the stack results in a 500 response.
- ExceptionMiddleware: The innermost layer, responsible for catching handled exceptions (like
HTTPException) and converting them into responses via configured handlers.
| Middleware Layer | Description | Source File |
|---|---|---|
ServerErrorMiddleware | Handles uncaught 500 errors; provides debug tracebacks. | starlette/middleware/errors.py |
User Middleware | Custom middleware added via middleware list or add_middleware(). | starlette/applications.py:75 |
ExceptionMiddleware | Converts caught exceptions into HTTP responses. | starlette/applications.py:76 |
Sources: starlette/applications.py:68-81, starlette/middleware/errors.py:88-100
Routing and Endpoints
Routing in Starlette is handled by the Router class, which matches incoming request scopes to specific Route, WebSocketRoute, Mount, or Host objects.
Route Matching Process
When a request enters the router, it iterates through its list of routes to find a match based on the path and, for HTTP, the method.
Endpoint Types
Starlette supports multiple styles of endpoints:
- Function-based: Simple async or sync functions.
- Class-based (HTTPEndpoint): Classes where methods (get, post, etc.) correspond to HTTP verbs.
- WebSocketEndpoint: Classes specialized for managing stateful WebSocket connections.
class OrganisationsEndpoint(HTTPEndpoint):
def get(self, request: Request) -> None:
"""Handled by HTTPEndpoint.dispatch"""
pass
Sources: starlette/endpoints.py:17-48, tests/test_schemas.py:58-79
Response System
Starlette provides a wide array of response classes that implement the ASGI protocol to send data back to the client.
Standard Response Classes
| Class | Media Type | Purpose |
|---|---|---|
Response | None (Base) | Base class for all responses. |
HTMLResponse | text/html | Sends HTML content. |
JSONResponse | application/json | Serializes Python objects to JSON. |
StreamingResponse | Variable | Streams content using an async iterator. |
FileResponse | Variable | Efficiently streams files from disk with range support. |
Sources: starlette/responses.py:14-230
Range Request Handling
FileResponse includes advanced logic for handling HTTP Range requests, allowing clients to request specific byte ranges of a file (e.g., for video seeking).
Sources: starlette/responses.py:317-380
Security and Authentication
Starlette includes an authentication system based on AuthenticationMiddleware and specialized backends.
Authentication Flow
- Middleware:
AuthenticationMiddlewarewraps the app and uses aAuthenticationBackendto populaterequest.userandrequest.auth. - Decorators: The
@requiresdecorator can be used to protect endpoints based on scopes.
API Schema Generation
Starlette supports automated OpenAPI schema generation by parsing route information and YAML content within function docstrings.
Schema Extraction
The SchemaGenerator traverses the route tree, identifying endpoints and extracting documentation:
- Path extraction: Converts Starlette path patterns (e.g.,
{id:int}) to OpenAPI format ({id}). - Docstring parsing: Uses
PyYAMLto parse the section of a docstring following a---separator.
Sources: starlette/schemas.py:35-115, tests/test_schemas.py:13-56
Conclusion
Starlette's design as both a framework and a toolkit allows for significant flexibility. Its reliance on the ASGI standard ensures compatibility with modern asynchronous servers like Uvicorn, while its modular nature permits developers to use specific components (like the response system or the router) in isolation within other projects.
Sources: README.md:65-75