HTTP Client Reference

Client Session

Client session is the recommended interface for making HTTP requests.

Session encapsulates connection pool (connector instance) and supports keep-alives by default.

Usage example:

>>> import aiohttp
>>> session = aiohttp.ClientSession()
>>> resp = yield from session.get('http://python.org')
>>> resp
<ClientResponse(python.org/) [200]>
>>> data = yield from resp.read()

New in version 0.15.2.

class aiohttp.client.ClientSession(*, connector=None, loop=None, cookies=None, headers=None, auth=None, request_class=ClientRequest, response_class=ClientResponse, ws_response_class=ClientWebSocketResponse)[source]

The class for creating client sessions and making requests.

Parameters:
  • connector (aiohttp.connector.BaseConnector) – BaseConnector sub-class instance to support connection pooling.
  • loopevent loop used for processing HTTP requests. If param is None, asyncio.get_event_loop() is used for getting default event loop, but we strongly recommend to use explicit loops everywhere. (optional)
  • cookies (dict) – Cookies to send with the request (optional)
  • headers (dict) – HTTP Headers to send with the request (optional)
  • auth (aiohttp.helpers.BasicAuth) – BasicAuth named tuple that represents HTTP Basic Auth (optional)
  • request_class – Request class implementation. ClientRequest by default.
  • response_class – Response class implementation. ClientResponse by default.
  • ws_response_class

    WebSocketResponse class implementation. ClientWebSocketResponse by default.

    New in version 0.16.

Changed in version 0.16: request_class default changed from None to ClientRequest

Changed in version 0.16: response_class default changed from None to ClientResponse

closed

True if the session has been closed, False otherwise.

A read-only property.

connector

aiohttp.connector.BaseConnector derived instance used for the session.

A read-only property.

cookies

The session cookies, http.cookies.SimpleCookie instance.

A read-only property. Overriding session.cookies = new_val is forbidden, but you may modify the object inplace if needed.

coroutine request(method, url, *, params=None, data=None, headers=None, auth=None, allow_redirects=True, max_redirects=10, encoding='utf-8', version=HttpVersion(major=1, minor=1), compress=None, chunked=None, expect100=False, read_until_eof=True)[source]

Performs an asynchronous http request. Returns a response object.

Parameters:
  • method (str) – HTTP method
  • url (str) – Request URL
  • params (dict) – Parameters to be sent in the query string of the new request (optional)
  • data – Dictionary, bytes, or file-like object to send in the body of the request (optional)
  • headers (dict) – HTTP Headers to send with the request (optional)
  • auth (aiohttp.helpers.BasicAuth) – BasicAuth named tuple that represents HTTP Basic Auth (optional)
  • allow_redirects (bool) – If set to False, do not follow redirects. True by default (optional).
  • version (aiohttp.protocol.HttpVersion) – Request http version (optional)
  • compress (bool) – Set to True if request has to be compressed with deflate encoding. None by default (optional).
  • chunked (int) – Set to chunk size for chunked transfer encoding. None by default (optional).
  • expect100 (bool) – Expect 100-continue response from server. False by default (optional).
  • read_until_eof (bool) – Read response until eof if response does not have Content-Length header. True by default (optional).
coroutine get(url, *, allow_redirects=True, **kwargs)[source]

Perform a GET request.

In order to modify inner request parameters, provide kwargs.

Parameters:
  • url (str) – Request URL
  • allow_redirects (bool) – If set to False, do not follow redirects. True by default (optional).
coroutine post(url, *, data=None, **kwargs)[source]

Perform a POST request.

In order to modify inner request parameters, provide kwargs.

Parameters:
  • url (str) – Request URL
  • data – Dictionary, bytes, or file-like object to send in the body of the request (optional)
coroutine put(url, *, data=None, **kwargs)[source]

Perform a PUT request.

In order to modify inner request parameters, provide kwargs.

Parameters:
  • url (str) – Request URL
  • data – Dictionary, bytes, or file-like object to send in the body of the request (optional)
coroutine delete(url, **kwargs)[source]

Perform a DELETE request.

In order to modify inner request parameters, provide kwargs.

Parameters:url (str) – Request URL
coroutine head(url, *, allow_redirects=False, **kwargs)[source]

Perform a HEAD request.

In order to modify inner request parameters, provide kwargs.

Parameters:
  • url (str) – Request URL
  • allow_redirects (bool) – If set to False, do not follow redirects. False by default (optional).
coroutine options(url, *, allow_redirects=True, **kwargs)[source]

Perform an OPTIONS request.

In order to modify inner request parameters, provide kwargs.

Parameters:
  • url (str) – Request URL
  • allow_redirects (bool) – If set to False, do not follow redirects. True by default (optional).
coroutine patch(url, *, data=None, **kwargs)[source]

Perform a PATCH request.

In order to modify inner request parameters, provide kwargs.

Parameters:
  • url (str) – Request URL
  • data – Dictionary, bytes, or file-like object to send in the body of the request (optional)
