Routing
Relevant source files
The following files were used as context for generating this wiki page:
Routing is the core mechanism in Starlette that maps incoming ASGI scopes (HTTP requests, WebSocket connections, or Lifespan events) to specific endpoints. It provides a structured way to define URL patterns, handle path parameters with type conversion, and manage application modularity through mounting and host-based dispatching. Sources: starlette/routing.py:488-500, README.md:68-81
The system is built around the Router class, which iterates through a list of BaseRoute implementations to find a match. When a match is found, the router updates the ASGI scope with relevant metadata, such as path parameters, and delegates the handling of the request to the matched route's endpoint. Sources: starlette/routing.py:537-565
Core Components
The routing system is composed of several specialized classes that inherit from BaseRoute. Each class handles a specific type of matching logic.
Router Class
The Router is the primary orchestrator. It maintains a list of routes and handles the high-level dispatching logic, including redirection for trailing slashes and default 404/405 handling. Sources: starlette/routing.py:441-486
Route Types
Starlette defines four primary route types for different networking scenarios:
| Class | Purpose | Key Parameters |
|---|---|---|
Route | Handles HTTP requests | path, endpoint, methods |
WebSocketRoute | Handles WebSocket connections | path, endpoint |
Mount | Nesting a sub-application or group of routes | path, app, routes |
Host | Dispatching based on the HTTP Host header | host, app |
Sources: starlette/routing.py:164, starlette/routing.py:246, starlette/routing.py:302, starlette/routing.py:397
Request Flow and Matching
When an ASGI request enters the Router, it follows a specific sequence to determine which endpoint should process it.
The diagram shows the logic within Router.app for dispatching HTTP and WebSocket requests. Sources: starlette/routing.py:537-584
Matching Logic
- Full Match: The path and HTTP method (if applicable) match exactly. Sources: starlette/routing.py:214-220
- Partial Match: The path matches, but the HTTP method does not. This is used to return a
405 Method Not Allowedresponse with the correctAllowheader. Sources: starlette/routing.py:218-222, starlette/routing.py:557-565 - Redirect Slashes: If no match is found, but a version of the path with or without a trailing slash would match, the router can issue a
RedirectResponse. Sources: starlette/routing.py:567-582
Path Parameters and Convertors
Starlette supports dynamic path segments using the {name} or {name:type} syntax. The compile_path function transforms these templates into regular expressions and associates them with Convertor objects. Sources: starlette/routing.py:112-161
Built-in Convertors
The system uses the CONVERTOR_TYPES dictionary to map type strings to logic that handles regex generation and Python type casting.
| Convertor | Regex | Python Type |
|---|---|---|
str (default) | [^/]+ | str |
int | [0-9]+ | int |
float | [0-9]+(\.[0-9]+)? | float |
uuid | [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} | uuid.UUID |
path | .* | str |
Sources: starlette/routing.py:126-135, starlette/convertors.py
Parameter Extraction
During the matches call, the Route uses the compiled regex to extract groups from the URL. These values are passed through the convertor's convert() method before being added to scope["path_params"]. Sources: starlette/routing.py:209-216
Mounting and Host Routing
Starlette enables complex application structures through Mount and Host routes.
Mount Architecture
A Mount takes a path prefix and a sub-application (or list of routes). It "strips" the matched prefix from the path and prepends it to the root_path within the child scope. This allows sub-applications to be written with paths relative to their mount point. Sources: starlette/routing.py:338-360
Host Routing
The Host route matches based on the host header. It supports parameters, allowing for subdomain-based routing where the subdomain is extracted into path_params. Sources: starlette/routing.py:406-421
API Schema Generation
Starlette includes a BaseSchemaGenerator that can introspect the routing table to produce OpenAPI schemas. It traverses Mount and Host routes recursively to build a complete list of endpoints. Sources: starlette/schemas.py:33-56
Key Schema Logic
- Path Cleaning: It removes Starlette-specific convertors (e.g.,
/{id:int}becomes/{id}) to follow OpenAPI standards. Sources: starlette/schemas.py:84-91 - Method Discovery: For class-based endpoints, it checks for methods like
get,post, etc., to identify supported operations. Sources: starlette/schemas.py:73-80 - Docstring Parsing: It can parse YAML content from function docstrings separated by
---to populate endpoint details. Sources: starlette/schemas.py:93-115
Conclusion
The Starlette routing system provides a highly modular and flexible way to map network events to code. By utilizing BaseRoute polymorphism, it handles HTTP, WebSockets, and nested applications through a unified dispatching interface. The integration of path convertors ensures type safety, while the schema generation utilities provide automatic documentation capabilities based directly on the defined routing structure. Sources: starlette/routing.py:537-565, starlette/applications.py:73-81