Application Modularity
Relevant source files
The following files were used as context for generating this wiki page:
Starlette is designed as a modular ASGI toolkit and framework, emphasizing the creation of reusable components that can be shared across the ASGI ecosystem. This modularity is achieved through a clean separation between applications, routers, and individual routes, allowing each component to function in isolation or as part of a larger system.
The architecture promotes "mountable" applications where a sub-application can be attached to a specific path prefix of a parent application. This enables developers to build complex services by composing smaller, independent ASGI applications, which can include their own routing logic, middleware stacks, and exception handlers.
Sources: README.md:85-93, starlette/routing.py:441-456
Core Architectural Components
The modularity of Starlette relies on several fundamental classes that define how requests are routed and handled.
The Starlette Application Class
The Starlette class serves as the primary container for an application. It manages the high-level configuration, including the global middleware stack, exception handlers, and the primary router.
The Starlette app initializes a Router to handle incoming HTTP and WebSocket requests. It also wraps the router in a middleware stack that automatically includes ServerErrorMiddleware for uncaught errors and ExceptionMiddleware for handled exceptions.
Sources: starlette/applications.py:20-65
Routing and Mounting
Modularity is heavily implemented through the Router and the Mount class. A Mount allows an entire ASGI application (including another Starlette instance or a Router) to be served under a specific path.
| Component | Description |
|---|---|
Route | Matches a standard HTTP path and method to an endpoint. |
WebSocketRoute | Matches a path to a WebSocket endpoint. |
Mount | Attaches another ASGI application or a list of routes to a path prefix. |
Host | Routes requests based on the Host header, supporting subdomains. |
Sources: starlette/routing.py:273-518
Sub-application Composition
Starlette allows nesting applications via the Mount class. When a request matches a mounted path, the Router strips the matched prefix from the path and updates the root_path in the ASGI scope before passing the request to the sub-application.
The diagram above illustrates how a request to /api/users is delegated from a main router to a sub-application mounted at /api.
Path Handling in Mounts
When a Mount is processed:
- The
pathattribute of the mount defines the prefix. - The
root_pathin the ASGI scope is extended by the matched prefix. - The
pathin the scope is updated to reflect the remaining unmatched portion for the sub-application.
Sources: starlette/routing.py:469-491, tests/test_routing.py:408-417
Modular Middleware and Exception Handling
Modularity extends to how middleware and exception handlers are applied. Each Route or Mount can have its own local middleware stack, which is independent of the global application middleware.
Middleware Stacking Logic
The Starlette application builds its middleware stack in reverse order, ensuring the most recently added middleware is the first to process the request.
# starlette/applications.py:73-86
middleware = (
[Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]
+ self.user_middleware
+ [Middleware(ExceptionMiddleware, handlers=exception_handlers, debug=debug)]
)
app = self.router
for cls, args, kwargs in reversed(middleware):
app = cls(app, *args, **kwargs)
Sources: starlette/applications.py:73-86
Independent Schema Generation
The modular structure allows for automatic API schema generation that respects the application hierarchy. The SchemaGenerator can traverse through Mount and Host objects to discover all endpoints within a modular application tree.
Sources: starlette/schemas.py:38-55
Modularity in Testing and Tooling
Because Starlette components follow the ASGI specification, individual routes or sub-applications can be tested in isolation using the TestClient.
# tests/test_routing.py:441-446
def test_standalone_route_matches(
test_client_factory: TestClientFactory,
) -> None:
app = Route("/", PlainTextResponse("Hello, World!"))
client = test_client_factory(app)
response = client.get("/")
assert response.status_code == 200
This capability confirms that a single Route is a valid, independent ASGI application.
Sources: tests/test_routing.py:441-446, README.md:105-112
Summary of Modular Interaction
The modularity in Starlette allows developers to build highly decoupled systems. A developer can define a Router in one module, wrap it with specific Middleware in another, and finally Mount it into a Starlette application in a third. This hierarchy ensures that logic is encapsulated, and components remain reusable across different projects.
Sources: README.md:95-98, starlette/routing.py:597-628