coroutine ws_connect(url, *, protocols=(), timeout=10.0 autoclose=True, autoping=True)[source]

Create a websocket connection. Returns a ClientWebSocketResponse object.

Parameters:
  • url (str) – Websocket server url
  • protocols (tuple) – Websocket protocols
  • timeout (float) – Timeout for websocket read. 10 seconds by default
  • autoclose (bool) – Automatically close websocket connection on close message from server. If autoclose is False them close procedure has to be handled manually
  • autoping (bool) – automatically send pong on ping message from server

New in version 0.16.

close()[source]

Close underlying connector.

Release all acquired resources.

detach()[source]

Detach connector from session without closing the former.

Session is switched to closed state anyway.

request coroutine

coroutine aiohttp.client.request(method, url, *, params=None, data=None, headers=None, cookies=None, files=None, auth=None, allow_redirects=True, max_redirects=10, encoding='utf-8', version=HttpVersion(major=1, minor=1), compress=None, chunked=None, expect100=False, connector=None, loop=None, read_until_eof=True, request_class=None, response_class=None)[source]

Perform an asynchronous http request. Return a response object (ClientResponse or derived from).

Parameters:
  • method (str) – HTTP method
  • url (str) – Request URL
  • params (dict) – Parameters to be sent in the query string of the new request (optional)
  • data – Dictionary, bytes, or file-like object to send in the body of the request (optional)
  • headers (dict) – HTTP Headers to send with the request (optional)
  • cookies (dict) – Cookies to send with the request (optional)
  • auth (aiohttp.helpers.BasicAuth) – BasicAuth named tuple that represents HTTP Basic Auth (optional)
  • allow_redirects (bool) – If set to False, do not follow redirects. True by default (optional).
  • version (aiohttp.protocol.HttpVersion) – Request http version (optional)
  • compress (bool) – Set to True if request has to be compressed with deflate encoding. None by default (optional).
  • chunked (int) – Set to chunk size for chunked transfer encoding. None by default (optional).
  • expect100 (bool) – Expect 100-continue response from server. False by default (optional).
  • connector (aiohttp.connector.BaseConnector) – BaseConnector sub-class instance to support connection pooling.
  • read_until_eof (bool) – Read response until eof if response does not have Content-Length header. True by default (optional).
  • request_class – Custom Request class implementation (optional)
  • response_class – Custom Response class implementation (optional)
  • loopevent loop used for processing HTTP requests. If param is None, asyncio.get_event_loop() is used for getting default event loop, but we strongly recommend to use explicit loops everywhere. (optional)

Usage:

>>> import aiohttp
>>> resp = yield from aiohttp.request('GET', 'http://python.org/')
>>> resp
<ClientResponse(python.org/) [200]>
>>> data = yield from resp.read()

Connectors

Connectors are transports for aiohttp client API.

There are standard connectors:

  1. TCPConnector for regular TCP sockets (both HTTP and HTTPS schemas supported).
  2. ProxyConnector for connecting via HTTP proxy.
  3. UnixConnector for connecting via UNIX socket (it’s used mostly for testing purposes).

All connector classes should be derived from BaseConnector.

By default all connectors except ProxyConnector support keep-alive connections (behavior controlled by force_close constructor’s parameter).

BaseConnector

class aiohttp.connector.BaseConnector(*, conn_timeout=None, keepalive_timeout=30, limit=None, share_cookies=False, force_close=False, loop=None)[source]

Base class for all connectors.

Parameters:
  • conn_timeout (float) – timeout for connection establishing (optional). Values 0 or None mean no timeout.
  • keepalive_timeout (float) – timeout for connection reusing after releasing (optional). Values 0 or None mean no timeout.
  • limit (int) – limit for simultaneous connections to the same endpoint. Endpoints are the same if they are have equal (host, port, is_ssl) triple. If limit is None the connector has no limit.
  • share_cookies (bool) – update cookies on connection processing (optional, deprecated).
  • force_close (bool) – do close underlying sockets after connection releasing (optional).
  • loopevent loop used for handling connections. If param is None, asyncio.get_event_loop() is used for getting default event loop, but we strongly recommend to use explicit loops everywhere. (optional)

Deprecated since version 0.15.2: share_cookies parameter is deprecated, use ClientSession for hadling cookies for client connections.

closed

Read-only property, True if connector is closed.

force_close

Read-only property, True if connector should ultimately close connections on releasing.

New in version 0.16.

limit

The limit for simultaneous connections to the same endpoint.

Endpoints are the same if they are have equal (host, port, is_ssl) triple.

If limit is None the connector has no limit (default).

Read-only property.

New in version 0.16.

close()[source]

Close all opened connections.

coroutine connect(request)[source]

Get a free connection from pool or create new one if connection is absent in the pool.

The call may be paused if limit is exhausted until used connetions returns to pool.

