ASGI Concepts & Types
Relevant source files
The following files were used as context for generating this wiki page:
Starlette is built fundamentally as an [ASGI][asgi] (Asynchronous Server Gateway Interface) toolkit. It provides the necessary abstractions, type definitions, and core components to build asynchronous web services that interact with ASGI servers like Uvicorn or Daphne. The framework operates by processing three primary primitives: Scope, Receive, and Send.
The project is designed to be 100% type-annotated, ensuring that the interface between the web server, middleware, and application code is strictly defined and verifiable.
Sources: README.md:1-26, starlette/testclient.py:48-52
Core ASGI Interfaces
The ASGI specification defines how an application is called by a server. Starlette implements both ASGI 2 and ASGI 3 interfaces, with a preference for the single-callable ASGI 3 standard.
Primitive Types
The following table describes the three fundamental components of an ASGI interaction:
| Component | Type | Description |
|---|---|---|
| Scope | MutableMapping[str, Any] | A dictionary containing information about the connection, such as protocol, path, and headers. |
| Receive | Callable[[], Awaitable[Message]] | An awaitable callable that returns the next message from the client (e.g., request body chunks). |
| Send | Callable[[Message], Awaitable[None]] | An awaitable callable used to send messages back to the client (e.g., response headers or body). |
Sources: starlette/types.py:7-12, starlette/testclient.py:43-52
Application Signatures
Starlette identifies applications through their call signatures. While ASGI 3 is the modern standard, Starlette provides a _WrapASGI2 utility to bridge older ASGI 2 applications.
- ASGI 3 App:
async def app(scope, receive, send): ... - ASGI 2 App:
def app(scope): return async def instance(receive, send): ...
Sources: starlette/testclient.py:48-77
Request-Response Lifecycle
The lifecycle of an ASGI request involves the server creating a scope and then calling the application. The application then uses receive to get data and send to provide a response.
Data Flow Diagram
The following diagram illustrates the interaction between the ASGI Server and the Starlette Application:
This sequence represents the standard flow for an HTTP request within the framework.
Sources: starlette/routing.py:443-485, starlette/applications.py:78-82
Lifespan Protocol
The Lifespan protocol allows an ASGI application to perform startup and shutdown tasks. This is handled by a specific scope type: lifespan.
Lifespan Event Flow
When a server starts, it sends a lifespan.startup message. The application must respond with lifespan.startup.complete or lifespan.startup.failed. A similar handshake occurs for lifespan.shutdown.
Protocol-Specific Implementations
HTTP Protocol
HTTP requests in Starlette are wrapped in a scope where scope['type'] == 'http'. The router matches the path and method against defined routes.
- Key Messages:
http.request,http.response.start,http.response.body. - Routing: The
Routeriterates throughroutesto find aMatch.FULLorMatch.PARTIAL.
Sources: starlette/routing.py:456-485, starlette/testclient.py:228-265
WebSocket Protocol
WebSockets use scope['type'] == 'websocket'. Unlike HTTP, WebSockets maintain state (CONNECTING, CONNECTED, DISCONNECTED).
| State | Allowed Receive Message | Allowed Send Message |
|---|---|---|
| CONNECTING | websocket.connect | websocket.accept, websocket.close |
| CONNECTED | websocket.receive, websocket.disconnect | websocket.send, websocket.close |
| RESPONSE | N/A | websocket.http.response.body |
Sources: starlette/websockets.py:15-84
Middleware & Composition
Starlette uses a layered approach where middleware wraps the core application. Each middleware is itself an ASGI application that takes an app argument in its constructor.
The Starlette class builds this stack automatically, placing ServerErrorMiddleware at the outermost layer to catch all unhandled exceptions.
Sources: starlette/applications.py:53-73, starlette/routing.py:408-415
WSGI Compatibility
Starlette provides a bridge for legacy WSGI applications through WSGIMiddleware. It converts the asynchronous ASGI scope, receive, and send into a synchronous WSGI environ and start_response callable.
- Environ Building: The
build_environfunction maps ASGI scope keys (likepath,query_string,headers) to WSGI environment variables (likePATH_INFO,QUERY_STRING,HTTP_*). - Threading: Since WSGI is synchronous, the middleware runs the WSGI application in a separate threadpool using
anyio.to_thread.run_sync.
Sources: starlette/middleware/wsgi.py:22-68, starlette/middleware/wsgi.py:100-112
Summary
ASGI Concepts and Types form the backbone of Starlette, enabling its lightweight and modular architecture. By adhering strictly to the ASGI specification through typed Scope, Receive, and Send interactions, Starlette ensures compatibility across various servers and provides a robust foundation for both HTTP and WebSocket communications, as well as complex lifespan management.