HTTP Server Reference

Changed in version 0.12: The module was deeply refactored in backward incompatible manner.


The Request object contains all the information about an incoming HTTP request.

Every handler accepts a request instance as the first positional parameter.


You should never create the Request instance manually – aiohttp.web does it for you.

class aiohttp.web.Request[source]

A string representing the scheme of the request.

The scheme is 'https' if transport for request handling is SSL or secure_proxy_ssl_header is matching.

'http' otherwise.

Read-only str property.


HTTP method, read-only property.

The value is upper-cased str like "GET", "POST", "PUT" etc.


HTTP version of request, Read-only property.

Returns aiohttp.protocol.HttpVersion instance.


HOST header of request, Read-only property.

Returns str or None if HTTP request has no HOST header.


The URL including PATH_INFO and the query string. e.g, /app/blog?id=10

Read-only str property.


The URL including PATH INFO without the host or scheme. e.g., /app/blog

Read-only str property.


The query string in the URL, e.g., id=10

Read-only str property.


A multidict with all the variables in the query string.

Read-only MultiDictProxy lazy property.


A multidict with all the variables in the POST parameters. POST property available only after coroutine call.

Read-only MultiDictProxy.

Raises RuntimeError:
 if was not called before accessing the property.

A case-insensitive multidict proxy with all headers.

Read-only CIMultiDictProxy property.


True if keep-alive connection enabled by HTTP client and protocol version supports it, otherwise False.

Read-only bool property.


Read-only property with AbstractMatchInfo instance for result of route resolving.


Exact type of property depends on used router. If app.router is UrlDispatcher the property contains UrlMappingMatchInfo instance.


An Application instance used to call request handler, Read-only property.


An transport used to process request, Read-only property.

The property can be used, for example, for getting IP address of client’s peer:

peername = request.transport.get_extra_info('peername')
if peername is not None:
    host, port = peername

A multidict of all request’s cookies.

Read-only MultiDictProxy lazy property.


A FlowControlStreamReader instance, input stream for reading request’s BODY.

Read-only property.

New in version 0.15.


Return True if request has HTTP BODY, False otherwise.

Read-only bool property.

New in version 0.16.


A FlowControlStreamReader instance, input stream for reading request’s BODY.

Read-only property.

Deprecated since version 0.15: Use content instead.


Read-only property with content part of Content-Type header.

Returns str like 'text/html'


Returns value is 'application/octet-stream' if no Content-Type header present in HTTP headers according to RFC 2616


Read-only property that specifies the encoding for the request’s BODY.

The value is parsed from the Content-Type HTTP header.

Returns str like 'utf-8' or None if Content-Type has no charset information.


Read-only property that returns length of the request’s BODY.

The value is parsed from the Content-Length HTTP header.

Returns int or None if Content-Length is absent.

coroutine read()[source]

Read request body, returns bytes object with body content.


The method does store read data internally, subsequent read() call will return the same value.

coroutine text()[source]

Read request body, decode it using charset encoding or UTF-8 if no encoding was specified in MIME-type.

Returns str with body content.


The method does store read data internally, subsequent text() call will return the same value.

coroutine json(*, loader=json.loads)[source]

Read request body decoded as json.

The method is just a boilerplate coroutine implemented as:

def json(self, *, loader=json.loads):
    body = yield from self.text()
    return loader(body)
Parameters:loader (callable) – any callable that accepts str and returns dict with parsed JSON (json.loads() by default).


The method does store read data internally, subsequent json() call will return the same value.

coroutine post()[source]

A coroutine that reads POST parameters from request body.

Returns MultiDictProxy instance filled with parsed data.

If method is not POST, PUT or PATCH or content_type is not empty or application/x-www-form-urlencoded or multipart/form-data returns empty multidict.


The method does store read data internally, subsequent post() call will return the same value.

coroutine release()[source]

Release request.

Eat unread part of HTTP BODY if present.


User code may never call release(), all required work will be processed by aiohttp.web internal machinery.

Response classes

For now, aiohttp.web has two classes for the HTTP response: StreamResponse and Response.