Parameters:request (aiohttp.client.ClientRequest) – request object which is connection initiator.
Returns:Connection object.
coroutine _create_connection(req)[source]

Abstract method for actual connection establishing, should be overriden in subclasses.

TCPConnector

class aiohttp.connector.TCPConnector(*, verify_ssl=True, fingerprint=None, resolve=False, family=socket.AF_INET, ssl_context=None, conn_timeout=None, keepalive_timeout=30, limit=None, share_cookies=False, force_close=False, loop=None)[source]

Connector for working with HTTP and HTTPS via TCP sockets.

The most common transport. When you don’t know what connector type to use, use a TCPConnector instance.

TCPConnector inherits from BaseConnector.

Constructor accepts all parameters suitable for BaseConnector plus several TCP-specific ones:

Parameters:
  • verify_ssl (bool) – Perform SSL certificate validation for HTTPS requests (enabled by default). May be disabled to skip validation for sites with invalid certificates.
  • fingerprint (bytes) –

    Pass the binary md5, sha1, or sha256 digest of the expected certificate in DER format to verify that the certificate the server presents matches. Useful for certificate pinning.

    New in version 0.16.

  • resolve (bool) –

    use internal cache for DNS lookups, False by default.

    Enabling an option may speedup connection establishing a bit but may introduce some side effects also.

  • family (int) – TCP socket family, AF_INET by default (IPv4). For IPv6 use AF_INET6.
  • ssl_context (ssl.SSLContext) –

    ssl context used for processing HTTPS requests (optional).

    ssl_context may be used for configuring certification authority channel, supported SSL options etc.

verify_ssl

Check ssl certifications if True.

Read-only bool property.

ssl_context

ssl.SSLContext instance for https requests, read-only property.

family

TCP socket family e.g. socket.AF_INET or socket.AF_INET6

Read-only property.

resolve

Use quick lookup in internal DNS cache for host names if True.

Read-only bool property.

resolve

Use quick lookup in internal DNS cache for host names if True.

Read-only bool property.

resolved_hosts

The cache of resolved hosts if resolve is enabled.

Read-only types.MappingProxyType property.

fingerprint

md5, sha1, or sha256 hash of the expected certificate in DER format, or None if no certificate fingerprint check required.

Read-only bytes property.

New in version 0.16.

clear_resolved_hosts(self, host=None, port=None)[source]

Clear internal DNS cache.

Remove specific entry if both host and port are specified, clear all cache otherwise.

ProxyConnector

class aiohttp.connector.ProxyConnector(proxy, *, proxy_auth=None, conn_timeout=None, keepalive_timeout=30, limit=None, share_cookies=False, force_close=True, loop=None)[source]

HTTP Proxy connector.

Use ProxyConnector for sending HTTP/HTTPS requests through HTTP proxy.

ProxyConnector is inherited from TCPConnector.

Usage:

>>> conn = ProxyConnector(proxy="http://some.proxy.com")
>>> session = ClientSession(connector=conn)
>>> resp = yield from session.get('http://python.org')

Constructor accepts all parameters suitable for TCPConnector plus several proxy-specific ones:

Parameters:
  • proxy (str) – URL for proxy, e.g. "http://some.proxy.com".
  • proxy_auth (aiohttp.helpers.BasicAuth) – basic-auth authenthication info used for proxies with authorization.

Note

ProxyConnector in opposite to all other connectors doesn’t support keep-alives by default (force_close is True).

Changed in version 0.16: force_close parameter changed to True by default.

proxy

Proxy URL, read-only str property.

proxy_auth

Proxy auth info, read-only BasicAuth property or None for proxy without authentication.

New in version 0.16.

UnixConnector

class aiohttp.connector.UnixConnector(path, *, conn_timeout=None, keepalive_timeout=30, limit=None, share_cookies=False, force_close=False, loop=None)[source]

Unix socket connector.

Use ProxyConnector for sending HTTP/HTTPS requests through UNIX Sockets as underlying transport.

UNIX sockets are handy for writing tests and making very fast connections between processes on the same host.

UnixConnector is inherited from BaseConnector.

Usage:

>>> conn = UnixConnector(path='/path/to/socket')
>>> session = ClientSession(connector=conn)
>>> resp = yield from session.get('http://python.org')

Constructor accepts all parameters suitable for BaseConnector plus unix-specific one:

Parameters:path (str) – Unix socket path
path

Path to UNIX socket, read-only str property.

Connection

class aiohttp.connector.Connection[source]

Encapsulates single connection in connector object.

End user should never create Connection instances manually but get it by BaseConnector.connect() coroutine.

closed

bool read-only property, True if connection was closed, released or detached.

loop

Event loop used for connection

close()[source]

Close connection with forcibly closing underlying socket.

release()[source]

Release connection back to connector.

Underlying socket is not closed, the connection may be reused later if timeout (30 seconds by default) for connection was not expired.

detach()[source]

Detach underlying socket from connection.

Underlying socket is not closed, next close() or release() calls don’t return socket to free pool.