Client Reference¶
Client Session¶
Client session is the recommended interface for making HTTP requests.
Session encapsulates a connection pool (connector instance) and supports keepalives by default. Unless you are connecting to a large, unknown number of different servers over the lifetime of your application, it is suggested you use a single session for the lifetime of your application to benefit from connection pooling.
Usage example:
import aiohttp
import asyncio
async def fetch(client):
async with client.get('http://python.org') as resp:
assert resp.status == 200
return await resp.text()
async def main():
async with aiohttp.ClientSession() as client:
html = await fetch(client)
print(html)
asyncio.run(main())
The client session supports the context manager protocol for self closing.
- class aiohttp.ClientSession(base_url=None, *, connector=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, request_class=ClientRequest, response_class=ClientResponse, ws_response_class=ClientWebSocketResponse, version=aiohttp.HttpVersion11, cookie_jar=None, connector_owner=True, raise_for_status=False, timeout=sentinel, auto_decompress=True, trust_env=False, requote_redirect_url=True, trace_configs=None, middlewares=(), read_bufsize=2**16, max_line_size=8190, max_field_size=8190, fallback_charset_resolver=lambda r, b: ..., ssl_shutdown_timeout=0)[source]¶
The class for creating client sessions and making requests.
- Parameters:
base_url –
Base part of the URL (optional) If set, allows to join a base part to relative URLs in request calls. If the URL has a path it must have a trailing
/(as in https://docs.aiohttp.org/en/stable/).Note that URL joining follows RFC 3986. This means, in the most common case the request URLs should have no leading slash, e.g.:
session = ClientSession(base_url="http://example.com/foo/") await session.request("GET", "bar") # request for http://example.com/foo/bar await session.request("GET", "/bar") # request for http://example.com/bar
Added in version 3.8.
Changed in version 3.12: Added support for overriding the base URL with an absolute one in client sessions.
connector (aiohttp.BaseConnector) – BaseConnector sub-class instance to support connection pooling.
cookies (dict) – Cookies to send with the request (optional)
headers –
HTTP Headers to send with every request (optional).
May be either iterable of key-value pairs or
Mapping(e.g.dict,CIMultiDict).skip_auto_headers –
set of headers for which autogeneration should be skipped.
aiohttp autogenerates headers like
User-AgentorContent-Typeif these headers are not explicitly passed. Usingskip_auto_headersparameter allows to skip that generation. Note thatContent-Lengthautogeneration can’t be skipped.auth (aiohttp.BasicAuth) – an object that represents HTTP Basic Authorization (optional). It will be included with any request. However, if the
_base_urlparameter is set, the request URL’s origin must match the base URL’s origin; otherwise, the default auth will not be included.json_serialize (collections.abc.Callable) –
Json serializer callable.
By default
json.dumps()function.request_class (aiohttp.ClientRequest) – Custom class to use for client requests.
response_class (ClientResponse) – Custom class to use for client responses.
ws_response_class (ClientWebSocketResponse) – Custom class to use for websocket responses.
version – supported HTTP version,
HTTP 1.1by default.cookie_jar –
Cookie Jar,
AbstractCookieJarinstance.By default every session instance has own private cookie jar for automatic cookies processing but user may redefine this behavior by providing own jar implementation.
One example is not processing cookies at all when working in proxy mode.
If no cookie processing is needed, a
aiohttp.DummyCookieJarinstance can be provided.connector_owner (bool) –
Close connector instance on session closing.
Setting the parameter to
Falseallows to share connection pool between sessions without sharing session state: cookies etc.raise_for_status (bool) –
Automatically call
ClientResponse.raise_for_status()for each response,Falseby default.This parameter can be overridden when making a request, e.g.:
client_session = aiohttp.ClientSession(raise_for_status=True) resp = await client_session.get(url, raise_for_status=False) async with resp: assert resp.status == 200
Set the parameter to
Trueif you needraise_for_statusfor most of cases but overrideraise_for_statusfor those requests where you need to handle responses with status 400 or higher.You can also provide a coroutine which takes the response as an argument and can raise an exception based on custom logic, e.g.:
async def custom_check(response): if response.status not in {201, 202}: raise RuntimeError('expected either 201 or 202') text = await response.text() if 'apple pie' not in text: raise RuntimeError('I wanted to see "apple pie" in response') client_session = aiohttp.ClientSession(raise_for_status=custom_check) ...
As with boolean values, you’re free to set this on the session and/or overwrite it on a per-request basis.
timeout –
- a
ClientTimeoutsettings structure, 300 seconds (5min) total timeout, 30 seconds socket connect timeout by default.
Added in version 3.3.
Changed in version 3.10.9: The default value for the
sock_connecttimeout has been changed to 30 seconds.- a
auto_decompress (bool) –
Automatically decompress response body (
Trueby default).Added in version 2.3.
trust_env (bool) –
Trust environment settings for proxy configuration if the parameter is
True(Falseby default). See Proxy support for more information.Get proxy credentials from
~/.netrcfile if present.Get HTTP Basic Auth credentials from
~/.netrcfile if present.If
NETRCenvironment variable is set, read from file specified there rather than from~/.netrc.See also
.netrcdocumentation: https://www.gnu.org/software/inetutils/manual/html_node/The-_002enetrc-file.htmlAdded in version 2.3.
Changed in version 3.0: Added support for
~/.netrcfile.Changed in version 3.9: Added support for reading HTTP Basic Auth credentials from
~/.netrcfile.requote_redirect_url (bool) –
- Apply URL requoting for redirection URLs if
automatic redirection is enabled (
Trueby default).
Added in version 3.5.
trace_configs – A list of
TraceConfiginstances used for client tracing.None(default) is used for request tracing disabling. See Tracing Reference for more information.middlewares –
- A sequence of middleware instances to apply to all session requests.
Each middleware must match the
ClientMiddlewareTypesignature.()(empty tuple, default) is used when no middleware is needed. See Client Middleware for more information.
Added in version 3.12.
read_bufsize (int) –
- Size of the read buffer (
ClientResponse.content). 64 KiB by default.
Added in version 3.7.
- Size of the read buffer (
max_line_size (int) – Maximum allowed size of lines in responses.
max_field_size (int) – Maximum allowed size of header fields in responses.
fallback_charset_resolver (Callable[[ClientResponse,bytes],str]) –
A callable that accepts a
ClientResponseand thebytescontents, and returns astrwhich will be used as the encoding parameter tobytes.decode().This function will be called when the charset is not known (e.g. not specified in the Content-Type header). The default function simply defaults to
utf-8.Added in version 3.8.6.
ssl_shutdown_timeout (float) –
(DEPRECATED) This parameter is deprecated and will be removed in aiohttp 4.0. Grace period for SSL shutdown handshake on TLS connections when the connector is closed (
0seconds by default). By default (0), SSL connections are aborted immediately when the connector is closed, without performing the shutdown handshake. During normal operation, SSL connections use Python’s default SSL shutdown behavior. Setting this to a positive value (e.g.,0.1) will perform a graceful shutdown when closing the connector, notifying the remote peer which can help prevent “connection reset” errors at the cost of additional cleanup time. This timeout is passed to the underlyingTCPConnectorwhen one is created automatically. Note: On Python versions prior to 3.11, only a value of0is supported; other values will trigger a warning.Added in version 3.12.5.
Changed in version 3.12.11: Changed default from
0.1to0to abort SSL connections immediately when the connector is closed. Added support forssl_shutdown_timeout=0on all Python versions. ARuntimeWarningis issued when non-zero values are passed on Python < 3.11.Deprecated since version 3.12.11: This parameter is deprecated and will be removed in aiohttp 4.0.
- closed¶
Trueif the session has been closed,Falseotherwise.A read-only property.
- connector¶
aiohttp.BaseConnectorderived instance used for the session.A read-only property.
- cookie_jar¶
The session cookies,
AbstractCookieJarinstance.Gives access to cookie jar’s content and modifiers.
A read-only property.
- requote_redirect_url¶
aiohttp re quote’s redirect urls by default, but some servers require exact url from location header. To disable re-quote system set
requote_redirect_urlattribute toFalse.Added in version 2.1.
Note
This parameter affects all subsequent requests.
Deprecated since version 3.5: The attribute modification is deprecated.
- loop¶
A loop instance used for session creation.
A read-only property.
Deprecated since version 3.5.
- timeout¶
Default client timeouts,
ClientTimeoutinstance. The value can be tuned by passing timeout parameter toClientSessionconstructor.Added in version 3.7.
- headers¶
HTTP Headers that sent with every request
May be either iterable of key-value pairs or
Mapping(e.g.dict,CIMultiDict).Added in version 3.7.
- skip_auto_headers¶
Set of headers for which autogeneration skipped.
frozensetofstroristr(optional)Added in version 3.7.
- auth¶
An object that represents HTTP Basic Authorization.
BasicAuth(optional)Added in version 3.7.
- json_serialize¶
Json serializer callable.
By default
json.dumps()function.Added in version 3.7.
- connector_owner¶
Should connector be closed on session closing
bool(optional)Added in version 3.7.
- raise_for_status¶
Should
ClientResponse.raise_for_status()be called for each responseEither
boolorcollections.abc.CallableAdded in version 3.7.
- auto_decompress¶
Should the body response be automatically decompressed
booldefault isTrueAdded in version 3.7.
- trust_env¶
Trust environment settings for proxy configuration or ~/.netrc file if present. See Proxy support for more information.
booldefault isFalseAdded in version 3.7.
- trace_configs¶
A list of
TraceConfiginstances used for client tracing.None(default) is used for request tracing disabling. See Tracing Reference for more information.Added in version 3.7.
- async request(method, url, *, params=None, data=None, json=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, allow_redirects=True, max_redirects=10, compress=None, chunked=None, expect100=False, raise_for_status=None, read_until_eof=True, proxy=None, proxy_auth=None, timeout=sentinel, ssl=True, server_hostname=None, proxy_headers=None, trace_request_ctx=None, middlewares=None, read_bufsize=None, auto_decompress=None, max_line_size=None, max_field_size=None)[source]¶
Performs an asynchronous HTTP request. Returns a response object that should be used as an async context manager.
- Parameters:
method (str) – HTTP method
url – Request URL,
URLorstrthat will be encoded withURL(seeURLto skip encoding).params –
Mapping, iterable of tuple of key/value pairs or string to be sent as parameters in the query string of the new request. Ignored for subsequent redirected requests (optional)
Allowed values are:
collections.abc.Mappinge.g.dict,multidict.MultiDictormultidict.MultiDictProxycollections.abc.Iterablee.g.tupleorliststrwith preferably url-encoded content (Warning: content will not be encoded by aiohttp)
data – The data to send in the body of the request. This can be a
FormDataobject or anything that can be passed intoFormData, e.g. a dictionary, bytes, or file-like object. (optional)json – Any json compatible python object (optional). json and data parameters could not be used at the same time.
cookies (dict) –
- HTTP Cookies to send with
the request (optional)
Global session cookies and the explicitly set cookies will be merged when sending the request.
Added in version 3.5.
headers (dict) – HTTP Headers to send with the request (optional)
skip_auto_headers –
set of headers for which autogeneration should be skipped.
aiohttp autogenerates headers like
User-AgentorContent-Typeif these headers are not explicitly passed. Usingskip_auto_headersparameter allows to skip that generation.auth (aiohttp.BasicAuth) – an object that represents HTTP Basic Authorization (optional)
allow_redirects (bool) – Whether to process redirects or not. When
True, redirects are followed (up tomax_redirectstimes) and logged intoClientResponse.historyandtrace_configs. WhenFalse, the original response is returned.Trueby default (optional).max_redirects (int) – Maximum number of redirects to follow.
TooManyRedirectsis raised if the number is exceeded. Ignored whenallow_redirects=False.10by default.compress (bool) – Set to
Trueif request has to be compressed with deflate encoding. If compress can not be combined with a Content-Encoding and Content-Length headers.Noneby default (optional).chunked (int) – Enable chunked transfer encoding. It is up to the developer to decide how to chunk data streams. If chunking is enabled, aiohttp encodes the provided chunks in the “Transfer-encoding: chunked” format. If chunked is set, then the Transfer-encoding and content-length headers are disallowed.
Noneby default (optional).expect100 (bool) – Expect 100-continue response from server.
Falseby default (optional).raise_for_status (bool) –
- Automatically call
ClientResponse.raise_for_status()for response if set to
True. If set toNonevalue fromClientSessionwill be used.Noneby default (optional).
Added in version 3.4.
- Automatically call
read_until_eof (bool) – Read response until EOF if response does not have Content-Length header.
Trueby default (optional).proxy_auth (aiohttp.BasicAuth) – an object that represents proxy HTTP Basic Authorization (optional)
timeout (int) –
override the session’s timeout.
Changed in version 3.3: The parameter is
ClientTimeoutinstance,floatis still supported for sake of backward compatibility.If
floatis passed it is a total timeout (in seconds).ssl –
- SSL validation mode.
Truefor default SSL check (
ssl.create_default_context()is used),Falsefor skip SSL certificate validation,aiohttp.Fingerprintfor fingerprint validation,ssl.SSLContextfor custom SSL certificate validation.Supersedes verify_ssl, ssl_context and fingerprint parameters.
Added in version 3.0.
- SSL validation mode.
server_hostname (str) –
Sets or overrides the host name that the target server’s certificate will be matched against.
See
asyncio.loop.create_connection()for more information.Added in version 3.9.
proxy_headers (collections.abc.Mapping) –
HTTP headers to send to the proxy if the parameter proxy has been provided.
Added in version 2.3.
trace_request_ctx –
Object used to give as a kw param for each new
TraceConfigobject instantiated, used to give information to the tracers that is only available at request time.Added in version 3.0.
middlewares –
- A sequence of middleware instances to apply to this request only.
Each middleware must match the
ClientMiddlewareTypesignature.Noneby default which uses session middlewares. See Client Middleware for more information.
Added in version 3.12.
read_bufsize (int) –
- Size of the read buffer (
ClientResponse.content). Noneby default, it means that the session global value is used.
Added in version 3.7.
- Size of the read buffer (
auto_decompress (bool) – Automatically decompress response body. Overrides
ClientSession.auto_decompress. May be used to enable/disable auto decompression on a per-request basis.max_line_size (int) – Maximum allowed size of lines in responses.
max_field_size (int) – Maximum allowed size of header fields in responses.
- Return ClientResponse:
a
client responseobject.
- async get(url, *, allow_redirects=True, **kwargs)[source]¶
Perform a
GETrequest. Returns an async context manager.In order to modify inner
requestparameters, provide kwargs.- Parameters:
allow_redirects (bool) – Whether to process redirects or not. When
True, redirects are followed and logged intoClientResponse.history. WhenFalse, the original response is returned.Trueby default (optional).
- Return ClientResponse:
a
client responseobject.
- async post(url, *, data=None, **kwargs)[source]¶
Perform a
POSTrequest. Returns an async context manager.In order to modify inner
requestparameters, provide kwargs.- Parameters:
- Return ClientResponse:
a
client responseobject.
- async put(url, *, data=None, **kwargs)[source]¶
Perform a
PUTrequest. Returns an async context manager.In order to modify inner
requestparameters, provide kwargs.- Parameters:
- Return ClientResponse:
a
client responseobject.
- async delete(url, **kwargs)[source]¶
Perform a
DELETErequest. Returns an async context manager.In order to modify inner
requestparameters, provide kwargs.- Parameters:
- Return ClientResponse:
a
client responseobject.
- async head(url, *, allow_redirects=False, **kwargs)[source]¶
Perform a
HEADrequest. Returns an async context manager.In order to modify inner
requestparameters, provide kwargs.- Parameters:
allow_redirects (bool) – Whether to process redirects or not. When
True, redirects are followed and logged intoClientResponse.history. WhenFalse, the original response is returned.Falseby default (optional).
- Return ClientResponse:
a
client responseobject.
- async options(url, *, allow_redirects=True, **kwargs)[source]¶
Perform an
OPTIONSrequest. Returns an async context manager.In order to modify inner
requestparameters, provide kwargs.- Parameters:
allow_redirects (bool) – Whether to process redirects or not. When
True, redirects are followed and logged intoClientResponse.history. WhenFalse, the original response is returned.Trueby default (optional).
- Return ClientResponse:
a
client responseobject.
- async patch(url, *, data=None, **kwargs)[source]¶
Perform a
PATCHrequest. Returns an async context manager.In order to modify inner
requestparameters, provide kwargs.- Parameters:
- Return ClientResponse:
a
client responseobject.
- async ws_connect(url, *, method='GET', protocols=(), timeout=sentinel, auth=None, autoclose=True, autoping=True, heartbeat=None, origin=None, params=None, headers=None, proxy=None, proxy_auth=None, ssl=True, verify_ssl=None, fingerprint=None, ssl_context=None, proxy_headers=None, compress=0, max_msg_size=4194304)[source]¶
Create a websocket connection. Returns a
ClientWebSocketResponseasync context manager object.- Parameters:
url – Websocket server url,
URLorstrthat will be encoded withURL(seeURLto skip encoding).protocols (tuple) – Websocket protocols
timeout – a
ClientWSTimeouttimeout for websocket. By default, the value ClientWSTimeout(ws_receive=None, ws_close=10.0) is used (10.0seconds for the websocket to close).Nonemeans no timeout will be used.auth (aiohttp.BasicAuth) – an object that represents HTTP Basic Authorization (optional)
autoclose (bool) – Automatically close websocket connection on close message from server. If autoclose is False then close procedure has to be handled manually.
Trueby defaultautoping (bool) – automatically send pong on ping message from server.
Trueby defaultheartbeat (float) – Send ping message every heartbeat seconds and wait pong response, if pong response is not received then close connection. The timer is reset on any data reception.(optional)
origin (str) – Origin header to send to server(optional)
params –
Mapping, iterable of tuple of key/value pairs or string to be sent as parameters in the query string of the new request. Ignored for subsequent redirected requests (optional)
Allowed values are:
collections.abc.Mappinge.g.dict,multidict.MultiDictormultidict.MultiDictProxycollections.abc.Iterablee.g.tupleorliststrwith preferably url-encoded content (Warning: content will not be encoded by aiohttp)
headers (dict) – HTTP Headers to send with the request (optional)
proxy_auth (aiohttp.BasicAuth) – an object that represents proxy HTTP Basic Authorization (optional)
ssl –
- SSL validation mode.
Truefor default SSL check (
ssl.create_default_context()is used),Falsefor skip SSL certificate validation,aiohttp.Fingerprintfor fingerprint validation,ssl.SSLContextfor custom SSL certificate validation.Supersedes verify_ssl, ssl_context and fingerprint parameters.
Added in version 3.0.
- SSL validation mode.
verify_ssl (bool) –
Perform SSL certificate validation for HTTPS requests (enabled by default). May be disabled to skip validation for sites with invalid certificates.
Added in version 2.3.
Deprecated since version 3.0: Use
ssl=Falsefingerprint (bytes) –
Pass the SHA256 digest of the expected certificate in DER format to verify that the certificate the server presents matches. Useful for certificate pinning.
Note: use of MD5 or SHA1 digests is insecure and deprecated.
Added in version 2.3.
Deprecated since version 3.0: Use
ssl=aiohttp.Fingerprint(digest)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.
Added in version 2.3.
Deprecated since version 3.0: Use
ssl=ssl_contextproxy_headers (dict) –
HTTP headers to send to the proxy if the parameter proxy has been provided.
Added in version 2.3.
compress (int) –
- Enable Per-Message Compress Extension support.
0 for disable, 9 to 15 for window bit support. Default value is 0.
Added in version 2.3.
max_msg_size (int) –
- maximum size of read websocket message,
4 MB by default. To disable the size limit use
0.
Added in version 3.3.
method (str) –
- HTTP method to establish WebSocket connection,
'GET'by default.
Added in version 3.5.
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 keepaliving, cookies and complex connection stuff like properly configured SSL certification chaining.
- async aiohttp.request(method, url, *, params=None, data=None, json=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, allow_redirects=True, max_redirects=10, compress=False, chunked=None, expect100=False, raise_for_status=None, read_until_eof=True, proxy=None, proxy_auth=None, timeout=sentinel, ssl=True, server_hostname=None, proxy_headers=None, trace_request_ctx=None, read_bufsize=None, auto_decompress=None, max_line_size=None, max_field_size=None, version=aiohttp.HttpVersion11, connector=None)[source]¶
Asynchronous context manager for performing an asynchronous HTTP request. Returns a
ClientResponseresponse object. Use as an async context manager.- Parameters:
method (str) – HTTP method
url – Request URL,
URLorstrthat will be encoded withURL(seeURLto skip encoding).params –
Mapping, iterable of tuple of key/value pairs or string to be sent as parameters in the query string of the new request. Ignored for subsequent redirected requests (optional)
Allowed values are:
collections.abc.Iterablee.g.tupleor
strwith preferably url-encoded content(Warning: content will not be encoded by aiohttp)
data – The data to send in the body of the request. This can be a
FormDataobject or anything that can be passed intoFormData, e.g. a dictionary, bytes, or file-like object. (optional)json – Any json compatible python object (optional). json and data parameters could not be used at the same time.
cookies (dict) – HTTP Cookies to send with the request (optional)
headers (dict) – HTTP Headers to send with the request (optional)
skip_auto_headers –
set of headers for which autogeneration should be skipped.
aiohttp autogenerates headers like
User-AgentorContent-Typeif these headers are not explicitly passed. Usingskip_auto_headersparameter allows to skip that generation.auth (aiohttp.BasicAuth) – an object that represents HTTP Basic Authorization (optional)
allow_redirects (bool) – Whether to process redirects or not. When
True, redirects are followed (up tomax_redirectstimes) and logged intoClientResponse.historyandtrace_configs. WhenFalse, the original response is returned.Trueby default (optional).max_redirects (int) – Maximum number of redirects to follow.
TooManyRedirectsis raised if the number is exceeded. Ignored whenallow_redirects=False.10by default.compress (bool) – Set to
Trueif request has to be compressed with deflate encoding. If compress can not be combined with a Content-Encoding and Content-Length headers.Noneby default (optional).chunked (int) – Enables chunked transfer encoding. It is up to the developer to decide how to chunk data streams. If chunking is enabled, aiohttp encodes the provided chunks in the “Transfer-encoding: chunked” format. If chunked is set, then the Transfer-encoding and content-length headers are disallowed.
Noneby default (optional).expect100 (bool) – Expect 100-continue response from server.
Falseby default (optional).raise_for_status (bool) –
- Automatically call
ClientResponse.raise_for_status()for response if set toTrue. If set toNonevalue fromClientSessionwill be used.Noneby default (optional).
Added in version 3.4.
read_until_eof (bool) – Read response until EOF if response does not have Content-Length header.
Trueby default (optional).proxy_auth (aiohttp.BasicAuth) – an object that represents proxy HTTP Basic Authorization (optional)
timeout – a
ClientTimeoutsettings structure, 300 seconds (5min) total timeout, 30 seconds socket connect timeout by default.ssl –
SSL validation mode.
Truefor default SSL check (ssl.create_default_context()is used),Falsefor skip SSL certificate validation,aiohttp.Fingerprintfor fingerprint validation,ssl.SSLContextfor custom SSL certificate validation.Supersedes verify_ssl, ssl_context and fingerprint parameters.
server_hostname (str) –
Sets or overrides the host name that the target server’s certificate will be matched against.
See
asyncio.loop.create_connection()for more information.proxy_headers (collections.abc.Mapping) – HTTP headers to send to the proxy if the parameter proxy has been provided.
trace_request_ctx – Object used to give as a kw param for each new
TraceConfigobject instantiated, used to give information to the tracers that is only available at request time.read_bufsize (int) –
- Size of the read buffer (
ClientResponse.content). Noneby default, it means that the session global value is used.
Added in version 3.7.
- Size of the read buffer (
auto_decompress (bool) – Automatically decompress response body. May be used to enable/disable auto decompression on a per-request basis.
max_line_size (int) – Maximum allowed size of lines in responses.
max_field_size (int) – Maximum allowed size of header fields in responses.
version (aiohttp.protocol.HttpVersion) – Request HTTP version,
HTTP 1.1by default. (optional)connector (aiohttp.BaseConnector) – BaseConnector sub-class instance to support connection pooling. (optional)
- Return ClientResponse:
a
client responseobject.
Usage:
import aiohttp async def fetch(): async with aiohttp.request('GET', 'http://python.org/') as resp: assert resp.status == 200 print(await resp.text())
Connectors¶
Connectors are transports for aiohttp client API.
There are standard connectors:
TCPConnectorfor regular TCP sockets (both HTTP and HTTPS schemes supported).UnixConnectorfor connecting via UNIX socket (it’s used mostly for testing purposes).
All connector classes should be derived from BaseConnector.
By default all connectors support keep-alive connections (behavior is controlled by force_close constructor’s parameter).
- class aiohttp.BaseConnector(*, keepalive_timeout=15, force_close=False, limit=100, limit_per_host=0, enable_cleanup_closed=False, loop=None)[source]¶
Base class for all connectors.
- Parameters:
keepalive_timeout (float) – timeout for connection reusing after releasing (optional). Values
0. For disabling keep-alive feature useforce_close=Trueflag.limit (int) – total number simultaneous connections. If limit is
0the connector has no limit (default: 100).limit_per_host (int) – limit simultaneous connections to the same endpoint. Endpoints are the same if they are have equal
(host, port, is_ssl)triple. If limit is0the connector has no limit (default: 0).force_close (bool) – close underlying sockets after connection releasing (optional).
enable_cleanup_closed (bool) –
some SSL servers do not properly complete SSL shutdown process, in that case asyncio leaks SSL connections. If this parameter is set to True, aiohttp additionally aborts underlining transport after 2 seconds. It is off by default.
For Python version 3.12.7+, or 3.13.1 and later, this parameter is ignored because the asyncio SSL connection leak is fixed in these versions of Python.
loop –
event loop used for handling connections. If param is
None,asyncio.get_event_loop()is used for getting default event loop.Deprecated since version 2.0.
- closed¶
Read-only property,
Trueif connector is closed.
- force_close¶
Read-only property,
Trueif connector should ultimately close connections on releasing.
- limit¶
The total number for simultaneous connections. If limit is 0 the connector has no limit. The default limit size is 100.
- limit_per_host¶
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_per_host is
0the connector has no limit per host.Read-only property.
- async 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
limitis exhausted until used connections returns to pool.- Parameters:
request (aiohttp.ClientRequest) – request object which is connection initiator.
- Returns:
Connectionobject.
- class aiohttp.AddrInfoType¶
Refer to
aiohappyeyeballs.AddrInfoTypefor more info.
Warning
Be sure to use aiohttp.AddrInfoType rather than
aiohappyeyeballs.AddrInfoType to avoid import breakage, as
it is likely to be removed from aiohappyeyeballs in the
future.
- class aiohttp.SocketFactoryType¶
Refer to
aiohappyeyeballs.SocketFactoryTypefor more info.
Warning
Be sure to use aiohttp.SocketFactoryType rather than
aiohappyeyeballs.SocketFactoryType to avoid import breakage,
as it is likely to be removed from aiohappyeyeballs in the
future.
- class aiohttp.TCPConnector(*, ssl=True, verify_ssl=True, fingerprint=None, use_dns_cache=True, ttl_dns_cache=10, family=0, ssl_context=None, local_addr=None, resolver=None, keepalive_timeout=sentinel, force_close=False, limit=100, limit_per_host=0, enable_cleanup_closed=False, timeout_ceil_threshold=5, happy_eyeballs_delay=0.25, interleave=None, loop=None, socket_factory=None, ssl_shutdown_timeout=0)[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
TCPConnectorinstance.TCPConnectorinherits fromBaseConnector.Constructor accepts all parameters suitable for
BaseConnectorplus several TCP-specific ones:- param ssl:
- SSL validation mode.
Truefor default SSL check (
ssl.create_default_context()is used),Falsefor skip SSL certificate validation,aiohttp.Fingerprintfor fingerprint validation,ssl.SSLContextfor custom SSL certificate validation.Supersedes verify_ssl, ssl_context and fingerprint parameters.
Added in version 3.0.
- SSL validation mode.
- 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.
Deprecated since version 2.3: Pass verify_ssl to
ClientSession.get()etc.fingerprint (bytes) –
pass the SHA256 digest of the expected certificate in DER format to verify that the certificate the server presents matches. Useful for certificate pinning.
Note: use of MD5 or SHA1 digests is insecure and deprecated.
Deprecated since version 2.3: Pass verify_ssl to
ClientSession.get()etc.use_dns_cache (bool) –
use internal cache for DNS lookups,
Trueby default.Enabling an option may speedup connection establishing a bit but may introduce some side effects also.
ttl_dns_cache (int) –
expire after some seconds the DNS entries,
Nonemeans cached forever. By default 10 seconds (optional).In some environments the IP addresses related to a specific HOST can change after a specific time. Use this option to keep the DNS cache updated refreshing each entry after N seconds.
limit (int) – total number simultaneous connections. If limit is
0the connector has no limit (default: 100).limit_per_host (int) – limit simultaneous connections to the same endpoint. Endpoints are the same if they are have equal
(host, port, is_ssl)triple. If limit is0the connector has no limit (default: 0).resolver (aiohttp.abc.AbstractResolver) –
custom resolver instance to use.
aiohttp.DefaultResolverby default (asynchronous ifaiodns>=1.1is installed).Custom resolvers allow to resolve hostnames differently than the way the host is configured.
The resolver is
aiohttp.ThreadedResolverby default, asynchronous version is pretty robust but might fail in very rare cases.family (int) –
TCP socket family, both IPv4 and IPv6 by default. For IPv4 only use
socket.AF_INET, for IPv6 only –socket.AF_INET6.family is
0by default, that means both IPv4 and IPv6 are accepted. To specify only concrete version please passsocket.AF_INETorsocket.AF_INET6explicitly.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.
local_addr (tuple) – tuple of
(local_host, local_port)used to bind socket locally if specified.force_close (bool) – close underlying sockets after connection releasing (optional).
enable_cleanup_closed (bool) – Some ssl servers do not properly complete SSL shutdown process, in that case asyncio leaks SSL connections. If this parameter is set to True, aiohttp additionally aborts underlining transport after 2 seconds. It is off by default.
happy_eyeballs_delay (float) –
The amount of time in seconds to wait for a connection attempt to complete, before starting the next attempt in parallel. This is the “Connection Attempt Delay” as defined in RFC 8305. To disable Happy Eyeballs, set this to
None. The default value recommended by the RFC is 0.25 (250 milliseconds).Added in version 3.10.
interleave (int) –
controls address reordering when a host name resolves to multiple IP addresses. If
0or unspecified, no reordering is done, and addresses are tried in the order returned by the resolver. If a positive integer is specified, the addresses are interleaved by address family, and the given integer is interpreted as “First Address Family Count” as defined in RFC 8305. The default is0if happy_eyeballs_delay is not specified, and1if it is.Added in version 3.10.
socket_factory (SocketFactoryType) –
This function takes an
AddrInfoTypeand is used in lieu ofsocket.socket()when creating TCP connections.Added in version 3.12.
ssl_shutdown_timeout (float) –
(DEPRECATED) This parameter is deprecated and will be removed in aiohttp 4.0. Grace period for SSL shutdown on TLS connections when the connector is closed (
0seconds by default). By default (0), SSL connections are aborted immediately when the connector is closed, without performing the shutdown handshake. During normal operation, SSL connections use Python’s default SSL shutdown behavior. Setting this to a positive value (e.g.,0.1) will perform a graceful shutdown when closing the connector, notifying the remote server which can help prevent “connection reset” errors at the cost of additional cleanup time. Note: On Python versions prior to 3.11, only a value of0is supported; other values will trigger a warning.Added in version 3.12.5.
Changed in version 3.12.11: Changed default from
0.1to0to abort SSL connections immediately when the connector is closed. Added support forssl_shutdown_timeout=0on all Python versions. ARuntimeWarningis issued when non-zero values are passed on Python < 3.11.Deprecated since version 3.12.11: This parameter is deprecated and will be removed in aiohttp 4.0.
- family¶
TCP socket family e.g.
socket.AF_INETorsocket.AF_INET6Read-only property.
- cached_hosts¶
The cache of resolved hosts if
dns_cacheis enabled.Read-only
types.MappingProxyTypeproperty.
- class aiohttp.UnixConnector(path, *, conn_timeout=None, keepalive_timeout=30, limit=100, force_close=False, loop=None)[source]¶
Unix socket connector.
Use
UnixConnectorfor 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.
UnixConnectoris inherited fromBaseConnector.Usage:
conn = UnixConnector(path='/path/to/socket') session = ClientSession(connector=conn) async with session.get('http://python.org') as resp: ...
Constructor accepts all parameters suitable for
BaseConnectorplus UNIX-specific one:- Parameters:
path (str) – Unix socket path
- class aiohttp.Connection¶
Encapsulates single connection in connector object.
End user should never create
Connectioninstances manually but get it byBaseConnector.connect()coroutine.- loop¶
Event loop used for connection
Deprecated since version 3.5.
- transport¶
Connection transport
- close()¶
Close connection with forcibly closing underlying socket.
- release()¶
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.
Response object¶
- class aiohttp.ClientResponse[source]¶
Client response returned by
aiohttp.ClientSession.request()and family.User never creates the instance of ClientResponse class but gets it from API calls.
ClientResponsesupports async context manager protocol, e.g.:resp = await client_session.get(url) async with resp: assert resp.status == 200
After exiting from
async withblock response object will be released (seerelease()method).- version¶
Response’s version,
HttpVersioninstance.
- ok¶
Boolean representation of HTTP status code (
bool).Trueifstatusis less than400; otherwise,False.
- connection¶
Connectionused for handling response.
- content¶
Payload stream, which contains response’s BODY (
StreamReader). It supports various reading methods depending on the expected format. When chunked transfer encoding is used by the server, allows retrieving the actual http chunks.Reading from the stream may raise
aiohttp.ClientPayloadErrorif the response object is closed before response receives all data or in case if any transfer encoding related errors like malformed chunked encoding of broken compression data.
- cookies¶
HTTP cookies of response (Set-Cookie HTTP header,
SimpleCookie).Note
Since
SimpleCookieuses cookie name as the key, cookies with the same name but different domains or paths will be overwritten. Only the last cookie with a given name will be accessible via this attribute.To access all cookies, including duplicates with the same name, use
response.headers.getall('Set-Cookie').The session’s cookie jar will correctly store all cookies, even if they are not accessible via this attribute.
- headers¶
A case-insensitive multidict proxy with HTTP headers of response,
CIMultiDictProxy.
- raw_headers¶
Unmodified HTTP headers of response as unconverted bytes, a sequence of
(key, value)pairs.
- links¶
Link HTTP header parsed into a
MultiDictProxy.For each link, key is link param rel when it exists, or link url as
strotherwise, and value isMultiDictProxyof link params and url at key url asURLinstance.Added in version 3.2.
- content_type¶
Read-only property with content part of Content-Type header.
Note
Returns
'application/octet-stream'if no Content-Type header is present or the value contains invalid syntax according to RFC 9110. To see the original header checkresp.headers["Content-Type"].To make sure Content-Type header is not present in the server reply, use
headersorraw_headers, e.g.'Content-Type' not in resp.headers.
- charset¶
Read-only property that specifies the encoding for the request’s BODY.
The value is parsed from the Content-Type HTTP header.
Returns
strlike'utf-8'orNoneif no Content-Type header present in HTTP headers or it has no charset information.
- content_disposition¶
Read-only property that specified the Content-Disposition HTTP header.
Instance of
ContentDispositionorNoneif no Content-Disposition header present in HTTP headers.
- history¶
A
SequenceofClientResponseobjects of preceding requests (earliest request first) if there were redirects, an empty sequence otherwise.
- close()[source]¶
Close response and underlying connection.
For keep-alive support see
release().
- async read()[source]¶
Read the whole response’s body as
bytes.Close underlying connection if data reading gets an error, release connection otherwise.
Raise an
aiohttp.ClientResponseErrorif the data can’t be read.- Return bytes:
read BODY.
- release()[source]¶
It is not required to call release on the response object. When the client fully receives the payload, the underlying connection automatically returns back to pool. If the payload is not fully read, the connection is closed
- raise_for_status()[source]¶
Raise an
aiohttp.ClientResponseErrorif the response status is 400 or higher.Do nothing for success responses (less than 400).
- async text(encoding=None)[source]¶
Read response’s body and return decoded
strusing specified encoding parameter.If encoding is
Nonecontent encoding is determined from the Content-Type header, or using thefallback_charset_resolverfunction.Close underlying connection if data reading gets an error, release connection otherwise.
- Parameters:
encoding (str) – text encoding used for BODY decoding, or
Nonefor encoding autodetection (default).- Raises:
UnicodeDecodeErrorif decoding fails. See alsoget_encoding().- Return str:
decoded BODY
- async json(*, encoding=None, loads=json.loads, content_type='application/json')[source]¶
Read response’s body as JSON, return
dictusing specified encoding and loader. If data is not still available areadcall will be done.If response’s content-type does not match content_type parameter
aiohttp.ContentTypeErrorget raised. To disable content type check passNonevalue.- Parameters:
encoding (str) –
text encoding used for BODY decoding, or
Nonefor encoding autodetection (default).By the standard JSON encoding should be
UTF-8but practice beats purity: some servers return non-UTF responses. Autodetection works pretty fine anyway.loads (collections.abc.Callable) – callable used for loading JSON data,
json.loads()by default.content_type (str) – specify response’s content-type, if content type does not match raise
aiohttp.ClientResponseError. To disable content-type check, passNoneas value. (default: application/json).
- Returns:
BODY as JSON data parsed by loads parameter or
Noneif BODY is empty or contains white-spaces only.
- request_info¶
A
typing.NamedTuplewith request URL and headers fromClientRequestobject,aiohttp.RequestInfoinstance.
ClientWebSocketResponse¶
To connect to a websocket server aiohttp.ws_connect() or
aiohttp.ClientSession.ws_connect() coroutines should be used, do
not create an instance of class ClientWebSocketResponse
manually.
- class aiohttp.ClientWebSocketResponse[source]¶
Class for handling client-side websockets.
- closed¶
Read-only property,
Trueifclose()has been called orCLOSEmessage has been received from peer.
- protocol¶
Websocket subprotocol chosen after
start()call.May be
Noneif server and client protocols are not overlapping.
- get_extra_info(name, default=None)[source]¶
Reads optional extra information from the connection’s transport. If no value associated with
nameis found,defaultis returned.See
asyncio.BaseTransport.get_extra_info()- Parameters:
name (str) – The key to look up in the transport extra information.
default – Default value to be used when no value for
nameis found (default isNone).
- async ping(message=b'')[source]¶
Send
PINGto peer.- Parameters:
message – optional payload of ping message,
str(converted to UTF-8 encoded bytes) orbytes.
Changed in version 3.0: The method is converted into coroutine
- async pong(message=b'')[source]¶
Send
PONGto peer.- Parameters:
message – optional payload of pong message,
str(converted to UTF-8 encoded bytes) orbytes.
Changed in version 3.0: The method is converted into coroutine
- async send_str(data, compress=None)[source]¶
Send data to peer as
TEXTmessage.- Parameters:
- Raises:
Changed in version 3.0: The method is converted into coroutine, compress parameter added.
- async send_bytes(data, compress=None)[source]¶
Send data to peer as
BINARYmessage.- Parameters:
data – data to send.
compress (int) – sets specific level of compression for single message,
Nonefor not overriding per-socket setting.
- Raises:
TypeError – if data is not
bytes,bytearrayormemoryview.
Changed in version 3.0: The method is converted into coroutine, compress parameter added.
- async send_json(data, compress=None, *, dumps=json.dumps)[source]¶
Send data to peer as JSON string.
- Parameters:
data – data to send.
compress (int) – sets specific level of compression for single message,
Nonefor not overriding per-socket setting.dumps (collections.abc.Callable) – any callable that accepts an object and returns a JSON string (
json.dumps()by default).
- Raises:
RuntimeError – if connection is not started or closing
ValueError – if data is not serializable object
Changed in version 3.0: The method is converted into coroutine, compress parameter added.
- async send_frame(message, opcode, compress=None)[source]¶
Send a
WSMsgTypemessage message to peer.This method is low-level and should be used with caution as it only accepts bytes which must conform to the correct message type for message.
It is recommended to use the
send_str(),send_bytes()orsend_json()methods instead of this method.The primary use case for this method is to send bytes that are have already been encoded without having to decode and re-encode them.
- Parameters:
Added in version 3.11.
- async close(*, code=WSCloseCode.OK, message=b'')[source]¶
A coroutine that initiates closing handshake by sending
CLOSEmessage. It waits for close response from server. To add a timeout to close() call just wrap the call with asyncio.wait() or asyncio.wait_for().- Parameters:
code (int) – closing code. See also
WSCloseCode.message – optional payload of close message,
str(converted to UTF-8 encoded bytes) orbytes.
- async receive()[source]¶
A coroutine that waits upcoming data message from peer and returns it.
The coroutine implicitly handles
PING,PONGandCLOSEwithout returning the message.It process ping-pong game and performs closing handshake internally.
- Returns:
- async receive_str()[source]¶
A coroutine that calls
receive()but also asserts the message type isTEXT.- Return str:
peer’s message content.
- Raises:
aiohttp.WSMessageTypeError – if message is not
TEXT.
- async receive_bytes()[source]¶
A coroutine that calls
receive()but also asserts the message type isBINARY.- Return bytes:
peer’s message content.
- Raises:
aiohttp.WSMessageTypeError – if message is not
BINARY.
- async receive_json(*, loads=json.loads)[source]¶
A coroutine that calls
receive_str()and loads the JSON string to a Python dict.- Parameters:
loads (collections.abc.Callable) – any callable that accepts
strand returnsdictwith parsed JSON (json.loads()by default).- Return dict:
loaded JSON content
- Raises:
ValueError – if message is not valid JSON.
ClientRequest¶
- class aiohttp.ClientRequest[source]¶
Represents an HTTP request to be sent by the client.
This object encapsulates all the details of an HTTP request before it is sent. It is primarily used within client middleware to inspect or modify requests.
Note
You typically don’t create
ClientRequestinstances directly. They are created internally byClientSessionmethods and passed to middleware.For more information about using middleware, see Client Middleware.
- body: Payload | Literal[b'']¶
The request body payload (defaults to
b""if no body passed).Danger
DO NOT set this attribute directly! Direct assignment will cause resource leaks. Always use
update_body()instead:# WRONG - This will leak resources! request.body = b"new data" # CORRECT - Use update_body await request.update_body(b"new data")
Setting body directly bypasses cleanup of the previous payload, which can leave file handles open, streams unclosed, and buffers unreleased.
Additionally, setting body directly must be done from within an event loop and is not thread-safe. Setting body outside of an event loop may raise RuntimeError when closing file-based payloads.
- chunked: bool | None¶
Whether to use chunked transfer encoding:
True: Use chunked encodingFalse: Don’t use chunked encodingNone: Automatically determine based on body
- compress: str | None¶
The compression encoding for the request body. Common values include
'gzip'and'deflate', but any string value is technically allowed.Nonemeans no compression.
- headers: multidict.CIMultiDict¶
The HTTP headers that will be sent with the request. This is a case-insensitive multidict that can be modified by middleware.
# Add or modify headers request.headers['X-Custom-Header'] = 'value' request.headers['User-Agent'] = 'MyApp/1.0'
- original_url: yarl.URL¶
The original URL passed to the request method, including any fragment. This preserves the exact URL as provided by the user.
- proxy_headers: multidict.CIMultiDict | None¶
Headers to be sent to the proxy server (e.g.,
Proxy-Authorization). Only set whenproxyis notNone.
- response_class: type[ClientResponse]¶
The class to use for creating the response object. Defaults to
ClientResponsebut can be customized for special handling.
- server_hostname: str | None¶
Override the hostname for SSL certificate verification. Useful when connecting through proxies or to IP addresses.
- session: ClientSession¶
The client session that created this request. Useful for accessing session-level configuration or making additional requests within middleware.
Warning
Be careful when making requests with the same session inside middleware to avoid infinite recursion. Use
middlewares=()parameter when needed.
- ssl: ssl.SSLContext | bool | Fingerprint¶
SSL validation configuration for this request:
True: Use default SSL verificationFalse: Skip SSL verificationssl.SSLContext: Custom SSL contextFingerprint: Verify specific certificate fingerprint
- url: yarl.URL¶
The target URL of the request with the fragment (
#...) part stripped. This is the actual URL that will be used for the connection.Note
To access the original URL with fragment, use
original_url.
- version: HttpVersion¶
The HTTP version to use for the request (e.g.,
HttpVersion(1, 1)for HTTP/1.1).
- update_body(body)[source]¶
Update the request body and close any existing payload to prevent resource leaks.
This is the ONLY correct way to modify a request body. Never set the
bodyattribute directly.This method is particularly useful in middleware when you need to modify the request body after the request has been created but before it’s sent.
- Parameters:
body –
The new body content. Can be:
bytes/bytearray: Raw binary datastr: Text data (encoded using charset from Content-Type)FormData: Form data encoded as multipart/form-dataPayload: A pre-configured payload objectAsyncIterable[bytes]: Async iterable of bytes chunksFile-like object: Will be read and sent as binary data
None: Clears the body
async def middleware(request, handler): # Modify request body in middleware if request.method == 'POST': # CORRECT: Always use update_body await request.update_body(b'{"modified": true}') # WRONG: Never set body directly! # request.body = b'{"modified": true}' # This leaks resources! # Or add authentication data to form if isinstance(request.body, FormData): form = FormData() # Copy existing fields and add auth token form.add_field('auth_token', 'secret123') await request.update_body(form) return await handler(request)
Note
This method is async because it may need to close file handles or other resources associated with the previous payload. Always await this method to ensure proper cleanup.
Danger
Never set :attr:`ClientRequest.body` directly! Direct assignment will cause resource leaks. Always use this method instead. Setting the body attribute directly:
Bypasses cleanup of the previous payload
Leaves file handles and streams open
Can cause memory leaks
May result in unexpected behavior with async iterables
Warning
When updating the body, ensure that the Content-Type header is appropriate for the new body content. The Content-Length header will be updated automatically. When using
FormDataorPayloadobjects, headers are updated automatically, but you may need to set Content-Type manually for raw bytes or text.It is not recommended to change the payload type in middleware. If the body was already set (e.g., as bytes), it’s best to keep the same type rather than converting it (e.g., to str) as this may result in unexpected behavior.
Added in version 3.12.
Utilities¶
- class aiohttp.ClientTimeout(*, total=None, connect=None, sock_connect=None, sock_read=None)[source]¶
A data class for client timeout settings.
See Timeouts for usage examples.
- connect¶
Maximal number of seconds for acquiring a connection from pool. The time consists connection establishment for a new connection or waiting for a free connection from a pool if pool connection limits are exceeded.
For pure socket connection establishment time use
sock_connect.float,Noneby default.
- class aiohttp.ClientWSTimeout(*, ws_receive=None, ws_close=None)[source]¶
A data class for websocket client timeout settings.
Added in version 4.0.
Note
Timeouts of 5 seconds or more are rounded for scheduling on the next second boundary (an absolute time where microseconds part is zero) for the sake of performance.
E.g., assume a timeout is
10, absolute time when timeout should expire isloop.time() + 5, and it points to12345.67 + 10which is equal to12355.67.The absolute time for the timeout cancellation is
12356.It leads to grouping all close scheduled timeout expirations to exactly the same time to reduce amount of loop wakeups.
Changed in version 3.7: Rounding to the next seconds boundary is disabled for timeouts smaller than 5 seconds for the sake of easy debugging.
In turn, tiny timeouts can lead to significant performance degradation on production environment.
- class aiohttp.ETag(name, is_weak=False)[source]¶
Represents ETag identifier.
- value¶
Value of corresponding etag without quotes.
- is_weak¶
Flag indicates that etag is weak (has W/ prefix).
Added in version 3.8.
- class aiohttp.ContentDisposition¶
A data class to represent the Content-Disposition header, available as
ClientResponse.content_dispositionattribute.- type¶
A
strinstance. Value of Content-Disposition header itself, e.g.attachment.- filename¶
A
strinstance. Content filename extracted from parameters. May beNone.- parameters¶
Read-only mapping contains all parameters.
- class aiohttp.RequestInfo[source]¶
A
typing.NamedTuplewith request URL and headers fromClientRequestobject, available asClientResponse.request_infoattribute.- headers¶
HTTP headers for request,
multidict.CIMultiDictinstance.
- class aiohttp.BasicAuth(login, password='', encoding='latin1')[source]¶
HTTP basic authentication helper.
- Parameters:
Should be used for specifying authorization data in client API, e.g. auth parameter for
ClientSession.request().- classmethod decode(auth_header, encoding='latin1')[source]¶
Decode HTTP basic authentication credentials.
- class aiohttp.DigestAuthMiddleware(login, password, *, preemptive=True)[source]¶
HTTP digest authentication client middleware.
- Parameters:
This middleware supports HTTP digest authentication with both auth and auth-int quality of protection (qop) modes, and a variety of hashing algorithms.
It automatically handles the digest authentication handshake by:
Parsing 401 Unauthorized responses with WWW-Authenticate: Digest headers
Generating appropriate Authorization: Digest headers on retry
Maintaining nonce counts and challenge data per request
When
preemptive=True, reusing authentication credentials for subsequent requests to the same protection space (following RFC 7616 Section 3.6)
Preemptive Authentication
By default (
preemptive=True), the middleware remembers successful authentication challenges and automatically includes the Authorization header in subsequent requests to the same protection space. This behavior:Improves server efficiency by avoiding extra round trips
Matches how modern web browsers handle digest authentication
Follows the recommendation in RFC 7616 Section 3.6
The server may still respond with a 401 status and
stale=trueif the nonce has expired, in which case the middleware will automatically retry with the new nonce.To disable preemptive authentication and require a 401 challenge for every request, set
preemptive=False:# Default behavior - preemptive auth enabled digest_auth_middleware = DigestAuthMiddleware(login="user", password="pass") # Disable preemptive auth - always wait for 401 challenge digest_auth_middleware = DigestAuthMiddleware(login="user", password="pass", preemptive=False)
Usage:
digest_auth_middleware = DigestAuthMiddleware(login="user", password="pass") async with ClientSession(middlewares=(digest_auth_middleware,)) as session: async with session.get("http://protected.example.com") as resp: # The middleware automatically handles the digest auth handshake assert resp.status == 200 # Subsequent requests include auth header preemptively async with session.get("http://protected.example.com/other") as resp: assert resp.status == 200 # No 401 round trip needed
Added in version 3.12.
Changed in version 3.12.8: Added
preemptiveparameter to enable/disable preemptive authentication.
- class aiohttp.CookieJar(*, unsafe=False, quote_cookie=True, treat_as_secure_origin=[])[source]¶
The cookie jar instance is available as
ClientSession.cookie_jar.The jar contains
Morselitems for storing internal cookie data.API provides a count of saved cookies:
len(session.cookie_jar)
These cookies may be iterated over:
for cookie in session.cookie_jar: print(cookie.key) print(cookie["domain"])
The class implements
collections.abc.Iterable,collections.abc.Sizedandaiohttp.abc.AbstractCookieJarinterfaces.Implements cookie storage adhering to RFC 6265.
- Parameters:
unsafe (bool) – (optional) Whether to accept cookies from IPs.
quote_cookie (bool) –
- (optional) Whether to quote cookies according to
RFC 2109. Some backend systems (not compatible with RFC mentioned above) does not support quoted cookies.
Added in version 3.7.
treat_as_secure_origin –
- (optional) Mark origins as secure
for cookies marked as Secured. Possible types are
Possible types are:
Added in version 3.8.
- update_cookies(cookies, response_url=None)[source]¶
Update cookies returned by server in
Set-Cookieheader.- Parameters:
cookies – a
collections.abc.Mapping(e.g.dict,SimpleCookie) or iterable of pairs with cookies returned by server’s response.response_url (URL) – URL of response,
Nonefor shared cookies. Regular cookies are coupled with server’s URL and are sent only to this server, shared ones are sent in every client request.
- filter_cookies(request_url)[source]¶
Return jar’s cookies acceptable for URL and available in
Cookieheader for sending client requests for given URL.- Parameters:
response_url (URL) – request’s URL for which cookies are asked.
- Returns:
http.cookies.SimpleCookiewith filtered cookies for given URL.
- save(file_path)[source]¶
Write a pickled representation of cookies into the file at provided path.
- Parameters:
file_path – Path to file where cookies will be serialized,
strorpathlib.Pathinstance.
- load(file_path)[source]¶
Load a pickled representation of cookies from the file at provided path.
- Parameters:
file_path – Path to file from where cookies will be imported,
strorpathlib.Pathinstance.
- class aiohttp.DummyCookieJar(*, loop=None)[source]¶
Dummy cookie jar which does not store cookies but ignores them.
Could be useful e.g. for web crawlers to iterate over Internet without blowing up with saved cookies information.
To install dummy cookie jar pass it into session instance:
jar = aiohttp.DummyCookieJar() session = aiohttp.ClientSession(cookie_jar=DummyCookieJar())
- class aiohttp.Fingerprint(digest)[source]¶
Fingerprint helper for checking SSL certificates by SHA256 digest.
- Parameters:
digest (bytes) – SHA256 digest for certificate in DER-encoded binary form (see
ssl.SSLSocket.getpeercert()).
To check fingerprint pass the object into
ClientSession.get()call, e.g.:import hashlib with open(path_to_cert, 'rb') as f: digest = hashlib.sha256(f.read()).digest() await session.get(url, ssl=aiohttp.Fingerprint(digest))
Added in version 3.0.
- aiohttp.set_zlib_backend(lib)[source]¶
Sets the compression backend for zlib-based operations.
This function allows you to override the default zlib backend used internally by passing a module that implements the standard compression interface.
The module should implement at minimum the exact interface offered by the latest version of zlib.
- Parameters:
lib (types.ModuleType) – A module that implements the zlib-compatible compression API.
Example usage:
import zlib_ng.zlib_ng as zng import aiohttp aiohttp.set_zlib_backend(zng)
Note
aiohttp has been tested internally with
zlib,zlib_ng.zlib_ng, andisal.isal_zlib.Added in version 3.12.
FormData¶
A FormData object contains the form data and also handles
encoding it into a body that is either multipart/form-data or
application/x-www-form-urlencoded. multipart/form-data is
used if at least one field is an io.IOBase object or was
added with at least one optional argument to add_field
(content_type, filename, or content_transfer_encoding).
Otherwise, application/x-www-form-urlencoded is used.
FormData instances are callable and return a aiohttp.payload.Payload
on being called.
- class aiohttp.FormData(fields, quote_fields=True, charset=None)[source]¶
Helper class for multipart/form-data and application/x-www-form-urlencoded body generation.
- Parameters:
fields –
A container for the key/value pairs of this form.
Possible types are:
io.IOBase, e.g. a file-like object
If it is a
tupleorlist, it must be a valid argument foradd_fields.For
dict,multidict.MultiDict, andmultidict.MultiDictProxy, the keys and values must be valid name and value arguments toadd_field, respectively.
- add_field(name, value, content_type=None, filename=None, content_transfer_encoding=None)[source]¶
Add a field to the form.
- Parameters:
name (str) – Name of the field
value –
Value of the field
Possible types are:
bytes,bytearray, ormemoryviewio.IOBase, e.g. a file-like object
content_type (str) – The field’s content-type header (optional)
filename (str) –
The field’s filename (optional)
If this is not set and
valueis abytes,bytearray, ormemoryviewobject, the name argument is used as the filename unlesscontent_transfer_encodingis specified.If
filenameis not set andvalueis anio.IOBaseobject, the filename is extracted from the object if possible.content_transfer_encoding (str) – The field’s content-transfer-encoding header (optional)
Client exceptions¶
Exception hierarchy has been significantly modified in version
2.0. aiohttp defines only exceptions that covers connection handling
and server response misbehaviors. For developer specific mistakes,
aiohttp uses python standard exceptions like ValueError or
TypeError.
Reading a response content may raise a ClientPayloadError
exception. This exception indicates errors specific to the payload
encoding. Such as invalid compressed data, malformed chunked-encoded
chunks or not enough data that satisfy the content-length header.
All exceptions are available as members of aiohttp module.
- exception aiohttp.ClientError[source]¶
Base class for all client specific exceptions.
Derived from
Exception
- class aiohttp.ClientPayloadError[source]¶
This exception can only be raised while reading the response payload if one of these errors occurs:
invalid compression
malformed chunked encoding
not enough data that satisfy
Content-LengthHTTP header.
Derived from
ClientError
- exception aiohttp.InvalidURL[source]¶
URL used for fetching is malformed, e.g. it does not contain host part.
Derived from
ClientErrorandValueError
- exception aiohttp.InvalidUrlClientError[source]¶
Base class for all errors related to client url.
Derived from
InvalidURL
- exception aiohttp.RedirectClientError[source]¶
Base class for all errors related to client redirects.
Derived from
ClientError
- exception aiohttp.NonHttpUrlClientError[source]¶
Base class for all errors related to non http client urls.
Derived from
ClientError
- exception aiohttp.InvalidUrlRedirectClientError[source]¶
Redirect URL is malformed, e.g. it does not contain host part.
Derived from
InvalidUrlClientErrorandRedirectClientError
- exception aiohttp.NonHttpUrlRedirectClientError[source]¶
Redirect URL does not contain http schema.
Derived from
RedirectClientErrorandNonHttpUrlClientError
Response errors¶
- exception aiohttp.ClientResponseError[source]¶
These exceptions could happen after we get response from server.
Derived from
ClientError- request_info¶
Instance of
RequestInfoobject, contains information about request.
- headers¶
Headers in response, a list of pairs.
- history¶
History from failed response, if available, else empty tuple.
A
tupleofClientResponseobjects used for handle redirection responses.
- class aiohttp.ContentTypeError[source]¶
Invalid content type.
Derived from
ClientResponseErrorAdded in version 2.3.
- class aiohttp.TooManyRedirects[source]¶
Client was redirected too many times.
Maximum number of redirects can be configured by using parameter
max_redirectsinrequest.Derived from
ClientResponseErrorAdded in version 3.2.
- class aiohttp.WSServerHandshakeError[source]¶
Web socket server response error.
Derived from
ClientResponseError
Connection errors¶
- class aiohttp.ClientConnectionError[source]¶
These exceptions related to low-level connection problems.
Derived from
ClientError
- class aiohttp.ClientConnectionResetError[source]¶
Derived from
ClientConnectionErrorandConnectionResetError
- class aiohttp.ClientOSError[source]¶
Subset of connection errors that are initiated by an
OSErrorexception.Derived from
ClientConnectionErrorandOSError
- class aiohttp.ClientConnectorError[source]¶
Connector related exceptions.
Derived from
ClientOSError
- class aiohttp.ClientConnectorDNSError[source]¶
DNS resolution error.
Derived from
ClientConnectorError
- class aiohttp.ClientProxyConnectionError[source]¶
Derived from
ClientConnectorError
- class aiohttp.ClientSSLError[source]¶
Derived from
ClientConnectorError
- class aiohttp.ClientConnectorSSLError[source]¶
Response ssl error.
Derived from
ClientSSLErrorandssl.SSLError
- class aiohttp.ClientConnectorCertificateError[source]¶
Response certificate error.
Derived from
ClientSSLErrorandssl.CertificateError
- class aiohttp.UnixClientConnectorError¶
Derived from
ClientConnectorError
- class aiohttp.ServerConnectionError[source]¶
Derived from
ClientConnectionError
- class aiohttp.ServerDisconnectedError[source]¶
Server disconnected.
Derived from
ServerConnectionError- message¶
Partially parsed HTTP message (optional).
- class aiohttp.ServerFingerprintMismatch[source]¶
Server fingerprint mismatch.
Derived from
ServerConnectionError
- class aiohttp.ServerTimeoutError[source]¶
Server operation timeout: read timeout, etc.
To catch all timeouts, including the
totaltimeout, useasyncio.TimeoutError.Derived from
ServerConnectionErrorandasyncio.TimeoutError
- class aiohttp.ConnectionTimeoutError[source]¶
Connection timeout on
connectandsock_connecttimeouts.Derived from
ServerTimeoutError
- class aiohttp.SocketTimeoutError[source]¶
Reading from socket timeout on
sock_readtimeout.Derived from
ServerTimeoutError
Hierarchy of exceptions¶
-
-
-
ClientHttpProxyError
-
Client Types¶
- type aiohttp.ClientMiddlewareType¶
Type alias for client middleware functions. Middleware functions must have this signature:
Callable[ [ClientRequest, ClientHandlerType], Awaitable[ClientResponse] ]
- type aiohttp.ClientHandlerType¶
Type alias for client request handler functions:
Callable[[ClientRequest], Awaitable[ClientResponse]]