Usually you need to use the second one. StreamResponse is intended for streaming data, while Response contains HTTP BODY as an attribute and sends own content as single piece with the correct Content-Length HTTP header.

For sake of design decisions Response is derived from StreamResponse parent class.

The response supports keep-alive handling out-of-the-box if request supports it.

You can disable keep-alive by force_close() though.

The common case for sending an answer from web-handler is returning a Response instance:

def handler(request):
    return Response("All right!")


class aiohttp.web.StreamResponse(*, status=200, reason=None)[source]

The base class for the HTTP response handling.

Contains methods for setting HTTP response headers, cookies, response status code, writing HTTP response BODY and so on.

The most important thing you should know about response — it is Finite State Machine.

That means you can do any manipulations with headers, cookies and status code only before start() called.

Once you call start() any change of the HTTP header part will raise RuntimeError exception.

Any write() call after write_eof() is also forbidden.

  • status (int) – HTTP status code, 200 by default.
  • reason (str) – HTTP reason. If param is None reason will be calculated basing on status parameter. Otherwise pass str with arbitrary status explanation..

Read-only bool property, True if start() has been called, False otherwise.


Read-only property for HTTP response status code, int.

200 (OK) by default.


Read-only property for HTTP response reason, str.

set_status(status, reason=None)[source]

Set status and reason.

reason value is auto calculated if not specified (None).


Read-only property, copy of Request.keep_alive by default.

Can be switched to False by force_close() call.


Disable keep_alive for connection. There are no ways to enable it back.


Read-only bool property, True if compression is enabled.

False by default.

New in version 0.14.


Enable compression.

When force is False (default) compression is used only when deflate is in Accept-Encoding request’s header.

Accept-Encoding is not checked if force is True.

New in version 0.14.

See also



Read-only property, indicates if chunked encoding is on.

Can be enabled by enable_chunked_encoding() call.

New in version 0.14.


Enables chunked encoding for response. There are no ways to disable it back. With enabled chunked encoding each write() operation encoded in separate chunk.

New in version 0.14.

See also



CIMultiDict instance for outgoing HTTP headers.


An instance of http.cookies.SimpleCookie for outgoing cookies.


Direct setting up Set-Cookie header may be overwritten by explicit calls to cookie manipulation.

We are encourage using of cookies and set_cookie(), del_cookie() for cookie manipulations.

Convenient way for setting cookies, allows to specify some additional properties like max_age in a single call.

  • name (str) – cookie name
  • value (str) – cookie value (will be converted to str if value has another type).
  • expires – expiration date (optional)
  • domain (str) – cookie domain (optional)
  • max_age (int) – defines the lifetime of the cookie, in seconds. The delta-seconds value is a decimal non- negative integer. After delta-seconds seconds elapse, the client should discard the cookie. A value of zero means the cookie should be discarded immediately. (optional)
  • path (str) – specifies the subset of URLs to which this cookie applies. (optional, '/' by default)
  • secure (bool) – attribute (with no value) directs the user agent to use only (unspecified) secure means to contact the origin server whenever it sends back this cookie. The user agent (possibly under the user’s control) may determine what level of security it considers appropriate for “secure” cookies. The secure should be considered security advice from the server to the user agent, indicating that it is in the session’s interest to protect the cookie contents. (optional)
  • httponly (bool) – True if the cookie HTTP only (optional)
  • version (int) – a decimal integer, identifies to which version of the state management specification the cookie conforms. (Optional, version=1 by default)

Changed in version 0.14.3: Default value for path changed from None to '/'.

Deletes cookie.

  • name (str) – cookie name
  • domain (str) – optional cookie domain
  • path (str) – optional cookie path, '/' by default

Changed in version 0.14.3: Default value for path changed from None to '/'.


Content-Length for outgoing response.


Content part of Content-Type for outgoing response.


Charset aka encoding part of Content-Type for outgoing response.

The value converted to lower-case on attribute assigning.

Parameters:request (aiohttp.web.Request) – HTTP request object, that the response answers.

Send HTTP header. You should not change any header data after calling this method.


Send byte-ish data as the part of response BODY.

start() must be called before.

Raises TypeError if data is not bytes, bytearray or memoryview instance.

