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()
>>> session.close()
New in version 0.15.2.
The client session supports context manager protocol for self closing:
>>> with aiohttp.ClientSession() as session:
>>> resp = yield from session.get('http://python.org')
>>> yield from resp.release()
>>> session.closed
True
New in version 0.17.
-
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.
- loop –
event loop used for processing HTTP requests.
If loop is
None
the constructor borrows it from connector if specified.asyncio.get_event_loop()
is used for getting default event loop otherwise. - 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
toClientRequest
Changed in version 0.16: response_class default changed from
None
toClientResponse
-
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.
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:
-
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:
-
coroutine
options
(url, *, allow_redirects=True, **kwargs)[source]¶ Perform an
OPTIONS
request.In order to modify inner
request
parameters, provide kwargs.Parameters:
-
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.
Basic API¶
While we encourage ClientSession
usage we also provide simple
coroutines for making HTTP requests.
Basic API is good for performing simple HTTP requests without keep-aliving, cookies and complex connection stuff like properly configured SSL certification chaining.
-
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) – Requested 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)
- loop – event 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()
-
coroutine
aiohttp.client.
get
(url, **kwargs)[source]¶ Perform a GET request.
Parameters: Returns: ClientResponse
or derived from
-
coroutine
aiohttp.client.
options
(url, **kwargs)[source]¶ Perform a OPTIONS request.
Parameters: Returns: ClientResponse
or derived from
-
coroutine
aiohttp.client.
head
(url, **kwargs)[source]¶ Perform a HEAD request.
Parameters: Returns: ClientResponse
or derived from
-
coroutine
aiohttp.client.
delete
(url, **kwargs)[source]¶ Perform a DELETE request.
Parameters: Returns: ClientResponse
or derived from
-
coroutine
aiohttp.client.
post
(url, *, data=None, **kwargs)[source]¶ Perform a POST request.
Parameters: Returns: ClientResponse
or derived from
Connectors¶
Connectors are transports for aiohttp client API.
There are standard connectors:
TCPConnector
for regular TCP sockets (both HTTP and HTTPS schemas supported).ProxyConnector
for connecting via HTTP proxy.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 is 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
orNone
mean no timeout. - keepalive_timeout (float) – timeout for connection reusing
after releasing (optional). Values
0
orNone
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 isNone
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).
- loop – event 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.
-
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.
- conn_timeout (float) – timeout for connection establishing
(optional). Values
TCPConnector¶
-
class
aiohttp.connector.
TCPConnector
(*, verify_ssl=True, fingerprint=None, use_dns_cache=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 fromBaseConnector
.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.
- use_dns_cache (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.
New in version 0.17.
- resolve (bool) –
alias for use_dns_cache parameter.
Deprecated since version 0.17.
- family (int) – TCP socket family,
AF_INET
by default (IPv4). For IPv6 useAF_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.
-
ssl_context
¶ ssl.SSLContext
instance for https requests, read-only property.
-
family
¶ TCP socket family e.g.
socket.AF_INET
orsocket.AF_INET6
Read-only property.
-
dns_cache
¶ Use quick lookup in internal DNS cache for host names if
True
.Read-only
bool
property.New in version 0.17.
-
cached_hosts
¶ The cache of resolved hosts if
dns_cache
is enabled.Read-only
types.MappingProxyType
property.New in version 0.17.
-
resolved_hosts
¶ Alias for
cached_hosts
Deprecated since version 0.17.
-
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_dns_cache
(self, host=None, port=None)[source]¶ Clear internal DNS cache.
Remove specific entry if both host and port are specified, clear all cache otherwise.
New in version 0.17.
-
clear_resolved_hosts
(self, host=None, port=None)[source]¶ Alias for
clear_dns_cache()
.Deprecated since version 0.17.
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 fromTCPConnector
.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
isTrue
).Changed in version 0.16: force_close parameter changed to
True
by default.-
proxy_auth
¶ Proxy auth info, read-only
BasicAuth
property orNone
for proxy without authentication.New in version 0.16.
- proxy (str) – URL for proxy, e.g.
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 fromBaseConnector
.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
Connection¶
-
class
aiohttp.connector.
Connection
[source]¶ Encapsulates single connection in connector object.
End user should never create
Connection
instances manually but get it byBaseConnector.connect()
coroutine.-
loop
¶ Event loop used for connection
-