Server routing, responses, and static files
The aiohttp web layer maps each incoming request to one application handler. The handler returns a response that carries the status, headers, and body to the HTTP connection. The same routing model can also serve files from a controlled directory.
Route definitions
Route definitions state the public URL contract before the application serves traffic. A definition binds an HTTP method and path to an async handler, a class-based view, or a static directory. Applications can add definitions directly or register a collected route table through aiohttp/web_routedef.py.
The router keeps route resources in registration order. A GET route also permits HEAD by default, while allow_head=False keeps the endpoint limited to GET. A named route provides a stable point for building URLs from path values instead of repeating path text.
| Route form | Purpose |
|---|---|
| Method route | Connects one HTTP method and path to an async handler. |
GET route | Handles reads and can also create a matching HEAD route. |
| View route | Connects one path to a class-based handler for several methods. |
| Static route | Connects a URL prefix to a file directory. |
RouteTableDef | Collects route definitions with decorators before registration. |
References: aiohttp/web_routedef.py• L36-66 aiohttp/web_routedef.py• L90-136 aiohttp/web_routedef.py• L142-205 aiohttp/web_urldispatcher.py• L1120-1248
URL dispatch
URL dispatch first finds a resource that matches the request path and then finds a route for the request method. A resource is the path-level unit of routing. It can represent an exact path, a path with variables, a static prefix, or a nested application. The match result carries the selected handler and any captured path values.
Domain-matched subapplications are checked before ordinary path resources. For normal paths, the router checks the most explicit candidates first and keeps registration order when candidates share a path. Fixed paths take priority over dynamic paths. Domain rules compare hosts without regard to case. A domain registered without a port also matches a request host with a port, while a registered port remains significant.
When a path matches but its method does not, dispatch returns 405 Method Not Allowed with the allowed methods. When no resource matches, it returns 404 Not Found.
This diagram shows how a request moves from URL matching to a handler or a routing error.
flowchart TD
A[Request host path and method] --> B{Domain-matched subapplication}
B -->|match| C[Resolve nested router]
B -->|no match| D[Find most explicit path resource]
C --> E{Method route}
D --> E
E -->|match| F[Handler with match values]
E -->|path match only| G[405 Method Not Allowed]
D -->|no path match| H[404 Not Found]
References: aiohttp/web_urldispatcher.py• L343-348 aiohttp/web_urldispatcher.py• L741-748 aiohttp/web_urldispatcher.py• L802-838 aiohttp/web_urldispatcher.py• L855-864 aiohttp/web_urldispatcher.py• L995-1034
Class-based views
A class-based view groups method handlers for one path. The framework creates the view with the request and calls the lowercase method that matches the request method, such as get() or post(). This keeps shared path behavior with the method-specific work.
The view returns 405 Method Not Allowed when no matching method exists. Its Allow header lists the methods defined on the view. The route itself accepts any method so the view can make this method choice.
References: aiohttp/abc.py• L99-112 aiohttp/web_urldispatcher.py• L934-950
Resource handlers
Resource handlers connect path matching to application work. A plain resource matches one path exactly. A dynamic resource matches a path pattern and returns named values. A static resource maps a URL prefix to files. A subapplication resource passes the request into another application's router.
Resource names support URL creation and router inspection. The application freezes the router before serving requests. After freeze, the route shape and nested application context cannot change during request handling.
References: aiohttp/web_urldispatcher.py• L102-146 aiohttp/web_urldispatcher.py• L309-469 aiohttp/web_urldispatcher.py• L716-757 aiohttp/web_urldispatcher.py• L984-1118 aiohttp/web_urldispatcher.py• L1233-1236
Response types
Responses represent the result of a handler and define how the server sends status, headers, and body data. StreamResponse supports controlled output. Response adds a complete body backed by bytes, text, or a registered payload. json_response() creates JSON from an object, while json_bytes_response() accepts an encoder that already returns bytes.
The response prepares its headers once before output begins. It then sends a complete body or writes chunks until write_eof() ends the response. Known body sizes use Content-Length; otherwise HTTP/1.1 can use chunked transfer when the request and body rules allow it.
| Response type | Best use |
|---|---|
StreamResponse | Incremental output or a body written by the handler. |
Response | A known text, byte, or payload body. |
| JSON response | Data encoded as JSON with a JSON content type. |
FileResponse | A file body with metadata, ranges, and cache conditions. |
| HTTP exception | A status result raised by routing, a handler, or file checks. |
Status and headers must be final before preparation completes. Responses can set cookies, content type, charset, cache metadata, compression, and connection behavior. Compression is negotiated with the request. A response that already has Content-Encoding is not compressed again.
json_bytes_response() is intended for encoders that return bytes. It avoids an extra text encode and keeps the JSON content type on the resulting response. Response also accepts registered payloads. Such payloads can supply their own headers and write their body through the response stream.
References: aiohttp/web_response.py• L55-75 aiohttp/web_response.py• L72-198 aiohttp/web_response.py• L363-445 aiohttp/web_response.py• L459-497 aiohttp/web_response.py• L546-747 aiohttp/web_response.py• L749-801
HTTP exception responses
HTTP exceptions are status-bearing results for requests that cannot complete through a normal handler response. They carry a status, reason, headers, and optional text body. The request-processing layer can therefore turn a raised exception into an HTTP response without a separate error format.
Routing uses HTTPNotFound for an unknown path and HTTPMethodNotAllowed for a known path with an unsupported method. The method error includes the allowed methods in the Allow header. Other exception types cover redirects, access control, preconditions, range errors, and server errors.
References: aiohttp/web_exceptions.py• L84-164 aiohttp/web_exceptions.py• L172-212 aiohttp/web_exceptions.py• L284-331 aiohttp/web_urldispatcher.py• L277-305 aiohttp/web_urldispatcher.py• L904-929
Static file serving
Static serving maps a URL prefix to a directory and turns a matching filename into a file response. The static resource accepts GET and HEAD. It checks that the requested path stays within the configured root, then lets FileResponse handle the file transfer.
Directory requests are forbidden by default. With index display enabled, the server returns an escaped HTML listing with quoted links. Symlink access stays inside the root by default. An optional setting can allow symlinks to resolve outside the root while URL path traversal remains blocked.
Static URLs can include a version query value derived from the file content when version appending is enabled. This gives clients a new URL when the file content changes and supports cache-safe asset names.
FileResponse checks cache conditions before it opens a file. A failed precondition returns 412, while a fresh cached representation returns 304 without a body. For a valid transfer, it can select a .br or .gz variant when the client accepts that encoding. It marks the selected encoding so the response is not compressed a second time.
File responses provide the behavior needed for safe and efficient downloads:
- They infer a content type from the file name and use a binary fallback when none is known.
- A configured charset applies to inferred text types.
- They include
ETag,Last-Modified, and byte-range metadata. - They return
206for a satisfiable range and416for an unsatisfiable range. - They do not send a body for
HEADor another body-forbidden response. - They use the transport file path when available and send bounded chunks as a fallback.
This diagram shows the decision path for a request under a static URL prefix.
flowchart TD
A[Static URL request] --> B{Path stays in root}
B -->|no| C[404 Not Found]
B -->|yes| D{Directory}
D -->|yes and index off| E[403 Forbidden]
D -->|yes and index on| F[HTML directory listing]
D -->|no| G[Choose regular file]
G --> H{Cache or range condition}
H -->|precondition fails| I[412 response]
H -->|not modified| J[304 response]
H -->|range invalid| K[416 response]
H -->|range valid| L[206 file response]
H -->|no special condition| M[200 file response]
References: aiohttp/web_urldispatcher.py• L501-588 aiohttp/web_urldispatcher.py• L606-677 aiohttp/web_urldispatcher.py• L679-709 aiohttp/web_fileresponse.py• L85-103 aiohttp/web_fileresponse.py• L109-153 aiohttp/web_fileresponse.py• L163-235 aiohttp/web_fileresponse.py• L237-299 aiohttp/web_fileresponse.py• L301-438
Routing relationships
Routing is the boundary between the application and request processing. The router selects the handler and records match data. The application adds the active application context and invokes the handler. The handler returns a response that the server prepares and emits on the connection.
For the wider inbound flow, see Server request processing and Web server architecture. For startup, router freezing, runners, and deployment, see Server lifecycle and deployment.
References: aiohttp/web_app.py• L368-396 aiohttp/abc.py• L25-48 aiohttp/abc.py• L50-97
Change checklist
When these files or sections are changed, remember to consider these:
- Keep route-definition helpers,
RouteTableDef, andUrlDispatcher.add_routes()aligned so decorator routes and direct routes create the same route contract. - When dispatch precedence or method selection changes, review the
404and405paths and theAllowheader behavior together. - When host or domain matching changes, review matched subapplication priority and request hosts with and without ports.
- When response body or header rules change, check content length, chunked transfer, compression,
HEAD, and empty-body status codes together. - When static path or symlink rules change, review directory listings, encoded filenames, absolute paths, and traversal checks as one security boundary.
- When file metadata, cache conditions, or range handling changes, keep
ETag,Last-Modified,Content-Range,Accept-Ranges,Accept-Encoding, andVaryconsistent. - When response compression or JSON encoding changes, keep pre-encoded bodies from receiving a second encoding pass and keep the JSON content type contract intact.
- When static file options change, keep the option flow from
UrlDispatcher.add_static()throughStaticResourcetoFileResponsealigned, including the text charset and versioned URL contracts.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A request matches a path but no registered method | The router returns 405 and lists allowed methods. | Register the method on that resource or define it on the class-based view. |
| A host does not match a domain rule for a subapplication | The subapplication is skipped and another resource may handle the request or the router returns 404. | Register the required port behavior and test hosts with and without ports. |
| A static request resolves outside its root | The server returns 404 instead of exposing the path. | Keep the static sandbox enabled unless trusted symlink access is required. |
| A static target is a directory while index display is off | The server returns 403. | Enable index display only when directory listings are intended. |
| A response changes status or headers after preparation | The response rejects the change because headers may already be sent. | Set status, headers, and body settings before prepare() or the first write. |
| A response already has a content encoding and compression is enabled | The body keeps its existing encoding instead of receiving a second encoding pass. | Treat the existing Content-Encoding as authoritative. |
| A file validator fails or a requested range is invalid | The server returns 412, 304, or 416 instead of the file body. | Send validators and ranges that match the current representation or accept the full response. |
| A static target is missing, unreadable, or not a regular file | File serving returns an HTTP error instead of a file body. | Check the served directory and file permissions before publishing the route. |
Key files
| File | Why to read it |
|---|---|
| aiohttp/web_routedef.py | Defines the public forms used to describe method, view, and static routes. |
| aiohttp/web_urldispatcher.py | Explains resource matching, route selection, URL building, subapplication dispatch, and static-prefix behavior. |
| aiohttp/web_app.py | Shows how the application owns the router and invokes the matched handler. |
| aiohttp/web_response.py | Defines normal, streaming, and JSON response behavior. |
| aiohttp/web_fileresponse.py | Defines file metadata, cache conditions, ranges, compressed variants, charset selection, and file transfer. |
| aiohttp/web_exceptions.py | Defines the status-bearing errors used as HTTP responses. |