Raises RuntimeError if start() has not been called.

Raises RuntimeError if write_eof() has been called.

coroutine drain()[source]

A coroutine to let the write buffer of the underlying transport a chance to be flushed.

The intended use is to write:

yield from resp.drain()

Yielding from drain() gives the opportunity for the loop to schedule the write operation and flush the buffer. It should especially be used when a possibly large amount of data is written to the transport, and the coroutine does not yield-from between calls to write().

New in version 0.14.

coroutine write_eof()[source]

A coroutine may be called as a mark of the HTTP response processing finish.

Internal machinery will call this method at the end of the request processing if needed.

After write_eof() call any manipulations with the response object are forbidden.


class aiohttp.web.Response(*, status=200, headers=None, content_type=None, body=None, text=None)[source]

The most usable response class, inherited from StreamResponse.

Accepts body argument for setting the HTTP response BODY.

The actual body sending happens in overridden write_eof().

  • body (bytes) – response’s BODY
  • status (int) – HTTP status code, 200 OK by default.
  • headers ( – HTTP headers that should be added to response’s ones.
  • text (str) – response’s BODY
  • content_type (str) – response’s content type

Read-write attribute for storing response’s content aka BODY, bytes.

Setting body also recalculates content_length value.

Resetting body (assigning None) sets content_length to None too, dropping Content-Length HTTP header.


Read-write attribute for storing response’s content, represented as str, str.

Setting str also recalculates content_length value and body value

Resetting body (assigning None) sets content_length to None too, dropping Content-Length HTTP header.


class aiohttp.web.WebSocketResponse(*, timeout=10.0, autoclose=True, autoping=True, protocols=())[source]

Class for handling server-side websockets.

After starting (by start() call) the response you cannot use write() method but should to communicate with websocket client by send_str(), receive() and others.


Starts websocket. After the call you can use websocket methods.

Parameters:request (aiohttp.web.Request) – HTTP request object, that the response answers.
Raises HTTPException:
 if websocket handshake has failed.

Performs checks for request data to figure out if websocket can be started on the request.

If can_start() call is success then start() will success too.

Parameters:request (aiohttp.web.Request) – HTTP request object, that the response answers.
Returns:(ok, protocol) pair, ok is True on success, protocol is websocket subprotocol which is passed by client and accepted by server (one of protocols sequence from WebSocketResponse ctor). protocol may be None if client and server subprotocols are nit overlapping.


The method newer raises exception.


Read-only property, True if connection has been closed or in process of closing. MSG_CLOSE message has been received from peer.


Read-only property, close code from peer. It is set to None on opened connection.


Websocket subprotocol chosen after start() call.

May be None if server and client protocols are not overlapping.


Returns last occured exception or None.


Send MSG_PING to peer.

Parameters:message – optional payload of ping message, str (converted to UTF-8 encoded bytes) or bytes.
Raises RuntimeError:
 if connections is not started or closing.

Send unsolicited MSG_PONG to peer.

Parameters:message – optional payload of pong message, str (converted to UTF-8 encoded bytes) or bytes.
Raises RuntimeError:
 if connections is not started or closing.

Send data to peer as MSG_TEXT message.


data (str) – data to send.


Send data to peer as MSG_BINARY message.


data – data to send.

coroutine close(*, code=1000, message=b'')[source]

A coroutine that initiates closing handshake by sending MSG_CLOSE message.

  • code (int) – closing code
  • message – optional payload of pong message, str (converted to UTF-8 encoded bytes) or bytes.
Raises RuntimeError:

if connection is not started or closing

coroutine receive()[source]

A coroutine that waits upcoming data message from peer and returns it.

The coroutine implicitly handles MSG_PING, MSG_PONG and MSG_CLOSE without returning the message.

It process ping-pong game and performs closing handshake internally.

After websocket closing raises WSClientDisconnectedError with connection closing data.

Raises RuntimeError:
 if connection is not started
Raise:WSClientDisconnectedError on closing.
coroutine receive_str()[source]

A coroutine that calls receive_mgs() but also asserts the message type is MSG_TEXT.

Return str:peer’s message content.
Raises TypeError:
 if message is MSG_BINARY.
coroutine receive_bytes()[source]

A coroutine that calls receive_mgs() but also asserts the message type is MSG_BINARY.

Return bytes:peer’s message content.
Raises TypeError:
 if message is MSG_TEXT.

New in version 0.14.

Application and Router


Application is a synonym for web-server.

To get fully working example, you have to make application, register supported urls in router and create a server socket with aiohttp.RequestHandlerFactory as a protocol factory. RequestHandlerFactory could be constructed with make_handler().

Application contains a router instance and a list of callbacks that will be called during application finishing.

Application is a dict, so you can use it as registry for arbitrary properties for later access from handler via property:

app = Application(loop=loop)
app['database'] = yield from aiopg.create_engine(**db_config)

def handler(request):
    with (yield from['database']) as conn:
        conn.execute("DELETE * FROM table")
class aiohttp.web.Application(*, loop=None, router=None, logger=<default>, middlewares=(), **kwargs)[source]

The class inherits dict.

  • loop

    event loop used for processing HTTP requests.

    If param is None asyncio.get_event_loop() used for getting default event loop, but we strongly recommend to use explicit loops everywhere.

  • instance, the system creates UrlDispatcher by default if router is None.
  • logger

    logging.Logger instance for storing application logs.

    By default the value is logging.getLogger("aiohttp.web")

  • middlewares

    sequence of middleware factories, see Middlewares for details.

    New in version 0.13.


Read-only property that returns router instance.


logging.Logger instance for storing application logs.


event loop used for processing HTTP requests.


Creates HTTP protocol factory for handling requests.

Parameters:kwargs – additional parameters for RequestHandlerFactory constructor.

You should pass result of the method as protocol_factory to create_server(), e.g.:

loop = asyncio.get_event_loop()

app = Application(loop=loop)

# setup route table
# app.router.add_route(...)

yield from loop.create_server(app.make_handler(),
                              '', 8080)
coroutine finish()[source]

A coroutine that should be called after server stopping.

This method executes functions registered by register_on_finish() in LIFO order.

If callback raises an exception, the error will be stored by call_exception_handler() with keys: message, exception, application.

register_on_finish(self, func, *args, **kwargs):

Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register_on_finish(). It is possible to register the same function and arguments more than once.

During the call of finish() all functions registered are called in last in, first out order.

func may be either regular function or coroutine, finish() will un-yield (yield from) the later.


Application object has route attribute but has no add_router method. The reason is: we want to support different route implementations (even maybe not url-matching based but traversal ones).

For sake of that fact we have very trivial ABC for AbstractRouter: it should have only AbstractRouter.resolve() coroutine.

No methods for adding routes or route reversing (getting URL by route name). All those are router implementation details (but, sure, you need to deal with that methods after choosing the router for your application).


RequestHandlerFactory is responsible for creating HTTP protocol objects that can handle http connections.


List of all currently oppened connections.


A coroutine that should be called to close all opened connections.


For dispatching URLs to handlers aiohttp.web uses routers.

Router is any object that implements AbstractRouter interface.

aiohttp.web provides an implementation called UrlDispatcher.

Application uses UrlDispatcher as router() by default.

class aiohttp.web.UrlDispatcher[source]

Straightforward url-matching router, implements for access to named routes.

Before running Application you should fill route table first by calling add_route() and add_static().

Handler lookup is performed by iterating on added routes in FIFO order. The first matching route will be used to call corresponding handler.

If on route creation you specify name parameter the result is named route.

Named route can be retrieved by app.router[name] call, checked for existence by name in app.router etc.

See also

Route classes

add_route(method, path, handler, *, name=None, expect_handler=None)[source]

Append handler to the end of route table.

path may be either constant string like '/a/b/c' or
variable rule like '/a/{var}' (see handling variable pathes)

Pay attention please: handler is converted to coroutine internally when it is a regular function.

  • method (str) –

    HTTP method for route. Should be one of 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' or '*' for any method.

    The parameter is case-insensitive, e.g. you can push 'get' as well as 'GET'.

  • path (str) – route path
  • handler (callable) – route handler
  • name (str) – optional route name.
  • expect_handler (coroutine) – optional expect header handler.

new PlainRoute or DynamicRoute instance.

add_static(prefix, path, *, name=None, expect_handler=None, chunk_size=256*1024)[source]

Adds router for returning static files.

Useful for handling static content like images, javascript and css files.


Use add_static() for development only. In production, static content should be processed by web servers like nginx or apache.

  • prefix (str) – URL path prefix for handled static files
  • path (str) – path to the folder in file system that contains handled static files.
  • name (str) – optional route name.
  • expect_handler (coroutine) – optional expect header handler.
  • chunk_size (int) –

    size of single chunk for file downloading, 64Kb by default.

    Increasing chunk_size parameter to, say, 1Mb may increase file downloading speed but consumes more memory.

    New in version 0.16.

Returns:new StaticRoute instance.
coroutine resolve(requst)[source]

A coroutine that returns AbstractMatchInfo for request.

The method never raises exception, but returns AbstractMatchInfo instance with:

  1. route asigned to SystemRoute instance

  2. handler which raises HTTPNotFound or HTTPMethodNotAllowed on handler’s execution if there is no registered route for request.

    Middlewares can process that exceptions to render pretty-looking error page for example.

Used by internal machinery, end user unlikely need to call the method.

Changed in version 0.14: The method don’t raise HTTPNotFound and HTTPMethodNotAllowed anymore.


Default router UrlDispatcher operates with routes.

User should not instantiate route classes by hand but can give named route instance by router[name] if he have added route by UrlDispatcher.add_route() or UrlDispatcher.add_static() calls with non-empty name parameter.

The main usage of named routes is constructing URL by route name for passing it into template engine for example:

url = app.router['route_name'].url(query={'a': 1, 'b': 2})

There are three concrete route classes:* DynamicRoute for urls with variable pathes spec.

class aiohttp.web.Route[source]

Base class for routes served by UrlDispatcher.


HTTP method handled by the route, e.g. GET, POST etc.


handler that processes the route.


Name of the route.


Abstract method, accepts URL path and returns dict with parsed path parts for UrlMappingMatchInfo or None if the route cannot handle given path.

The method exists for internal usage, end user unlikely need to call it.

url(*, query=None, **kwargs)[source]

Abstract method for constructing url handled by the route.

query is a mapping or list of (name, value) pairs for specifying query part of url (parameter is processed by urlencode()).

Other available parameters depends on concrete route class and described in descendant classes.

class aiohttp.web.PlainRoute[source]

The route class for handling plain URL path, e.g. "/a/b/c"

url(*, parts, query=None)[source]

Construct url, doesn’t accepts extra parameters:

>>> route.url(query={'d': 1, 'e': 2})
class aiohttp.web.DynamicRoute[source]

The route class for handling variable path, e.g. "/a/{name1}/{name2}"

url(*, parts, query=None)[source]

Construct url with given dynamic parts:

>>> route.url(parts={'name1': 'b', 'name2': 'c'},
              query={'d': 1, 'e': 2})
class aiohttp.web.StaticRoute[source]

The route class for handling static files, created by UrlDispatcher.add_static() call.

url(*, filename, query=None)[source]

Construct url for given filename:

>>> route.url(filename='img/logo.png', query={'param': 1})
class aiohttp.web.SystemRoute

The route class for internal purposes.

Now it has used for handling 404: Not Found and 405: Method Not Allowed.


Always raises RuntimeError, SystemRoute should not be used in url construction expressions.


After route matching web application calls found handler if any.

Matching result can be accessible from handler as Request.match_info attribute.

In general the result may be any object derived from AbstractMatchInfo (UrlMappingMatchInfo for default UrlDispatcher router).

class aiohttp.web.UrlMappingMatchInfo[source]

Inherited from dict and AbstractMatchInfo. Dict items are given from Route.match() call return value.


Route instance for url matching.


class aiohttp.web.FileField

A namedtuple() that is returned as multidict value by Request.POST() if field is uploaded file.


Field name


File name as specified by uploading (client) side.


An io.IOBase instance with content of uploaded file.


MIME type of uploaded file, 'text/plain' by default.

See also

File Uploads