Skip to content

httpx #

Classes:

Name Description
ASGITransport

A custom AsyncTransport that handles sending requests directly to an ASGI app.

AsyncClient

An asynchronous HTTP client, with connection pooling, HTTP/2, redirects,

Auth

Base class for all authentication schemes.

BaseTransport
BasicAuth

Allows the 'auth' argument to be passed as a (username, password) pair,

Client

An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.

CloseError

Failed to close a connection.

ConnectError

Failed to establish a connection.

ConnectTimeout

Timed out while connecting to the host.

CookieConflict

Attempted to lookup a cookie by name, but multiple cookies existed.

Cookies

HTTP Cookies, as a mutable mapping.

DecodingError

Decoding of the response failed, due to a malformed encoding.

DigestAuth
HTTPError

Base class for RequestError and HTTPStatusError.

HTTPStatusError

The response had an error HTTP status of 4xx or 5xx.

Headers

HTTP headers, as a case-insensitive multi-dict.

InvalidURL

URL is improperly formed or cannot be parsed.

Limits

Configuration for limits to various client behaviors.

LocalProtocolError

A protocol was violated by the client.

NetRCAuth

Use a 'netrc' file to lookup basic auth credentials based on the url host.

NetworkError

The base class for network-related errors.

PoolTimeout

Timed out waiting to acquire a connection from the pool.

ProtocolError

The protocol was violated.

ProxyError

An error occurred while establishing a proxy connection.

QueryParams

URL query parameters, as a multi-dict.

ReadError

Failed to receive data from the network.

ReadTimeout

Timed out while receiving data from the host.

RemoteProtocolError

The protocol was violated by the server.

Request
RequestError

Base class for all exceptions that may occur when issuing a .request().

RequestNotRead

Attempted to access streaming request content, without having called read().

Response
ResponseNotRead

Attempted to access streaming response content, without having called read().

StreamClosed

Attempted to read or stream response content, but the request has been

StreamConsumed

Attempted to read or stream content, but the content has already

StreamError

The base class for stream exceptions.

SyncByteStream
Timeout

Timeout configuration.

TimeoutException

The base class for timeout errors.

TooManyRedirects

Too many redirects.

TransportError

Base class for all exceptions that occur at the level of the Transport API.

URL
UnsupportedProtocol

Attempted to make a request to an unsupported protocol.

WSGITransport

A custom transport that handles sending requests directly to an WSGI app.

WriteError

Failed to send data through the network.

WriteTimeout

Timed out while sending data to the host.

codes

HTTP status codes and reason phrases

Functions:

Name Description
delete

Sends a DELETE request.

get

Sends a GET request.

head

Sends a HEAD request.

options

Sends an OPTIONS request.

patch

Sends a PATCH request.

post

Sends a POST request.

put

Sends a PUT request.

request

Sends an HTTP request.

stream

Alternative to httpx.request() that streams the response body

ASGITransport #

ASGITransport(app: _ASGIApp, raise_app_exceptions: bool = True, root_path: str = '', client: tuple[str, int] = ('127.0.0.1', 123))

A custom AsyncTransport that handles sending requests directly to an ASGI app.

transport = httpx.ASGITransport(
    app=app,
    root_path="/submount",
    client=("1.2.3.4", 123)
)
client = httpx.AsyncClient(transport=transport)

Arguments:

  • app - The ASGI application.
  • raise_app_exceptions - Boolean indicating if exceptions in the application should be raised. Default to True. Can be set to False for use cases such as testing the content of a client 500 response.
  • root_path - The root path on which the ASGI application should be mounted.
  • client - A two-tuple indicating the client IP and port of incoming requests. ```
Source code in .venv/lib/python3.13/site-packages/httpx/_transports/asgi.py
87
88
89
90
91
92
93
94
95
96
97
def __init__(
    self,
    app: _ASGIApp,
    raise_app_exceptions: bool = True,
    root_path: str = "",
    client: tuple[str, int] = ("127.0.0.1", 123),
) -> None:
    self.app = app
    self.raise_app_exceptions = raise_app_exceptions
    self.root_path = root_path
    self.client = client

AsyncClient #

AsyncClient(*, auth: AuthTypes | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, verify: SSLContext | str | bool = True, cert: CertTypes | None = None, http1: bool = True, http2: bool = False, proxy: ProxyTypes | None = None, mounts: None | Mapping[str, AsyncBaseTransport | None] = None, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, follow_redirects: bool = False, limits: Limits = DEFAULT_LIMITS, max_redirects: int = DEFAULT_MAX_REDIRECTS, event_hooks: None | Mapping[str, list[EventHook]] = None, base_url: URL | str = '', transport: AsyncBaseTransport | None = None, trust_env: bool = True, default_encoding: str | Callable[[bytes], str] = 'utf-8')

An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.

It can be shared between tasks.

Usage:

>>> async with httpx.AsyncClient() as client:
>>>     response = await client.get('https://example.org')

Parameters:

  • auth - (optional) An authentication class to use when sending requests.
  • params - (optional) Query parameters to include in request URLs, as a string, dictionary, or sequence of two-tuples.
  • headers - (optional) Dictionary of HTTP headers to include when sending requests.
  • cookies - (optional) Dictionary of Cookie items to include when sending requests.
  • verify - (optional) Either True to use an SSL context with the default CA bundle, False to disable verification, or an instance of ssl.SSLContext to use a custom context.
  • http2 - (optional) A boolean indicating if HTTP/2 support should be enabled. Defaults to False.
  • proxy - (optional) A proxy URL where all the traffic should be routed.
  • timeout - (optional) The timeout configuration to use when sending requests.
  • limits - (optional) The limits configuration to use.
  • max_redirects - (optional) The maximum number of redirect responses that should be followed.
  • base_url - (optional) A URL to use as the base when building request URLs.
  • transport - (optional) A transport class to use for sending requests over the network.
  • trust_env - (optional) Enables or disables usage of environment variables for configuration.
  • default_encoding - (optional) The default encoding to use for decoding response text, if no charset information is included in a response Content-Type header. Set to a callable for automatic character set detection. Default: "utf-8".

Methods:

Name Description
aclose

Close transport and proxies.

build_request

Build and return a request instance.

delete

Send a DELETE request.

get

Send a GET request.

head

Send a HEAD request.

options

Send an OPTIONS request.

patch

Send a PATCH request.

post

Send a POST request.

put

Send a PUT request.

request

Build and send a request.

send

Send a request.

stream

Alternative to httpx.request() that streams the response body

Attributes:

Name Type Description
auth Auth | None

Authentication class used when none is passed at the request-level.

base_url URL

Base URL to use when sending requests with relative URLs.

cookies Cookies

Cookie values to include when sending requests.

headers Headers

HTTP headers to include when sending requests.

is_closed bool

Check if the client being closed

params QueryParams

Query parameters to include in the URL when sending requests.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
def __init__(
    self,
    *,
    auth: AuthTypes | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    verify: ssl.SSLContext | str | bool = True,
    cert: CertTypes | None = None,
    http1: bool = True,
    http2: bool = False,
    proxy: ProxyTypes | None = None,
    mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    follow_redirects: bool = False,
    limits: Limits = DEFAULT_LIMITS,
    max_redirects: int = DEFAULT_MAX_REDIRECTS,
    event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
    base_url: URL | str = "",
    transport: AsyncBaseTransport | None = None,
    trust_env: bool = True,
    default_encoding: str | typing.Callable[[bytes], str] = "utf-8",
) -> None:
    super().__init__(
        auth=auth,
        params=params,
        headers=headers,
        cookies=cookies,
        timeout=timeout,
        follow_redirects=follow_redirects,
        max_redirects=max_redirects,
        event_hooks=event_hooks,
        base_url=base_url,
        trust_env=trust_env,
        default_encoding=default_encoding,
    )

    if http2:
        try:
            import h2  # noqa
        except ImportError:  # pragma: no cover
            raise ImportError(
                "Using http2=True, but the 'h2' package is not installed. "
                "Make sure to install httpx using `pip install httpx[http2]`."
            ) from None

    allow_env_proxies = trust_env and transport is None
    proxy_map = self._get_proxy_map(proxy, allow_env_proxies)

    self._transport = self._init_transport(
        verify=verify,
        cert=cert,
        trust_env=trust_env,
        http1=http1,
        http2=http2,
        limits=limits,
        transport=transport,
    )

    self._mounts: dict[URLPattern, AsyncBaseTransport | None] = {
        URLPattern(key): None
        if proxy is None
        else self._init_proxy_transport(
            proxy,
            verify=verify,
            cert=cert,
            trust_env=trust_env,
            http1=http1,
            http2=http2,
            limits=limits,
        )
        for key, proxy in proxy_map.items()
    }
    if mounts is not None:
        self._mounts.update(
            {URLPattern(key): transport for key, transport in mounts.items()}
        )
    self._mounts = dict(sorted(self._mounts.items()))

auth property writable #

auth: Auth | None

Authentication class used when none is passed at the request-level.

See also Authentication.

base_url property writable #

base_url: URL

Base URL to use when sending requests with relative URLs.

cookies property writable #

cookies: Cookies

Cookie values to include when sending requests.

headers property writable #

headers: Headers

HTTP headers to include when sending requests.

is_closed property #

is_closed: bool

Check if the client being closed

params property writable #

params: QueryParams

Query parameters to include in the URL when sending requests.

aclose async #

aclose() -> None

Close transport and proxies.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
async def aclose(self) -> None:
    """
    Close transport and proxies.
    """
    if self._state != ClientState.CLOSED:
        self._state = ClientState.CLOSED

        await self._transport.aclose()
        for proxy in self._mounts.values():
            if proxy is not None:
                await proxy.aclose()

build_request #

build_request(method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Request

Build and return a request instance.

  • The params, headers and cookies arguments are merged with any values set on the client.
  • The url argument is merged with any base_url set on the client.

See also: Request instances

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
def build_request(
    self,
    method: str,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Request:
    """
    Build and return a request instance.

    * The `params`, `headers` and `cookies` arguments
    are merged with any values set on the client.
    * The `url` argument is merged with any `base_url` set on the client.

    See also: [Request instances][0]

    [0]: /advanced/clients/#request-instances
    """
    url = self._merge_url(url)
    headers = self._merge_headers(headers)
    cookies = self._merge_cookies(cookies)
    params = self._merge_queryparams(params)
    extensions = {} if extensions is None else extensions
    if "timeout" not in extensions:
        timeout = (
            self.timeout
            if isinstance(timeout, UseClientDefault)
            else Timeout(timeout)
        )
        extensions = dict(**extensions, timeout=timeout.as_dict())
    return Request(
        method,
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        extensions=extensions,
    )

delete async #

delete(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a DELETE request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
async def delete(
    self,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `DELETE` request.

    **Parameters**: See `httpx.request`.
    """
    return await self.request(
        "DELETE",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

get async #

get(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a GET request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
async def get(
    self,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `GET` request.

    **Parameters**: See `httpx.request`.
    """
    return await self.request(
        "GET",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

head async #

head(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a HEAD request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
async def head(
    self,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `HEAD` request.

    **Parameters**: See `httpx.request`.
    """
    return await self.request(
        "HEAD",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

options async #

options(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send an OPTIONS request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
async def options(
    self,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send an `OPTIONS` request.

    **Parameters**: See `httpx.request`.
    """
    return await self.request(
        "OPTIONS",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

patch async #

patch(url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a PATCH request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
async def patch(
    self,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `PATCH` request.

    **Parameters**: See `httpx.request`.
    """
    return await self.request(
        "PATCH",
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

post async #

post(url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a POST request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
async def post(
    self,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `POST` request.

    **Parameters**: See `httpx.request`.
    """
    return await self.request(
        "POST",
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

put async #

put(url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a PUT request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
async def put(
    self,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `PUT` request.

    **Parameters**: See `httpx.request`.
    """
    return await self.request(
        "PUT",
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

request async #

request(method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Build and send a request.

Equivalent to:

request = client.build_request(...)
response = await client.send(request, ...)

See AsyncClient.build_request(), AsyncClient.send() and Merging of configuration for how the various parameters are merged with client-level configuration.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
async def request(
    self,
    method: str,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Build and send a request.

    Equivalent to:

    ```python
    request = client.build_request(...)
    response = await client.send(request, ...)
    ```

    See `AsyncClient.build_request()`, `AsyncClient.send()`
    and [Merging of configuration][0] for how the various parameters
    are merged with client-level configuration.

    [0]: /advanced/clients/#merging-of-configuration
    """

    if cookies is not None:  # pragma: no cover
        message = (
            "Setting per-request cookies=<...> is being deprecated, because "
            "the expected behaviour on cookie persistence is ambiguous. Set "
            "cookies directly on the client instance instead."
        )
        warnings.warn(message, DeprecationWarning, stacklevel=2)

    request = self.build_request(
        method=method,
        url=url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        timeout=timeout,
        extensions=extensions,
    )
    return await self.send(request, auth=auth, follow_redirects=follow_redirects)

send async #

send(request: Request, *, stream: bool = False, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT) -> Response

Send a request.

The request is sent as-is, unmodified.

Typically you'll want to build one with AsyncClient.build_request() so that any client-level configuration is merged into the request, but passing an explicit httpx.Request() is supported as well.

See also: Request instances

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
async def send(
    self,
    request: Request,
    *,
    stream: bool = False,
    auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
) -> Response:
    """
    Send a request.

    The request is sent as-is, unmodified.

    Typically you'll want to build one with `AsyncClient.build_request()`
    so that any client-level configuration is merged into the request,
    but passing an explicit `httpx.Request()` is supported as well.

    See also: [Request instances][0]

    [0]: /advanced/clients/#request-instances
    """
    if self._state == ClientState.CLOSED:
        raise RuntimeError("Cannot send a request, as the client has been closed.")

    self._state = ClientState.OPENED
    follow_redirects = (
        self.follow_redirects
        if isinstance(follow_redirects, UseClientDefault)
        else follow_redirects
    )

    self._set_timeout(request)

    auth = self._build_request_auth(request, auth)

    response = await self._send_handling_auth(
        request,
        auth=auth,
        follow_redirects=follow_redirects,
        history=[],
    )
    try:
        if not stream:
            await response.aread()

        return response

    except BaseException as exc:
        await response.aclose()
        raise exc

stream async #

stream(method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> AsyncIterator[Response]

Alternative to httpx.request() that streams the response body instead of loading it into memory at once.

Parameters: See httpx.request.

See also: Streaming Responses

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
@asynccontextmanager
async def stream(
    self,
    method: str,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> typing.AsyncIterator[Response]:
    """
    Alternative to `httpx.request()` that streams the response body
    instead of loading it into memory at once.

    **Parameters**: See `httpx.request`.

    See also: [Streaming Responses][0]

    [0]: /quickstart#streaming-responses
    """
    request = self.build_request(
        method=method,
        url=url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        timeout=timeout,
        extensions=extensions,
    )
    response = await self.send(
        request=request,
        auth=auth,
        follow_redirects=follow_redirects,
        stream=True,
    )
    try:
        yield response
    finally:
        await response.aclose()

Auth #

Base class for all authentication schemes.

To implement a custom authentication scheme, subclass Auth and override the .auth_flow() method.

If the authentication scheme does I/O such as disk access or network calls, or uses synchronization primitives such as locks, you should override .sync_auth_flow() and/or .async_auth_flow() instead of .auth_flow() to provide specialized implementations that will be used by Client and AsyncClient respectively.

Methods:

Name Description
async_auth_flow

Execute the authentication flow asynchronously.

auth_flow

Execute the authentication flow.

sync_auth_flow

Execute the authentication flow synchronously.

async_auth_flow async #

async_auth_flow(request: Request) -> AsyncGenerator[Request, Response]

Execute the authentication flow asynchronously.

By default, this defers to .auth_flow(). You should override this method when the authentication scheme does I/O and/or uses concurrency primitives.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
async def async_auth_flow(
    self, request: Request
) -> typing.AsyncGenerator[Request, Response]:
    """
    Execute the authentication flow asynchronously.

    By default, this defers to `.auth_flow()`. You should override this method
    when the authentication scheme does I/O and/or uses concurrency primitives.
    """
    if self.requires_request_body:
        await request.aread()

    flow = self.auth_flow(request)
    request = next(flow)

    while True:
        response = yield request
        if self.requires_response_body:
            await response.aread()

        try:
            request = flow.send(response)
        except StopIteration:
            break

auth_flow #

auth_flow(request: Request) -> Generator[Request, Response, None]

Execute the authentication flow.

To dispatch a request, yield it:

yield request

The client will .send() the response back into the flow generator. You can access it like so:

response = yield request

A return (or reaching the end of the generator) will result in the client returning the last response obtained from the server.

You can dispatch as many requests as is necessary.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
    """
    Execute the authentication flow.

    To dispatch a request, `yield` it:

    ```
    yield request
    ```

    The client will `.send()` the response back into the flow generator. You can
    access it like so:

    ```
    response = yield request
    ```

    A `return` (or reaching the end of the generator) will result in the
    client returning the last response obtained from the server.

    You can dispatch as many requests as is necessary.
    """
    yield request

sync_auth_flow #

sync_auth_flow(request: Request) -> Generator[Request, Response, None]

Execute the authentication flow synchronously.

By default, this defers to .auth_flow(). You should override this method when the authentication scheme does I/O and/or uses concurrency primitives.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def sync_auth_flow(
    self, request: Request
) -> typing.Generator[Request, Response, None]:
    """
    Execute the authentication flow synchronously.

    By default, this defers to `.auth_flow()`. You should override this method
    when the authentication scheme does I/O and/or uses concurrency primitives.
    """
    if self.requires_request_body:
        request.read()

    flow = self.auth_flow(request)
    request = next(flow)

    while True:
        response = yield request
        if self.requires_response_body:
            response.read()

        try:
            request = flow.send(response)
        except StopIteration:
            break

BaseTransport #

Methods:

Name Description
handle_request

Send a single HTTP request and return a response.

handle_request #

handle_request(request: Request) -> Response

Send a single HTTP request and return a response.

Developers shouldn't typically ever need to call into this API directly, since the Client class provides all the higher level user-facing API niceties.

In order to properly release any network resources, the response stream should either be consumed immediately, with a call to response.stream.read(), or else the handle_request call should be followed with a try/finally block to ensuring the stream is always closed.

Example usage:

with httpx.HTTPTransport() as transport:
    req = httpx.Request(
        method=b"GET",
        url=(b"https", b"www.example.com", 443, b"/"),
        headers=[(b"Host", b"www.example.com")],
    )
    resp = transport.handle_request(req)
    body = resp.stream.read()
    print(resp.status_code, resp.headers, body)

Takes a Request instance as the only argument.

Returns a Response instance.

Source code in .venv/lib/python3.13/site-packages/httpx/_transports/base.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def handle_request(self, request: Request) -> Response:
    """
    Send a single HTTP request and return a response.

    Developers shouldn't typically ever need to call into this API directly,
    since the Client class provides all the higher level user-facing API
    niceties.

    In order to properly release any network resources, the response
    stream should *either* be consumed immediately, with a call to
    `response.stream.read()`, or else the `handle_request` call should
    be followed with a try/finally block to ensuring the stream is
    always closed.

    Example usage:

        with httpx.HTTPTransport() as transport:
            req = httpx.Request(
                method=b"GET",
                url=(b"https", b"www.example.com", 443, b"/"),
                headers=[(b"Host", b"www.example.com")],
            )
            resp = transport.handle_request(req)
            body = resp.stream.read()
            print(resp.status_code, resp.headers, body)


    Takes a `Request` instance as the only argument.

    Returns a `Response` instance.
    """
    raise NotImplementedError(
        "The 'handle_request' method must be implemented."
    )  # pragma: no cover

BasicAuth #

BasicAuth(username: str | bytes, password: str | bytes)

Allows the 'auth' argument to be passed as a (username, password) pair, and uses HTTP Basic authentication.

Methods:

Name Description
async_auth_flow

Execute the authentication flow asynchronously.

sync_auth_flow

Execute the authentication flow synchronously.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
132
133
def __init__(self, username: str | bytes, password: str | bytes) -> None:
    self._auth_header = self._build_auth_header(username, password)

async_auth_flow async #

async_auth_flow(request: Request) -> AsyncGenerator[Request, Response]

Execute the authentication flow asynchronously.

By default, this defers to .auth_flow(). You should override this method when the authentication scheme does I/O and/or uses concurrency primitives.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
async def async_auth_flow(
    self, request: Request
) -> typing.AsyncGenerator[Request, Response]:
    """
    Execute the authentication flow asynchronously.

    By default, this defers to `.auth_flow()`. You should override this method
    when the authentication scheme does I/O and/or uses concurrency primitives.
    """
    if self.requires_request_body:
        await request.aread()

    flow = self.auth_flow(request)
    request = next(flow)

    while True:
        response = yield request
        if self.requires_response_body:
            await response.aread()

        try:
            request = flow.send(response)
        except StopIteration:
            break

sync_auth_flow #

sync_auth_flow(request: Request) -> Generator[Request, Response, None]

Execute the authentication flow synchronously.

By default, this defers to .auth_flow(). You should override this method when the authentication scheme does I/O and/or uses concurrency primitives.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def sync_auth_flow(
    self, request: Request
) -> typing.Generator[Request, Response, None]:
    """
    Execute the authentication flow synchronously.

    By default, this defers to `.auth_flow()`. You should override this method
    when the authentication scheme does I/O and/or uses concurrency primitives.
    """
    if self.requires_request_body:
        request.read()

    flow = self.auth_flow(request)
    request = next(flow)

    while True:
        response = yield request
        if self.requires_response_body:
            response.read()

        try:
            request = flow.send(response)
        except StopIteration:
            break

Client #

Client(*, auth: AuthTypes | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, verify: SSLContext | str | bool = True, cert: CertTypes | None = None, trust_env: bool = True, http1: bool = True, http2: bool = False, proxy: ProxyTypes | None = None, mounts: None | Mapping[str, BaseTransport | None] = None, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, follow_redirects: bool = False, limits: Limits = DEFAULT_LIMITS, max_redirects: int = DEFAULT_MAX_REDIRECTS, event_hooks: None | Mapping[str, list[EventHook]] = None, base_url: URL | str = '', transport: BaseTransport | None = None, default_encoding: str | Callable[[bytes], str] = 'utf-8')

An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.

It can be shared between threads.

Usage:

>>> client = httpx.Client()
>>> response = client.get('https://example.org')

Parameters:

  • auth - (optional) An authentication class to use when sending requests.
  • params - (optional) Query parameters to include in request URLs, as a string, dictionary, or sequence of two-tuples.
  • headers - (optional) Dictionary of HTTP headers to include when sending requests.
  • cookies - (optional) Dictionary of Cookie items to include when sending requests.
  • verify - (optional) Either True to use an SSL context with the default CA bundle, False to disable verification, or an instance of ssl.SSLContext to use a custom context.
  • http2 - (optional) A boolean indicating if HTTP/2 support should be enabled. Defaults to False.
  • proxy - (optional) A proxy URL where all the traffic should be routed.
  • timeout - (optional) The timeout configuration to use when sending requests.
  • limits - (optional) The limits configuration to use.
  • max_redirects - (optional) The maximum number of redirect responses that should be followed.
  • base_url - (optional) A URL to use as the base when building request URLs.
  • transport - (optional) A transport class to use for sending requests over the network.
  • trust_env - (optional) Enables or disables usage of environment variables for configuration.
  • default_encoding - (optional) The default encoding to use for decoding response text, if no charset information is included in a response Content-Type header. Set to a callable for automatic character set detection. Default: "utf-8".

Methods:

Name Description
build_request

Build and return a request instance.

close

Close transport and proxies.

delete

Send a DELETE request.

get

Send a GET request.

head

Send a HEAD request.

options

Send an OPTIONS request.

patch

Send a PATCH request.

post

Send a POST request.

put

Send a PUT request.

request

Build and send a request.

send

Send a request.

stream

Alternative to httpx.request() that streams the response body

Attributes:

Name Type Description
auth Auth | None

Authentication class used when none is passed at the request-level.

base_url URL

Base URL to use when sending requests with relative URLs.

cookies Cookies

Cookie values to include when sending requests.

headers Headers

HTTP headers to include when sending requests.

is_closed bool

Check if the client being closed

params QueryParams

Query parameters to include in the URL when sending requests.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
def __init__(
    self,
    *,
    auth: AuthTypes | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    verify: ssl.SSLContext | str | bool = True,
    cert: CertTypes | None = None,
    trust_env: bool = True,
    http1: bool = True,
    http2: bool = False,
    proxy: ProxyTypes | None = None,
    mounts: None | (typing.Mapping[str, BaseTransport | None]) = None,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    follow_redirects: bool = False,
    limits: Limits = DEFAULT_LIMITS,
    max_redirects: int = DEFAULT_MAX_REDIRECTS,
    event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None,
    base_url: URL | str = "",
    transport: BaseTransport | None = None,
    default_encoding: str | typing.Callable[[bytes], str] = "utf-8",
) -> None:
    super().__init__(
        auth=auth,
        params=params,
        headers=headers,
        cookies=cookies,
        timeout=timeout,
        follow_redirects=follow_redirects,
        max_redirects=max_redirects,
        event_hooks=event_hooks,
        base_url=base_url,
        trust_env=trust_env,
        default_encoding=default_encoding,
    )

    if http2:
        try:
            import h2  # noqa
        except ImportError:  # pragma: no cover
            raise ImportError(
                "Using http2=True, but the 'h2' package is not installed. "
                "Make sure to install httpx using `pip install httpx[http2]`."
            ) from None

    allow_env_proxies = trust_env and transport is None
    proxy_map = self._get_proxy_map(proxy, allow_env_proxies)

    self._transport = self._init_transport(
        verify=verify,
        cert=cert,
        trust_env=trust_env,
        http1=http1,
        http2=http2,
        limits=limits,
        transport=transport,
    )
    self._mounts: dict[URLPattern, BaseTransport | None] = {
        URLPattern(key): None
        if proxy is None
        else self._init_proxy_transport(
            proxy,
            verify=verify,
            cert=cert,
            trust_env=trust_env,
            http1=http1,
            http2=http2,
            limits=limits,
        )
        for key, proxy in proxy_map.items()
    }
    if mounts is not None:
        self._mounts.update(
            {URLPattern(key): transport for key, transport in mounts.items()}
        )

    self._mounts = dict(sorted(self._mounts.items()))

auth property writable #

auth: Auth | None

Authentication class used when none is passed at the request-level.

See also Authentication.

base_url property writable #

base_url: URL

Base URL to use when sending requests with relative URLs.

cookies property writable #

cookies: Cookies

Cookie values to include when sending requests.

headers property writable #

headers: Headers

HTTP headers to include when sending requests.

is_closed property #

is_closed: bool

Check if the client being closed

params property writable #

params: QueryParams

Query parameters to include in the URL when sending requests.

build_request #

build_request(method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Request

Build and return a request instance.

  • The params, headers and cookies arguments are merged with any values set on the client.
  • The url argument is merged with any base_url set on the client.

See also: Request instances

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
def build_request(
    self,
    method: str,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Request:
    """
    Build and return a request instance.

    * The `params`, `headers` and `cookies` arguments
    are merged with any values set on the client.
    * The `url` argument is merged with any `base_url` set on the client.

    See also: [Request instances][0]

    [0]: /advanced/clients/#request-instances
    """
    url = self._merge_url(url)
    headers = self._merge_headers(headers)
    cookies = self._merge_cookies(cookies)
    params = self._merge_queryparams(params)
    extensions = {} if extensions is None else extensions
    if "timeout" not in extensions:
        timeout = (
            self.timeout
            if isinstance(timeout, UseClientDefault)
            else Timeout(timeout)
        )
        extensions = dict(**extensions, timeout=timeout.as_dict())
    return Request(
        method,
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        extensions=extensions,
    )

close #

close() -> None

Close transport and proxies.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
def close(self) -> None:
    """
    Close transport and proxies.
    """
    if self._state != ClientState.CLOSED:
        self._state = ClientState.CLOSED

        self._transport.close()
        for transport in self._mounts.values():
            if transport is not None:
                transport.close()

delete #

delete(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a DELETE request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
def delete(
    self,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `DELETE` request.

    **Parameters**: See `httpx.request`.
    """
    return self.request(
        "DELETE",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

get #

get(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a GET request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
def get(
    self,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `GET` request.

    **Parameters**: See `httpx.request`.
    """
    return self.request(
        "GET",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

head #

head(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a HEAD request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
def head(
    self,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `HEAD` request.

    **Parameters**: See `httpx.request`.
    """
    return self.request(
        "HEAD",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

options #

options(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send an OPTIONS request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
def options(
    self,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send an `OPTIONS` request.

    **Parameters**: See `httpx.request`.
    """
    return self.request(
        "OPTIONS",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

patch #

patch(url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a PATCH request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
def patch(
    self,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `PATCH` request.

    **Parameters**: See `httpx.request`.
    """
    return self.request(
        "PATCH",
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

post #

post(url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a POST request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
def post(
    self,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `POST` request.

    **Parameters**: See `httpx.request`.
    """
    return self.request(
        "POST",
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

put #

put(url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Send a PUT request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
def put(
    self,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Send a `PUT` request.

    **Parameters**: See `httpx.request`.
    """
    return self.request(
        "PUT",
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        follow_redirects=follow_redirects,
        timeout=timeout,
        extensions=extensions,
    )

request #

request(method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Response

Build and send a request.

Equivalent to:

request = client.build_request(...)
response = client.send(request, ...)

See Client.build_request(), Client.send() and Merging of configuration for how the various parameters are merged with client-level configuration.

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
def request(
    self,
    method: str,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> Response:
    """
    Build and send a request.

    Equivalent to:

    ```python
    request = client.build_request(...)
    response = client.send(request, ...)
    ```

    See `Client.build_request()`, `Client.send()` and
    [Merging of configuration][0] for how the various parameters
    are merged with client-level configuration.

    [0]: /advanced/clients/#merging-of-configuration
    """
    if cookies is not None:
        message = (
            "Setting per-request cookies=<...> is being deprecated, because "
            "the expected behaviour on cookie persistence is ambiguous. Set "
            "cookies directly on the client instance instead."
        )
        warnings.warn(message, DeprecationWarning, stacklevel=2)

    request = self.build_request(
        method=method,
        url=url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        timeout=timeout,
        extensions=extensions,
    )
    return self.send(request, auth=auth, follow_redirects=follow_redirects)

send #

send(request: Request, *, stream: bool = False, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT) -> Response

Send a request.

The request is sent as-is, unmodified.

Typically you'll want to build one with Client.build_request() so that any client-level configuration is merged into the request, but passing an explicit httpx.Request() is supported as well.

See also: Request instances

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
def send(
    self,
    request: Request,
    *,
    stream: bool = False,
    auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
) -> Response:
    """
    Send a request.

    The request is sent as-is, unmodified.

    Typically you'll want to build one with `Client.build_request()`
    so that any client-level configuration is merged into the request,
    but passing an explicit `httpx.Request()` is supported as well.

    See also: [Request instances][0]

    [0]: /advanced/clients/#request-instances
    """
    if self._state == ClientState.CLOSED:
        raise RuntimeError("Cannot send a request, as the client has been closed.")

    self._state = ClientState.OPENED
    follow_redirects = (
        self.follow_redirects
        if isinstance(follow_redirects, UseClientDefault)
        else follow_redirects
    )

    self._set_timeout(request)

    auth = self._build_request_auth(request, auth)

    response = self._send_handling_auth(
        request,
        auth=auth,
        follow_redirects=follow_redirects,
        history=[],
    )
    try:
        if not stream:
            response.read()

        return response

    except BaseException as exc:
        response.close()
        raise exc

stream #

stream(method: str, url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, extensions: RequestExtensions | None = None) -> Iterator[Response]

Alternative to httpx.request() that streams the response body instead of loading it into memory at once.

Parameters: See httpx.request.

See also: Streaming Responses

Source code in .venv/lib/python3.13/site-packages/httpx/_client.py
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
@contextmanager
def stream(
    self,
    method: str,
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT,
    follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT,
    timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT,
    extensions: RequestExtensions | None = None,
) -> typing.Iterator[Response]:
    """
    Alternative to `httpx.request()` that streams the response body
    instead of loading it into memory at once.

    **Parameters**: See `httpx.request`.

    See also: [Streaming Responses][0]

    [0]: /quickstart#streaming-responses
    """
    request = self.build_request(
        method=method,
        url=url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        timeout=timeout,
        extensions=extensions,
    )
    response = self.send(
        request=request,
        auth=auth,
        follow_redirects=follow_redirects,
        stream=True,
    )
    try:
        yield response
    finally:
        response.close()

CloseError #

CloseError(message: str, *, request: Request | None = None)

Failed to close a connection.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

ConnectError #

ConnectError(message: str, *, request: Request | None = None)

Failed to establish a connection.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

ConnectTimeout #

ConnectTimeout(message: str, *, request: Request | None = None)

Timed out while connecting to the host.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

CookieConflict #

CookieConflict(message: str)

Attempted to lookup a cookie by name, but multiple cookies existed.

Can occur when calling response.cookies.get(...).

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
287
288
def __init__(self, message: str) -> None:
    super().__init__(message)

Cookies #

Cookies(cookies: CookieTypes | None = None)

HTTP Cookies, as a mutable mapping.

Methods:

Name Description
clear

Delete all cookies. Optionally include a domain and path in

delete

Delete a cookie by name. May optionally include domain and path

extract_cookies

Loads any cookies based on the response Set-Cookie headers.

get

Get a cookie by name. May optionally include domain and path

set

Set a cookie value by name. May optionally include domain and path.

set_cookie_header

Sets an appropriate 'Cookie:' HTTP header on the Request.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
def __init__(self, cookies: CookieTypes | None = None) -> None:
    if cookies is None or isinstance(cookies, dict):
        self.jar = CookieJar()
        if isinstance(cookies, dict):
            for key, value in cookies.items():
                self.set(key, value)
    elif isinstance(cookies, list):
        self.jar = CookieJar()
        for key, value in cookies:
            self.set(key, value)
    elif isinstance(cookies, Cookies):
        self.jar = CookieJar()
        for cookie in cookies.jar:
            self.jar.set_cookie(cookie)
    else:
        self.jar = cookies

clear #

clear(domain: str | None = None, path: str | None = None) -> None

Delete all cookies. Optionally include a domain and path in order to only delete a subset of all the cookies.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
def clear(self, domain: str | None = None, path: str | None = None) -> None:
    """
    Delete all cookies. Optionally include a domain and path in
    order to only delete a subset of all the cookies.
    """
    args = []
    if domain is not None:
        args.append(domain)
    if path is not None:
        assert domain is not None
        args.append(path)
    self.jar.clear(*args)

delete #

delete(name: str, domain: str | None = None, path: str | None = None) -> None

Delete a cookie by name. May optionally include domain and path in order to specify exactly which cookie to delete.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
def delete(
    self,
    name: str,
    domain: str | None = None,
    path: str | None = None,
) -> None:
    """
    Delete a cookie by name. May optionally include domain and path
    in order to specify exactly which cookie to delete.
    """
    if domain is not None and path is not None:
        return self.jar.clear(domain, path, name)

    remove = [
        cookie
        for cookie in self.jar
        if cookie.name == name
        and (domain is None or cookie.domain == domain)
        and (path is None or cookie.path == path)
    ]

    for cookie in remove:
        self.jar.clear(cookie.domain, cookie.path, cookie.name)

extract_cookies #

extract_cookies(response: Response) -> None

Loads any cookies based on the response Set-Cookie headers.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
1101
1102
1103
1104
1105
1106
1107
1108
def extract_cookies(self, response: Response) -> None:
    """
    Loads any cookies based on the response `Set-Cookie` headers.
    """
    urllib_response = self._CookieCompatResponse(response)
    urllib_request = self._CookieCompatRequest(response.request)

    self.jar.extract_cookies(urllib_response, urllib_request)  # type: ignore

get #

get(name: str, default: str | None = None, domain: str | None = None, path: str | None = None) -> str | None

Get a cookie by name. May optionally include domain and path in order to specify exactly which cookie to retrieve.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
def get(  # type: ignore
    self,
    name: str,
    default: str | None = None,
    domain: str | None = None,
    path: str | None = None,
) -> str | None:
    """
    Get a cookie by name. May optionally include domain and path
    in order to specify exactly which cookie to retrieve.
    """
    value = None
    for cookie in self.jar:
        if cookie.name == name:
            if domain is None or cookie.domain == domain:
                if path is None or cookie.path == path:
                    if value is not None:
                        message = f"Multiple cookies exist with name={name}"
                        raise CookieConflict(message)
                    value = cookie.value

    if value is None:
        return default
    return value

set #

set(name: str, value: str, domain: str = '', path: str = '/') -> None

Set a cookie value by name. May optionally include domain and path.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None:
    """
    Set a cookie value by name. May optionally include domain and path.
    """
    kwargs = {
        "version": 0,
        "name": name,
        "value": value,
        "port": None,
        "port_specified": False,
        "domain": domain,
        "domain_specified": bool(domain),
        "domain_initial_dot": domain.startswith("."),
        "path": path,
        "path_specified": bool(path),
        "secure": False,
        "expires": None,
        "discard": True,
        "comment": None,
        "comment_url": None,
        "rest": {"HttpOnly": None},
        "rfc2109": False,
    }
    cookie = Cookie(**kwargs)  # type: ignore
    self.jar.set_cookie(cookie)
set_cookie_header(request: Request) -> None

Sets an appropriate 'Cookie:' HTTP header on the Request.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
1110
1111
1112
1113
1114
1115
def set_cookie_header(self, request: Request) -> None:
    """
    Sets an appropriate 'Cookie:' HTTP header on the `Request`.
    """
    urllib_request = self._CookieCompatRequest(request)
    self.jar.add_cookie_header(urllib_request)

DecodingError #

DecodingError(message: str, *, request: Request | None = None)

Decoding of the response failed, due to a malformed encoding.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

DigestAuth #

DigestAuth(username: str | bytes, password: str | bytes)

Methods:

Name Description
async_auth_flow

Execute the authentication flow asynchronously.

sync_auth_flow

Execute the authentication flow synchronously.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
187
188
189
190
191
def __init__(self, username: str | bytes, password: str | bytes) -> None:
    self._username = to_bytes(username)
    self._password = to_bytes(password)
    self._last_challenge: _DigestAuthChallenge | None = None
    self._nonce_count = 1

async_auth_flow async #

async_auth_flow(request: Request) -> AsyncGenerator[Request, Response]

Execute the authentication flow asynchronously.

By default, this defers to .auth_flow(). You should override this method when the authentication scheme does I/O and/or uses concurrency primitives.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
async def async_auth_flow(
    self, request: Request
) -> typing.AsyncGenerator[Request, Response]:
    """
    Execute the authentication flow asynchronously.

    By default, this defers to `.auth_flow()`. You should override this method
    when the authentication scheme does I/O and/or uses concurrency primitives.
    """
    if self.requires_request_body:
        await request.aread()

    flow = self.auth_flow(request)
    request = next(flow)

    while True:
        response = yield request
        if self.requires_response_body:
            await response.aread()

        try:
            request = flow.send(response)
        except StopIteration:
            break

sync_auth_flow #

sync_auth_flow(request: Request) -> Generator[Request, Response, None]

Execute the authentication flow synchronously.

By default, this defers to .auth_flow(). You should override this method when the authentication scheme does I/O and/or uses concurrency primitives.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def sync_auth_flow(
    self, request: Request
) -> typing.Generator[Request, Response, None]:
    """
    Execute the authentication flow synchronously.

    By default, this defers to `.auth_flow()`. You should override this method
    when the authentication scheme does I/O and/or uses concurrency primitives.
    """
    if self.requires_request_body:
        request.read()

    flow = self.auth_flow(request)
    request = next(flow)

    while True:
        response = yield request
        if self.requires_response_body:
            response.read()

        try:
            request = flow.send(response)
        except StopIteration:
            break

HTTPError #

HTTPError(message: str)

Base class for RequestError and HTTPStatusError.

Useful for try...except blocks when issuing a request, and then calling .raise_for_status().

For example:

try:
    response = httpx.get("https://www.example.com")
    response.raise_for_status()
except httpx.HTTPError as exc:
    print(f"HTTP Exception for {exc.request.url} - {exc}")
Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
92
93
94
def __init__(self, message: str) -> None:
    super().__init__(message)
    self._request: Request | None = None

HTTPStatusError #

HTTPStatusError(message: str, *, request: Request, response: Response)

The response had an error HTTP status of 4xx or 5xx.

May be raised when calling response.raise_for_status()

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
265
266
267
268
def __init__(self, message: str, *, request: Request, response: Response) -> None:
    super().__init__(message)
    self.request = request
    self.response = response

Headers #

Headers(headers: HeaderTypes | None = None, encoding: str | None = None)

HTTP headers, as a case-insensitive multi-dict.

Methods:

Name Description
__delitem__

Remove the header key.

__getitem__

Return a single header value.

__setitem__

Set the header key to value, removing any duplicate entries.

get

Return a header value. If multiple occurrences of the header occur

get_list

Return a list of all header values for a given key.

items

Return (key, value) items of headers. Concatenate headers

multi_items

Return a list of (key, value) pairs of headers. Allow multiple

Attributes:

Name Type Description
encoding str

Header encoding is mandated as ascii, but we allow fallbacks to utf-8

raw list[tuple[bytes, bytes]]

Returns a list of the raw header items, as byte pairs.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def __init__(
    self,
    headers: HeaderTypes | None = None,
    encoding: str | None = None,
) -> None:
    self._list = []  # type: typing.List[typing.Tuple[bytes, bytes, bytes]]

    if isinstance(headers, Headers):
        self._list = list(headers._list)
    elif isinstance(headers, Mapping):
        for k, v in headers.items():
            bytes_key = _normalize_header_key(k, encoding)
            bytes_value = _normalize_header_value(v, encoding)
            self._list.append((bytes_key, bytes_key.lower(), bytes_value))
    elif headers is not None:
        for k, v in headers:
            bytes_key = _normalize_header_key(k, encoding)
            bytes_value = _normalize_header_value(v, encoding)
            self._list.append((bytes_key, bytes_key.lower(), bytes_value))

    self._encoding = encoding

encoding property writable #

encoding: str

Header encoding is mandated as ascii, but we allow fallbacks to utf-8 or iso-8859-1.

raw property #

Returns a list of the raw header items, as byte pairs.

__delitem__ #

__delitem__(key: str) -> None

Remove the header key.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def __delitem__(self, key: str) -> None:
    """
    Remove the header `key`.
    """
    del_key = key.lower().encode(self.encoding)

    pop_indexes = [
        idx
        for idx, (_, item_key, _) in enumerate(self._list)
        if item_key.lower() == del_key
    ]

    if not pop_indexes:
        raise KeyError(key)

    for idx in reversed(pop_indexes):
        del self._list[idx]

__getitem__ #

__getitem__(key: str) -> str

Return a single header value.

If there are multiple headers with the same key, then we concatenate them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def __getitem__(self, key: str) -> str:
    """
    Return a single header value.

    If there are multiple headers with the same key, then we concatenate
    them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2
    """
    normalized_key = key.lower().encode(self.encoding)

    items = [
        header_value.decode(self.encoding)
        for _, header_key, header_value in self._list
        if header_key == normalized_key
    ]

    if items:
        return ", ".join(items)

    raise KeyError(key)

__setitem__ #

__setitem__(key: str, value: str) -> None

Set the header key to value, removing any duplicate entries. Retains insertion order.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def __setitem__(self, key: str, value: str) -> None:
    """
    Set the header `key` to `value`, removing any duplicate entries.
    Retains insertion order.
    """
    set_key = key.encode(self._encoding or "utf-8")
    set_value = value.encode(self._encoding or "utf-8")
    lookup_key = set_key.lower()

    found_indexes = [
        idx
        for idx, (_, item_key, _) in enumerate(self._list)
        if item_key == lookup_key
    ]

    for idx in reversed(found_indexes[1:]):
        del self._list[idx]

    if found_indexes:
        idx = found_indexes[0]
        self._list[idx] = (set_key, lookup_key, set_value)
    else:
        self._list.append((set_key, lookup_key, set_value))

get #

get(key: str, default: Any = None) -> Any

Return a header value. If multiple occurrences of the header occur then concatenate them together with commas.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
242
243
244
245
246
247
248
249
250
def get(self, key: str, default: typing.Any = None) -> typing.Any:
    """
    Return a header value. If multiple occurrences of the header occur
    then concatenate them together with commas.
    """
    try:
        return self[key]
    except KeyError:
        return default

get_list #

get_list(key: str, split_commas: bool = False) -> list[str]

Return a list of all header values for a given key. If split_commas=True is passed, then any comma separated header values are split into multiple return strings.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def get_list(self, key: str, split_commas: bool = False) -> list[str]:
    """
    Return a list of all header values for a given key.
    If `split_commas=True` is passed, then any comma separated header
    values are split into multiple return strings.
    """
    get_header_key = key.lower().encode(self.encoding)

    values = [
        item_value.decode(self.encoding)
        for _, item_key, item_value in self._list
        if item_key.lower() == get_header_key
    ]

    if not split_commas:
        return values

    split_values = []
    for value in values:
        split_values.extend([item.strip() for item in value.split(",")])
    return split_values

items #

items() -> ItemsView[str, str]

Return (key, value) items of headers. Concatenate headers into a single comma separated value when a key occurs multiple times.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def items(self) -> typing.ItemsView[str, str]:
    """
    Return `(key, value)` items of headers. Concatenate headers
    into a single comma separated value when a key occurs multiple times.
    """
    values_dict: dict[str, str] = {}
    for _, key, value in self._list:
        str_key = key.decode(self.encoding)
        str_value = value.decode(self.encoding)
        if str_key in values_dict:
            values_dict[str_key] += f", {str_value}"
        else:
            values_dict[str_key] = str_value
    return values_dict.items()

multi_items #

multi_items() -> list[tuple[str, str]]

Return a list of (key, value) pairs of headers. Allow multiple occurrences of the same key without concatenating into a single comma separated value.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
231
232
233
234
235
236
237
238
239
240
def multi_items(self) -> list[tuple[str, str]]:
    """
    Return a list of `(key, value)` pairs of headers. Allow multiple
    occurrences of the same key without concatenating into a single
    comma separated value.
    """
    return [
        (key.decode(self.encoding), value.decode(self.encoding))
        for _, key, value in self._list
    ]

InvalidURL #

InvalidURL(message: str)

URL is improperly formed or cannot be parsed.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
276
277
def __init__(self, message: str) -> None:
    super().__init__(message)

Limits #

Limits(*, max_connections: int | None = None, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = 5.0)

Configuration for limits to various client behaviors.

Parameters:

  • max_connections - The maximum number of concurrent connections that may be established.
  • max_keepalive_connections - Allow the connection pool to maintain keep-alive connections below this point. Should be less than or equal to max_connections.
  • keepalive_expiry - Time limit on idle keep-alive connections in seconds.
Source code in .venv/lib/python3.13/site-packages/httpx/_config.py
173
174
175
176
177
178
179
180
181
182
def __init__(
    self,
    *,
    max_connections: int | None = None,
    max_keepalive_connections: int | None = None,
    keepalive_expiry: float | None = 5.0,
) -> None:
    self.max_connections = max_connections
    self.max_keepalive_connections = max_keepalive_connections
    self.keepalive_expiry = keepalive_expiry

LocalProtocolError #

LocalProtocolError(message: str, *, request: Request | None = None)

A protocol was violated by the client.

For example if the user instantiated a Request instance explicitly, failed to include the mandatory Host: header, and then issued it directly using client.send().

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

NetRCAuth #

NetRCAuth(file: str | None = None)

Use a 'netrc' file to lookup basic auth credentials based on the url host.

Methods:

Name Description
async_auth_flow

Execute the authentication flow asynchronously.

sync_auth_flow

Execute the authentication flow synchronously.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
150
151
152
153
154
155
def __init__(self, file: str | None = None) -> None:
    # Lazily import 'netrc'.
    # There's no need for us to load this module unless 'NetRCAuth' is being used.
    import netrc

    self._netrc_info = netrc.netrc(file)

async_auth_flow async #

async_auth_flow(request: Request) -> AsyncGenerator[Request, Response]

Execute the authentication flow asynchronously.

By default, this defers to .auth_flow(). You should override this method when the authentication scheme does I/O and/or uses concurrency primitives.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
async def async_auth_flow(
    self, request: Request
) -> typing.AsyncGenerator[Request, Response]:
    """
    Execute the authentication flow asynchronously.

    By default, this defers to `.auth_flow()`. You should override this method
    when the authentication scheme does I/O and/or uses concurrency primitives.
    """
    if self.requires_request_body:
        await request.aread()

    flow = self.auth_flow(request)
    request = next(flow)

    while True:
        response = yield request
        if self.requires_response_body:
            await response.aread()

        try:
            request = flow.send(response)
        except StopIteration:
            break

sync_auth_flow #

sync_auth_flow(request: Request) -> Generator[Request, Response, None]

Execute the authentication flow synchronously.

By default, this defers to .auth_flow(). You should override this method when the authentication scheme does I/O and/or uses concurrency primitives.

Source code in .venv/lib/python3.13/site-packages/httpx/_auth.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def sync_auth_flow(
    self, request: Request
) -> typing.Generator[Request, Response, None]:
    """
    Execute the authentication flow synchronously.

    By default, this defers to `.auth_flow()`. You should override this method
    when the authentication scheme does I/O and/or uses concurrency primitives.
    """
    if self.requires_request_body:
        request.read()

    flow = self.auth_flow(request)
    request = next(flow)

    while True:
        response = yield request
        if self.requires_response_body:
            response.read()

        try:
            request = flow.send(response)
        except StopIteration:
            break

NetworkError #

NetworkError(message: str, *, request: Request | None = None)

The base class for network-related errors.

An error occurred while interacting with the network.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

PoolTimeout #

PoolTimeout(message: str, *, request: Request | None = None)

Timed out waiting to acquire a connection from the pool.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

ProtocolError #

ProtocolError(message: str, *, request: Request | None = None)

The protocol was violated.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

ProxyError #

ProxyError(message: str, *, request: Request | None = None)

An error occurred while establishing a proxy connection.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

QueryParams #

QueryParams(*args: QueryParamTypes | None, **kwargs: Any)

URL query parameters, as a multi-dict.

Methods:

Name Description
add

Return a new QueryParams instance, setting or appending the value of a key.

get

Get a value from the query param for a given key. If the key occurs

get_list

Get all values from the query param for a given key.

items

Return all items in the query params. If a key occurs more than once

keys

Return all the keys in the query params.

merge

Return a new QueryParams instance, updated with.

multi_items

Return all items in the query params. Allow duplicate keys to occur.

remove

Return a new QueryParams instance, removing the value of a key.

set

Return a new QueryParams instance, setting the value of a key.

values

Return all the values in the query params. If a key occurs more than once

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None:
    assert len(args) < 2, "Too many arguments."
    assert not (args and kwargs), "Cannot mix named and unnamed arguments."

    value = args[0] if args else kwargs

    if value is None or isinstance(value, (str, bytes)):
        value = value.decode("ascii") if isinstance(value, bytes) else value
        self._dict = parse_qs(value, keep_blank_values=True)
    elif isinstance(value, QueryParams):
        self._dict = {k: list(v) for k, v in value._dict.items()}
    else:
        dict_value: dict[typing.Any, list[typing.Any]] = {}
        if isinstance(value, (list, tuple)):
            # Convert list inputs like:
            #     [("a", "123"), ("a", "456"), ("b", "789")]
            # To a dict representation, like:
            #     {"a": ["123", "456"], "b": ["789"]}
            for item in value:
                dict_value.setdefault(item[0], []).append(item[1])
        else:
            # Convert dict inputs like:
            #    {"a": "123", "b": ["456", "789"]}
            # To dict inputs where values are always lists, like:
            #    {"a": ["123"], "b": ["456", "789"]}
            dict_value = {
                k: list(v) if isinstance(v, (list, tuple)) else [v]
                for k, v in value.items()
            }

        # Ensure that keys and values are neatly coerced to strings.
        # We coerce values `True` and `False` to JSON-like "true" and "false"
        # representations, and coerce `None` values to the empty string.
        self._dict = {
            str(k): [primitive_value_to_str(item) for item in v]
            for k, v in dict_value.items()
        }

add #

add(key: str, value: Any = None) -> QueryParams

Return a new QueryParams instance, setting or appending the value of a key.

Usage:

q = httpx.QueryParams("a=123") q = q.add("a", "456") assert q == httpx.QueryParams("a=123&a=456")

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
def add(self, key: str, value: typing.Any = None) -> QueryParams:
    """
    Return a new QueryParams instance, setting or appending the value of a key.

    Usage:

    q = httpx.QueryParams("a=123")
    q = q.add("a", "456")
    assert q == httpx.QueryParams("a=123&a=456")
    """
    q = QueryParams()
    q._dict = dict(self._dict)
    q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)]
    return q

get #

get(key: Any, default: Any = None) -> Any

Get a value from the query param for a given key. If the key occurs more than once, then only the first value is returned.

Usage:

q = httpx.QueryParams("a=123&a=456&b=789") assert q.get("a") == "123"

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
512
513
514
515
516
517
518
519
520
521
522
523
524
def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:
    """
    Get a value from the query param for a given key. If the key occurs
    more than once, then only the first value is returned.

    Usage:

    q = httpx.QueryParams("a=123&a=456&b=789")
    assert q.get("a") == "123"
    """
    if key in self._dict:
        return self._dict[str(key)][0]
    return default

get_list #

get_list(key: str) -> list[str]

Get all values from the query param for a given key.

Usage:

q = httpx.QueryParams("a=123&a=456&b=789") assert q.get_list("a") == ["123", "456"]

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
526
527
528
529
530
531
532
533
534
535
def get_list(self, key: str) -> list[str]:
    """
    Get all values from the query param for a given key.

    Usage:

    q = httpx.QueryParams("a=123&a=456&b=789")
    assert q.get_list("a") == ["123", "456"]
    """
    return list(self._dict.get(str(key), []))

items #

items() -> ItemsView[str, str]

Return all items in the query params. If a key occurs more than once only the first item for that key is returned.

Usage:

q = httpx.QueryParams("a=123&a=456&b=789") assert list(q.items()) == [("a", "123"), ("b", "789")]

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
486
487
488
489
490
491
492
493
494
495
496
def items(self) -> typing.ItemsView[str, str]:
    """
    Return all items in the query params. If a key occurs more than once
    only the first item for that key is returned.

    Usage:

    q = httpx.QueryParams("a=123&a=456&b=789")
    assert list(q.items()) == [("a", "123"), ("b", "789")]
    """
    return {k: v[0] for k, v in self._dict.items()}.items()

keys #

keys() -> KeysView[str]

Return all the keys in the query params.

Usage:

q = httpx.QueryParams("a=123&a=456&b=789") assert list(q.keys()) == ["a", "b"]

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
463
464
465
466
467
468
469
470
471
472
def keys(self) -> typing.KeysView[str]:
    """
    Return all the keys in the query params.

    Usage:

    q = httpx.QueryParams("a=123&a=456&b=789")
    assert list(q.keys()) == ["a", "b"]
    """
    return self._dict.keys()

merge #

merge(params: QueryParamTypes | None = None) -> QueryParams

Return a new QueryParams instance, updated with.

Usage:

q = httpx.QueryParams("a=123") q = q.merge({"b": "456"}) assert q == httpx.QueryParams("a=123&b=456")

q = httpx.QueryParams("a=123") q = q.merge({"a": "456", "b": "789"}) assert q == httpx.QueryParams("a=456&b=789")

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
def merge(self, params: QueryParamTypes | None = None) -> QueryParams:
    """
    Return a new QueryParams instance, updated with.

    Usage:

    q = httpx.QueryParams("a=123")
    q = q.merge({"b": "456"})
    assert q == httpx.QueryParams("a=123&b=456")

    q = httpx.QueryParams("a=123")
    q = q.merge({"a": "456", "b": "789"})
    assert q == httpx.QueryParams("a=456&b=789")
    """
    q = QueryParams(params)
    q._dict = {**self._dict, **q._dict}
    return q

multi_items #

multi_items() -> list[tuple[str, str]]

Return all items in the query params. Allow duplicate keys to occur.

Usage:

q = httpx.QueryParams("a=123&a=456&b=789") assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")]

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
498
499
500
501
502
503
504
505
506
507
508
509
510
def multi_items(self) -> list[tuple[str, str]]:
    """
    Return all items in the query params. Allow duplicate keys to occur.

    Usage:

    q = httpx.QueryParams("a=123&a=456&b=789")
    assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")]
    """
    multi_items: list[tuple[str, str]] = []
    for k, v in self._dict.items():
        multi_items.extend([(k, i) for i in v])
    return multi_items

remove #

remove(key: str) -> QueryParams

Return a new QueryParams instance, removing the value of a key.

Usage:

q = httpx.QueryParams("a=123") q = q.remove("a") assert q == httpx.QueryParams("")

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def remove(self, key: str) -> QueryParams:
    """
    Return a new QueryParams instance, removing the value of a key.

    Usage:

    q = httpx.QueryParams("a=123")
    q = q.remove("a")
    assert q == httpx.QueryParams("")
    """
    q = QueryParams()
    q._dict = dict(self._dict)
    q._dict.pop(str(key), None)
    return q

set #

set(key: str, value: Any = None) -> QueryParams

Return a new QueryParams instance, setting the value of a key.

Usage:

q = httpx.QueryParams("a=123") q = q.set("a", "456") assert q == httpx.QueryParams("a=456")

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
537
538
539
540
541
542
543
544
545
546
547
548
549
550
def set(self, key: str, value: typing.Any = None) -> QueryParams:
    """
    Return a new QueryParams instance, setting the value of a key.

    Usage:

    q = httpx.QueryParams("a=123")
    q = q.set("a", "456")
    assert q == httpx.QueryParams("a=456")
    """
    q = QueryParams()
    q._dict = dict(self._dict)
    q._dict[str(key)] = [primitive_value_to_str(value)]
    return q

values #

values() -> ValuesView[str]

Return all the values in the query params. If a key occurs more than once only the first item for that key is returned.

Usage:

q = httpx.QueryParams("a=123&a=456&b=789") assert list(q.values()) == ["123", "789"]

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
474
475
476
477
478
479
480
481
482
483
484
def values(self) -> typing.ValuesView[str]:
    """
    Return all the values in the query params. If a key occurs more than once
    only the first item for that key is returned.

    Usage:

    q = httpx.QueryParams("a=123&a=456&b=789")
    assert list(q.values()) == ["123", "789"]
    """
    return {k: v[0] for k, v in self._dict.items()}.values()

ReadError #

ReadError(message: str, *, request: Request | None = None)

Failed to receive data from the network.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

ReadTimeout #

ReadTimeout(message: str, *, request: Request | None = None)

Timed out while receiving data from the host.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

RemoteProtocolError #

RemoteProtocolError(message: str, *, request: Request | None = None)

The protocol was violated by the server.

For example, returning malformed HTTP.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

Request #

Request(method: str, url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, stream: SyncByteStream | AsyncByteStream | None = None, extensions: RequestExtensions | None = None)

Methods:

Name Description
aread

Read and return the request content.

read

Read and return the request content.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def __init__(
    self,
    method: str,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    stream: SyncByteStream | AsyncByteStream | None = None,
    extensions: RequestExtensions | None = None,
) -> None:
    self.method = method.upper()
    self.url = URL(url) if params is None else URL(url, params=params)
    self.headers = Headers(headers)
    self.extensions = {} if extensions is None else dict(extensions)

    if cookies:
        Cookies(cookies).set_cookie_header(self)

    if stream is None:
        content_type: str | None = self.headers.get("content-type")
        headers, stream = encode_request(
            content=content,
            data=data,
            files=files,
            json=json,
            boundary=get_multipart_boundary_from_content_type(
                content_type=content_type.encode(self.headers.encoding)
                if content_type
                else None
            ),
        )
        self._prepare(headers)
        self.stream = stream
        # Load the request body, except for streaming content.
        if isinstance(stream, ByteStream):
            self.read()
    else:
        # There's an important distinction between `Request(content=...)`,
        # and `Request(stream=...)`.
        #
        # Using `content=...` implies automatically populated `Host` and content
        # headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`.
        #
        # Using `stream=...` will not automatically include *any*
        # auto-populated headers.
        #
        # As an end-user you don't really need `stream=...`. It's only
        # useful when:
        #
        # * Preserving the request stream when copying requests, eg for redirects.
        # * Creating request instances on the *server-side* of the transport API.
        self.stream = stream

aread async #

aread() -> bytes

Read and return the request content.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
482
483
484
485
486
487
488
489
490
491
492
493
494
async def aread(self) -> bytes:
    """
    Read and return the request content.
    """
    if not hasattr(self, "_content"):
        assert isinstance(self.stream, typing.AsyncIterable)
        self._content = b"".join([part async for part in self.stream])
        if not isinstance(self.stream, ByteStream):
            # If a streaming request has been read entirely into memory, then
            # we can replace the stream with a raw bytes implementation,
            # to ensure that any non-replayable streams can still be used.
            self.stream = ByteStream(self._content)
    return self._content

read #

read() -> bytes

Read and return the request content.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
468
469
470
471
472
473
474
475
476
477
478
479
480
def read(self) -> bytes:
    """
    Read and return the request content.
    """
    if not hasattr(self, "_content"):
        assert isinstance(self.stream, typing.Iterable)
        self._content = b"".join(self.stream)
        if not isinstance(self.stream, ByteStream):
            # If a streaming request has been read entirely into memory, then
            # we can replace the stream with a raw bytes implementation,
            # to ensure that any non-replayable streams can still be used.
            self.stream = ByteStream(self._content)
    return self._content

RequestError #

RequestError(message: str, *, request: Request | None = None)

Base class for all exceptions that may occur when issuing a .request().

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

RequestNotRead #

RequestNotRead()

Attempted to access streaming request content, without having called read().

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
358
359
360
361
362
363
def __init__(self) -> None:
    message = (
        "Attempted to access streaming request content,"
        " without having called `read()`."
    )
    super().__init__(message)

Response #

Response(status_code: int, *, headers: HeaderTypes | None = None, content: ResponseContent | None = None, text: str | None = None, html: str | None = None, json: Any = None, stream: SyncByteStream | AsyncByteStream | None = None, request: Request | None = None, extensions: ResponseExtensions | None = None, history: list[Response] | None = None, default_encoding: str | Callable[[bytes], str] = 'utf-8')

Methods:

Name Description
aclose

Close the response and release the connection.

aiter_bytes

A byte-iterator over the decoded response content.

aiter_raw

A byte-iterator over the raw response content.

aiter_text

A str-iterator over the decoded response content

aread

Read and return the response content.

close

Close the response and release the connection.

iter_bytes

A byte-iterator over the decoded response content.

iter_raw

A byte-iterator over the raw response content.

iter_text

A str-iterator over the decoded response content

raise_for_status

Raise the HTTPStatusError if one occurred.

read

Read and return the response content.

Attributes:

Name Type Description
charset_encoding str | None

Return the encoding, as specified by the Content-Type header.

elapsed timedelta

Returns the time taken for the complete request/response

encoding str | None

Return an encoding to use for decoding the byte content into text.

has_redirect_location bool

Returns True for 3xx responses with a properly formed URL redirection,

is_client_error bool

A property which is True for 4xx status codes, False otherwise.

is_error bool

A property which is True for 4xx and 5xx status codes, False otherwise.

is_informational bool

A property which is True for 1xx status codes, False otherwise.

is_redirect bool

A property which is True for 3xx status codes, False otherwise.

is_server_error bool

A property which is True for 5xx status codes, False otherwise.

is_success bool

A property which is True for 2xx status codes, False otherwise.

links dict[str | None, dict[str, str]]

Returns the parsed header links of the response, if any

request Request

Returns the request instance associated to the current response.

url URL

Returns the URL for which the request was made.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
def __init__(
    self,
    status_code: int,
    *,
    headers: HeaderTypes | None = None,
    content: ResponseContent | None = None,
    text: str | None = None,
    html: str | None = None,
    json: typing.Any = None,
    stream: SyncByteStream | AsyncByteStream | None = None,
    request: Request | None = None,
    extensions: ResponseExtensions | None = None,
    history: list[Response] | None = None,
    default_encoding: str | typing.Callable[[bytes], str] = "utf-8",
) -> None:
    self.status_code = status_code
    self.headers = Headers(headers)

    self._request: Request | None = request

    # When follow_redirects=False and a redirect is received,
    # the client will set `response.next_request`.
    self.next_request: Request | None = None

    self.extensions = {} if extensions is None else dict(extensions)
    self.history = [] if history is None else list(history)

    self.is_closed = False
    self.is_stream_consumed = False

    self.default_encoding = default_encoding

    if stream is None:
        headers, stream = encode_response(content, text, html, json)
        self._prepare(headers)
        self.stream = stream
        if isinstance(stream, ByteStream):
            # Load the response body, except for streaming content.
            self.read()
    else:
        # There's an important distinction between `Response(content=...)`,
        # and `Response(stream=...)`.
        #
        # Using `content=...` implies automatically populated content headers,
        # of either `Content-Length: ...` or `Transfer-Encoding: chunked`.
        #
        # Using `stream=...` will not automatically include any content headers.
        #
        # As an end-user you don't really need `stream=...`. It's only
        # useful when creating response instances having received a stream
        # from the transport API.
        self.stream = stream

    self._num_bytes_downloaded = 0

charset_encoding property #

charset_encoding: str | None

Return the encoding, as specified by the Content-Type header.

elapsed property writable #

elapsed: timedelta

Returns the time taken for the complete request/response cycle to complete.

encoding property writable #

encoding: str | None

Return an encoding to use for decoding the byte content into text. The priority for determining this is given by...

  • .encoding = <> has been set explicitly.
  • The encoding as specified by the charset parameter in the Content-Type header.
  • The encoding as determined by default_encoding, which may either be a string like "utf-8" indicating the encoding to use, or may be a callable which enables charset autodetection.

has_redirect_location property #

has_redirect_location: bool

Returns True for 3xx responses with a properly formed URL redirection, False otherwise.

is_client_error property #

is_client_error: bool

A property which is True for 4xx status codes, False otherwise.

is_error property #

is_error: bool

A property which is True for 4xx and 5xx status codes, False otherwise.

is_informational property #

is_informational: bool

A property which is True for 1xx status codes, False otherwise.

is_redirect property #

is_redirect: bool

A property which is True for 3xx status codes, False otherwise.

Note that not all responses with a 3xx status code indicate a URL redirect.

Use response.has_redirect_location to determine responses with a properly formed URL redirection.

is_server_error property #

is_server_error: bool

A property which is True for 5xx status codes, False otherwise.

is_success property #

is_success: bool

A property which is True for 2xx status codes, False otherwise.

links: dict[str | None, dict[str, str]]

Returns the parsed header links of the response, if any

request property writable #

request: Request

Returns the request instance associated to the current response.

url property #

url: URL

Returns the URL for which the request was made.

aclose async #

aclose() -> None

Close the response and release the connection. Automatically called if the response body is read to completion.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
async def aclose(self) -> None:
    """
    Close the response and release the connection.
    Automatically called if the response body is read to completion.
    """
    if not isinstance(self.stream, AsyncByteStream):
        raise RuntimeError("Attempted to call an async close on an sync stream.")

    if not self.is_closed:
        self.is_closed = True
        with request_context(request=self._request):
            await self.stream.aclose()

aiter_bytes async #

aiter_bytes(chunk_size: int | None = None) -> AsyncIterator[bytes]

A byte-iterator over the decoded response content. This allows us to handle gzip, deflate, brotli, and zstd encoded responses.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
async def aiter_bytes(
    self, chunk_size: int | None = None
) -> typing.AsyncIterator[bytes]:
    """
    A byte-iterator over the decoded response content.
    This allows us to handle gzip, deflate, brotli, and zstd encoded responses.
    """
    if hasattr(self, "_content"):
        chunk_size = len(self._content) if chunk_size is None else chunk_size
        for i in range(0, len(self._content), max(chunk_size, 1)):
            yield self._content[i : i + chunk_size]
    else:
        decoder = self._get_content_decoder()
        chunker = ByteChunker(chunk_size=chunk_size)
        with request_context(request=self._request):
            async for raw_bytes in self.aiter_raw():
                decoded = decoder.decode(raw_bytes)
                for chunk in chunker.decode(decoded):
                    yield chunk
            decoded = decoder.flush()
            for chunk in chunker.decode(decoded):
                yield chunk  # pragma: no cover
            for chunk in chunker.flush():
                yield chunk

aiter_raw async #

aiter_raw(chunk_size: int | None = None) -> AsyncIterator[bytes]

A byte-iterator over the raw response content.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
async def aiter_raw(
    self, chunk_size: int | None = None
) -> typing.AsyncIterator[bytes]:
    """
    A byte-iterator over the raw response content.
    """
    if self.is_stream_consumed:
        raise StreamConsumed()
    if self.is_closed:
        raise StreamClosed()
    if not isinstance(self.stream, AsyncByteStream):
        raise RuntimeError("Attempted to call an async iterator on an sync stream.")

    self.is_stream_consumed = True
    self._num_bytes_downloaded = 0
    chunker = ByteChunker(chunk_size=chunk_size)

    with request_context(request=self._request):
        async for raw_stream_bytes in self.stream:
            self._num_bytes_downloaded += len(raw_stream_bytes)
            for chunk in chunker.decode(raw_stream_bytes):
                yield chunk

    for chunk in chunker.flush():
        yield chunk

    await self.aclose()

aiter_text async #

aiter_text(chunk_size: int | None = None) -> AsyncIterator[str]

A str-iterator over the decoded response content that handles both gzip, deflate, etc but also detects the content's string encoding.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
async def aiter_text(
    self, chunk_size: int | None = None
) -> typing.AsyncIterator[str]:
    """
    A str-iterator over the decoded response content
    that handles both gzip, deflate, etc but also detects the content's
    string encoding.
    """
    decoder = TextDecoder(encoding=self.encoding or "utf-8")
    chunker = TextChunker(chunk_size=chunk_size)
    with request_context(request=self._request):
        async for byte_content in self.aiter_bytes():
            text_content = decoder.decode(byte_content)
            for chunk in chunker.decode(text_content):
                yield chunk
        text_content = decoder.flush()
        for chunk in chunker.decode(text_content):
            yield chunk  # pragma: no cover
        for chunk in chunker.flush():
            yield chunk

aread async #

aread() -> bytes

Read and return the response content.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
974
975
976
977
978
979
980
async def aread(self) -> bytes:
    """
    Read and return the response content.
    """
    if not hasattr(self, "_content"):
        self._content = b"".join([part async for part in self.aiter_bytes()])
    return self._content

close #

close() -> None

Close the response and release the connection. Automatically called if the response body is read to completion.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
961
962
963
964
965
966
967
968
969
970
971
972
def close(self) -> None:
    """
    Close the response and release the connection.
    Automatically called if the response body is read to completion.
    """
    if not isinstance(self.stream, SyncByteStream):
        raise RuntimeError("Attempted to call an sync close on an async stream.")

    if not self.is_closed:
        self.is_closed = True
        with request_context(request=self._request):
            self.stream.close()

iter_bytes #

iter_bytes(chunk_size: int | None = None) -> Iterator[bytes]

A byte-iterator over the decoded response content. This allows us to handle gzip, deflate, brotli, and zstd encoded responses.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
def iter_bytes(self, chunk_size: int | None = None) -> typing.Iterator[bytes]:
    """
    A byte-iterator over the decoded response content.
    This allows us to handle gzip, deflate, brotli, and zstd encoded responses.
    """
    if hasattr(self, "_content"):
        chunk_size = len(self._content) if chunk_size is None else chunk_size
        for i in range(0, len(self._content), max(chunk_size, 1)):
            yield self._content[i : i + chunk_size]
    else:
        decoder = self._get_content_decoder()
        chunker = ByteChunker(chunk_size=chunk_size)
        with request_context(request=self._request):
            for raw_bytes in self.iter_raw():
                decoded = decoder.decode(raw_bytes)
                for chunk in chunker.decode(decoded):
                    yield chunk
            decoded = decoder.flush()
            for chunk in chunker.decode(decoded):
                yield chunk  # pragma: no cover
            for chunk in chunker.flush():
                yield chunk

iter_raw #

iter_raw(chunk_size: int | None = None) -> Iterator[bytes]

A byte-iterator over the raw response content.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
def iter_raw(self, chunk_size: int | None = None) -> typing.Iterator[bytes]:
    """
    A byte-iterator over the raw response content.
    """
    if self.is_stream_consumed:
        raise StreamConsumed()
    if self.is_closed:
        raise StreamClosed()
    if not isinstance(self.stream, SyncByteStream):
        raise RuntimeError("Attempted to call a sync iterator on an async stream.")

    self.is_stream_consumed = True
    self._num_bytes_downloaded = 0
    chunker = ByteChunker(chunk_size=chunk_size)

    with request_context(request=self._request):
        for raw_stream_bytes in self.stream:
            self._num_bytes_downloaded += len(raw_stream_bytes)
            for chunk in chunker.decode(raw_stream_bytes):
                yield chunk

    for chunk in chunker.flush():
        yield chunk

    self.close()

iter_text #

iter_text(chunk_size: int | None = None) -> Iterator[str]

A str-iterator over the decoded response content that handles both gzip, deflate, etc but also detects the content's string encoding.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
def iter_text(self, chunk_size: int | None = None) -> typing.Iterator[str]:
    """
    A str-iterator over the decoded response content
    that handles both gzip, deflate, etc but also detects the content's
    string encoding.
    """
    decoder = TextDecoder(encoding=self.encoding or "utf-8")
    chunker = TextChunker(chunk_size=chunk_size)
    with request_context(request=self._request):
        for byte_content in self.iter_bytes():
            text_content = decoder.decode(byte_content)
            for chunk in chunker.decode(text_content):
                yield chunk
        text_content = decoder.flush()
        for chunk in chunker.decode(text_content):
            yield chunk  # pragma: no cover
        for chunk in chunker.flush():
            yield chunk

raise_for_status #

raise_for_status() -> Response

Raise the HTTPStatusError if one occurred.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
def raise_for_status(self) -> Response:
    """
    Raise the `HTTPStatusError` if one occurred.
    """
    request = self._request
    if request is None:
        raise RuntimeError(
            "Cannot call `raise_for_status` as the request "
            "instance has not been set on this response."
        )

    if self.is_success:
        return self

    if self.has_redirect_location:
        message = (
            "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n"
            "Redirect location: '{0.headers[location]}'\n"
            "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}"
        )
    else:
        message = (
            "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n"
            "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}"
        )

    status_class = self.status_code // 100
    error_types = {
        1: "Informational response",
        3: "Redirect response",
        4: "Client error",
        5: "Server error",
    }
    error_type = error_types.get(status_class, "Invalid status code")
    message = message.format(self, error_type=error_type)
    raise HTTPStatusError(message, request=request, response=self)

read #

read() -> bytes

Read and return the response content.

Source code in .venv/lib/python3.13/site-packages/httpx/_models.py
876
877
878
879
880
881
882
def read(self) -> bytes:
    """
    Read and return the response content.
    """
    if not hasattr(self, "_content"):
        self._content = b"".join(self.iter_bytes())
    return self._content

ResponseNotRead #

ResponseNotRead()

Attempted to access streaming response content, without having called read().

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
345
346
347
348
349
350
def __init__(self) -> None:
    message = (
        "Attempted to access streaming response content,"
        " without having called `read()`."
    )
    super().__init__(message)

StreamClosed #

StreamClosed()

Attempted to read or stream response content, but the request has been closed.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
333
334
335
336
337
def __init__(self) -> None:
    message = (
        "Attempted to read or stream content, but the stream has " "been closed."
    )
    super().__init__(message)

StreamConsumed #

StreamConsumed()

Attempted to read or stream content, but the content has already been streamed.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
315
316
317
318
319
320
321
322
323
324
def __init__(self) -> None:
    message = (
        "Attempted to read or stream some content, but the content has "
        "already been streamed. For requests, this could be due to passing "
        "a generator as request content, and then receiving a redirect "
        "response or a secondary request as part of an authentication flow."
        "For responses, this could be due to attempting to stream the response "
        "content more than once."
    )
    super().__init__(message)

StreamError #

StreamError(message: str)

The base class for stream exceptions.

The developer made an error in accessing the request stream in an invalid way.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
305
306
def __init__(self, message: str) -> None:
    super().__init__(message)

SyncByteStream #

Methods:

Name Description
close

Subclasses can override this method to release any network resources

close #

close() -> None

Subclasses can override this method to release any network resources after a request/response cycle is complete.

Source code in .venv/lib/python3.13/site-packages/httpx/_types.py
 99
100
101
102
103
def close(self) -> None:
    """
    Subclasses can override this method to release any network resources
    after a request/response cycle is complete.
    """

Timeout #

Timeout(timeout: TimeoutTypes | UnsetType = UNSET, *, connect: None | float | UnsetType = UNSET, read: None | float | UnsetType = UNSET, write: None | float | UnsetType = UNSET, pool: None | float | UnsetType = UNSET)

Timeout configuration.

Usage:

Timeout(None) # No timeouts. Timeout(5.0) # 5s timeout on all operations. Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere. Timeout(5.0, pool=None) # No timeout on acquiring connection from pool. # 5s timeout elsewhere.

Source code in .venv/lib/python3.13/site-packages/httpx/_config.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def __init__(
    self,
    timeout: TimeoutTypes | UnsetType = UNSET,
    *,
    connect: None | float | UnsetType = UNSET,
    read: None | float | UnsetType = UNSET,
    write: None | float | UnsetType = UNSET,
    pool: None | float | UnsetType = UNSET,
) -> None:
    if isinstance(timeout, Timeout):
        # Passed as a single explicit Timeout.
        assert connect is UNSET
        assert read is UNSET
        assert write is UNSET
        assert pool is UNSET
        self.connect = timeout.connect  # type: typing.Optional[float]
        self.read = timeout.read  # type: typing.Optional[float]
        self.write = timeout.write  # type: typing.Optional[float]
        self.pool = timeout.pool  # type: typing.Optional[float]
    elif isinstance(timeout, tuple):
        # Passed as a tuple.
        self.connect = timeout[0]
        self.read = timeout[1]
        self.write = None if len(timeout) < 3 else timeout[2]
        self.pool = None if len(timeout) < 4 else timeout[3]
    elif not (
        isinstance(connect, UnsetType)
        or isinstance(read, UnsetType)
        or isinstance(write, UnsetType)
        or isinstance(pool, UnsetType)
    ):
        self.connect = connect
        self.read = read
        self.write = write
        self.pool = pool
    else:
        if isinstance(timeout, UnsetType):
            raise ValueError(
                "httpx.Timeout must either include a default, or set all "
                "four parameters explicitly."
            )
        self.connect = timeout if isinstance(connect, UnsetType) else connect
        self.read = timeout if isinstance(read, UnsetType) else read
        self.write = timeout if isinstance(write, UnsetType) else write
        self.pool = timeout if isinstance(pool, UnsetType) else pool

TimeoutException #

TimeoutException(message: str, *, request: Request | None = None)

The base class for timeout errors.

An operation has timed out.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

TooManyRedirects #

TooManyRedirects(message: str, *, request: Request | None = None)

Too many redirects.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

TransportError #

TransportError(message: str, *, request: Request | None = None)

Base class for all exceptions that occur at the level of the Transport API.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

URL #

URL(url: URL | str = '', **kwargs: Any)

url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink")

assert url.scheme == "https" assert url.username == "jo@email.com" assert url.password == "a secret" assert url.userinfo == b"jo%40email.com:a%20secret" assert url.host == "müller.de" assert url.raw_host == b"xn--mller-kva.de" assert url.port == 1234 assert url.netloc == b"xn--mller-kva.de:1234" assert url.path == "/pa th" assert url.query == b"?search=ab" assert url.raw_path == b"/pa%20th?search=ab" assert url.fragment == "anchorlink"

The components of a URL are broken down like this:

https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink [scheme] [ username ][password] [ host ][port][ path ][ query ] [fragment] [ userinfo ][ netloc ][ raw_path ]

Note that:

  • url.scheme is normalized to always be lowercased.

  • url.host is normalized to always be lowercased. Internationalized domain names are represented in unicode, without IDNA encoding applied. For instance:

url = httpx.URL("http://中国.icom.museum") assert url.host == "中国.icom.museum" url = httpx.URL("http://xn--fiqs8s.icom.museum") assert url.host == "中国.icom.museum"

  • url.raw_host is normalized to always be lowercased, and is IDNA encoded.

url = httpx.URL("http://中国.icom.museum") assert url.raw_host == b"xn--fiqs8s.icom.museum" url = httpx.URL("http://xn--fiqs8s.icom.museum") assert url.raw_host == b"xn--fiqs8s.icom.museum"

  • url.port is either None or an integer. URLs that include the default port for "http", "https", "ws", "wss", and "ftp" schemes have their port normalized to None.

assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80") assert httpx.URL("http://example.com").port is None assert httpx.URL("http://example.com:80").port is None

  • url.userinfo is raw bytes, without URL escaping. Usually you'll want to work with url.username and url.password instead, which handle the URL escaping.

  • url.raw_path is raw bytes of both the path and query, without URL escaping. This portion is used as the target when constructing HTTP requests. Usually you'll want to work with url.path instead.

  • url.query is raw bytes, without URL escaping. A URL query string portion can only be properly URL escaped when decoding the parameter names and values themselves.

Methods:

Name Description
copy_with

Copy this URL, returning a new URL with some components altered.

join

Return an absolute URL, using this URL as the base.

Attributes:

Name Type Description
fragment str

The URL fragments, as used in HTML anchors.

host str

The URL host as a string.

is_absolute_url bool

Return True for absolute URLs such as 'http://example.com/path',

is_relative_url bool

Return False for absolute URLs such as 'http://example.com/path',

netloc bytes

Either <host> or <host>:<port> as bytes.

params QueryParams

The URL query parameters, neatly parsed and packaged into an immutable

password str

The URL password as a string, with URL decoding applied.

path str

The URL path as a string. Excluding the query string, and URL decoded.

port int | None

The URL port as an integer.

query bytes

The URL query string, as raw bytes, excluding the leading b"?".

raw_host bytes

The raw bytes representation of the URL host.

raw_path bytes

The complete URL path and query string as raw bytes.

raw_scheme bytes

The raw bytes representation of the URL scheme, such as b"http", b"https".

scheme str

The URL scheme, such as "http", "https".

userinfo bytes

The URL userinfo as a raw bytestring.

username str

The URL username as a string, with URL decoding applied.

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def __init__(self, url: URL | str = "", **kwargs: typing.Any) -> None:
    if kwargs:
        allowed = {
            "scheme": str,
            "username": str,
            "password": str,
            "userinfo": bytes,
            "host": str,
            "port": int,
            "netloc": bytes,
            "path": str,
            "query": bytes,
            "raw_path": bytes,
            "fragment": str,
            "params": object,
        }

        # Perform type checking for all supported keyword arguments.
        for key, value in kwargs.items():
            if key not in allowed:
                message = f"{key!r} is an invalid keyword argument for URL()"
                raise TypeError(message)
            if value is not None and not isinstance(value, allowed[key]):
                expected = allowed[key].__name__
                seen = type(value).__name__
                message = f"Argument {key!r} must be {expected} but got {seen}"
                raise TypeError(message)
            if isinstance(value, bytes):
                kwargs[key] = value.decode("ascii")

        if "params" in kwargs:
            # Replace any "params" keyword with the raw "query" instead.
            #
            # Ensure that empty params use `kwargs["query"] = None` rather
            # than `kwargs["query"] = ""`, so that generated URLs do not
            # include an empty trailing "?".
            params = kwargs.pop("params")
            kwargs["query"] = None if not params else str(QueryParams(params))

    if isinstance(url, str):
        self._uri_reference = urlparse(url, **kwargs)
    elif isinstance(url, URL):
        self._uri_reference = url._uri_reference.copy_with(**kwargs)
    else:
        raise TypeError(
            "Invalid type for url.  Expected str or httpx.URL,"
            f" got {type(url)}: {url!r}"
        )

fragment property #

fragment: str

The URL fragments, as used in HTML anchors. As a string, without the leading '#'.

host property #

host: str

The URL host as a string. Always normalized to lowercase, with IDNA hosts decoded into unicode.

Examples:

url = httpx.URL("http://www.EXAMPLE.org") assert url.host == "www.example.org"

url = httpx.URL("http://中国.icom.museum") assert url.host == "中国.icom.museum"

url = httpx.URL("http://xn--fiqs8s.icom.museum") assert url.host == "中国.icom.museum"

url = httpx.URL("https://[::ffff:192.168.0.1]") assert url.host == "::ffff:192.168.0.1"

is_absolute_url property #

is_absolute_url: bool

Return True for absolute URLs such as 'http://example.com/path', and False for relative URLs such as '/path'.

is_relative_url property #

is_relative_url: bool

Return False for absolute URLs such as 'http://example.com/path', and True for relative URLs such as '/path'.

netloc property #

netloc: bytes

Either <host> or <host>:<port> as bytes. Always normalized to lowercase, and IDNA encoded.

This property may be used for generating the value of a request "Host" header.

params property #

params: QueryParams

The URL query parameters, neatly parsed and packaged into an immutable multidict representation.

password property #

password: str

The URL password as a string, with URL decoding applied. For example: "a secret"

path property #

path: str

The URL path as a string. Excluding the query string, and URL decoded.

For example:

url = httpx.URL("https://example.com/pa%20th") assert url.path == "/pa th"

port property #

port: int | None

The URL port as an integer.

Note that the URL class performs port normalization as per the WHATWG spec. Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always treated as None.

For example:

assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80") assert httpx.URL("http://www.example.com:80").port is None

query property #

query: bytes

The URL query string, as raw bytes, excluding the leading b"?".

This is necessarily a bytewise interface, because we cannot perform URL decoding of this representation until we've parsed the keys and values into a QueryParams instance.

For example:

url = httpx.URL("https://example.com/?filter=some%20search%20terms") assert url.query == b"filter=some%20search%20terms"

raw_host property #

raw_host: bytes

The raw bytes representation of the URL host. Always normalized to lowercase, and IDNA encoded.

Examples:

url = httpx.URL("http://www.EXAMPLE.org") assert url.raw_host == b"www.example.org"

url = httpx.URL("http://中国.icom.museum") assert url.raw_host == b"xn--fiqs8s.icom.museum"

url = httpx.URL("http://xn--fiqs8s.icom.museum") assert url.raw_host == b"xn--fiqs8s.icom.museum"

url = httpx.URL("https://[::ffff:192.168.0.1]") assert url.raw_host == b"::ffff:192.168.0.1"

raw_path property #

raw_path: bytes

The complete URL path and query string as raw bytes. Used as the target when constructing HTTP requests.

For example:

GET /users?search=some%20text HTTP/1.1 Host: www.example.org Connection: close

raw_scheme property #

raw_scheme: bytes

The raw bytes representation of the URL scheme, such as b"http", b"https". Always normalised to lowercase.

scheme property #

scheme: str

The URL scheme, such as "http", "https". Always normalised to lowercase.

userinfo property #

userinfo: bytes

The URL userinfo as a raw bytestring. For example: b"jo%40email.com:a%20secret".

username property #

username: str

The URL username as a string, with URL decoding applied. For example: "jo@email.com"

copy_with #

copy_with(**kwargs: Any) -> URL

Copy this URL, returning a new URL with some components altered. Accepts the same set of parameters as the components that are made available via properties on the URL class.

For example:

url = httpx.URL("https://www.example.com").copy_with( username="jo@gmail.com", password="a secret" ) assert url == "https://jo%40email.com:a%20secret@www.example.com"

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def copy_with(self, **kwargs: typing.Any) -> URL:
    """
    Copy this URL, returning a new URL with some components altered.
    Accepts the same set of parameters as the components that are made
    available via properties on the `URL` class.

    For example:

    url = httpx.URL("https://www.example.com").copy_with(
        username="jo@gmail.com", password="a secret"
    )
    assert url == "https://jo%40email.com:a%20secret@www.example.com"
    """
    return URL(self, **kwargs)

join #

join(url: URL | str) -> URL

Return an absolute URL, using this URL as the base.

Eg.

url = httpx.URL("https://www.example.com/test") url = url.join("/new/path") assert url == "https://www.example.com/new/path"

Source code in .venv/lib/python3.13/site-packages/httpx/_urls.py
354
355
356
357
358
359
360
361
362
363
364
365
366
def join(self, url: URL | str) -> URL:
    """
    Return an absolute URL, using this URL as the base.

    Eg.

    url = httpx.URL("https://www.example.com/test")
    url = url.join("/new/path")
    assert url == "https://www.example.com/new/path"
    """
    from urllib.parse import urljoin

    return URL(urljoin(str(self), str(URL(url))))

UnsupportedProtocol #

UnsupportedProtocol(message: str, *, request: Request | None = None)

Attempted to make a request to an unsupported protocol.

For example issuing a request to ftp://www.example.com.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

WSGITransport #

WSGITransport(app: WSGIApplication, raise_app_exceptions: bool = True, script_name: str = '', remote_addr: str = '127.0.0.1', wsgi_errors: TextIO | None = None)

A custom transport that handles sending requests directly to an WSGI app. The simplest way to use this functionality is to use the app argument.

client = httpx.Client(app=app)

Alternatively, you can setup the transport instance explicitly. This allows you to include any additional configuration arguments specific to the WSGITransport class:

transport = httpx.WSGITransport(
    app=app,
    script_name="/submount",
    remote_addr="1.2.3.4"
)
client = httpx.Client(transport=transport)

Arguments:

  • app - The WSGI application.
  • raise_app_exceptions - Boolean indicating if exceptions in the application should be raised. Default to True. Can be set to False for use cases such as testing the content of a client 500 response.
  • script_name - The root path on which the WSGI application should be mounted.
  • remote_addr - A string indicating the client IP of incoming requests. ```
Source code in .venv/lib/python3.13/site-packages/httpx/_transports/wsgi.py
77
78
79
80
81
82
83
84
85
86
87
88
89
def __init__(
    self,
    app: WSGIApplication,
    raise_app_exceptions: bool = True,
    script_name: str = "",
    remote_addr: str = "127.0.0.1",
    wsgi_errors: typing.TextIO | None = None,
) -> None:
    self.app = app
    self.raise_app_exceptions = raise_app_exceptions
    self.script_name = script_name
    self.remote_addr = remote_addr
    self.wsgi_errors = wsgi_errors

WriteError #

WriteError(message: str, *, request: Request | None = None)

Failed to send data through the network.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

WriteTimeout #

WriteTimeout(message: str, *, request: Request | None = None)

Timed out while sending data to the host.

Source code in .venv/lib/python3.13/site-packages/httpx/_exceptions.py
112
113
114
115
116
117
118
119
120
def __init__(self, message: str, *, request: Request | None = None) -> None:
    super().__init__(message)
    # At the point an exception is raised we won't typically have a request
    # instance to associate it with.
    #
    # The 'request_context' context manager is used within the Client and
    # Response methods in order to ensure that any raised exceptions
    # have a `.request` property set on them.
    self._request = request

codes #

HTTP status codes and reason phrases

Status codes from the following RFCs are all observed:

* RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616
* RFC 6585: Additional HTTP Status Codes
* RFC 3229: Delta encoding in HTTP
* RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518
* RFC 5842: Binding Extensions to WebDAV
* RFC 7238: Permanent Redirect
* RFC 2295: Transparent Content Negotiation in HTTP
* RFC 2774: An HTTP Extension Framework
* RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)
* RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)
* RFC 7725: An HTTP Status Code to Report Legal Obstacles
* RFC 8297: An HTTP Status Code for Indicating Hints
* RFC 8470: Using Early Data in HTTP

Methods:

Name Description
is_client_error

Returns True for 4xx status codes, False otherwise.

is_error

Returns True for 4xx or 5xx status codes, False otherwise.

is_informational

Returns True for 1xx status codes, False otherwise.

is_redirect

Returns True for 3xx status codes, False otherwise.

is_server_error

Returns True for 5xx status codes, False otherwise.

is_success

Returns True for 2xx status codes, False otherwise.

is_client_error classmethod #

is_client_error(value: int) -> bool

Returns True for 4xx status codes, False otherwise.

Source code in .venv/lib/python3.13/site-packages/httpx/_status_codes.py
66
67
68
69
70
71
@classmethod
def is_client_error(cls, value: int) -> bool:
    """
    Returns `True` for 4xx status codes, `False` otherwise.
    """
    return 400 <= value <= 499

is_error classmethod #

is_error(value: int) -> bool

Returns True for 4xx or 5xx status codes, False otherwise.

Source code in .venv/lib/python3.13/site-packages/httpx/_status_codes.py
80
81
82
83
84
85
@classmethod
def is_error(cls, value: int) -> bool:
    """
    Returns `True` for 4xx or 5xx status codes, `False` otherwise.
    """
    return 400 <= value <= 599

is_informational classmethod #

is_informational(value: int) -> bool

Returns True for 1xx status codes, False otherwise.

Source code in .venv/lib/python3.13/site-packages/httpx/_status_codes.py
45
46
47
48
49
50
@classmethod
def is_informational(cls, value: int) -> bool:
    """
    Returns `True` for 1xx status codes, `False` otherwise.
    """
    return 100 <= value <= 199

is_redirect classmethod #

is_redirect(value: int) -> bool

Returns True for 3xx status codes, False otherwise.

Source code in .venv/lib/python3.13/site-packages/httpx/_status_codes.py
59
60
61
62
63
64
@classmethod
def is_redirect(cls, value: int) -> bool:
    """
    Returns `True` for 3xx status codes, `False` otherwise.
    """
    return 300 <= value <= 399

is_server_error classmethod #

is_server_error(value: int) -> bool

Returns True for 5xx status codes, False otherwise.

Source code in .venv/lib/python3.13/site-packages/httpx/_status_codes.py
73
74
75
76
77
78
@classmethod
def is_server_error(cls, value: int) -> bool:
    """
    Returns `True` for 5xx status codes, `False` otherwise.
    """
    return 500 <= value <= 599

is_success classmethod #

is_success(value: int) -> bool

Returns True for 2xx status codes, False otherwise.

Source code in .venv/lib/python3.13/site-packages/httpx/_status_codes.py
52
53
54
55
56
57
@classmethod
def is_success(cls, value: int) -> bool:
    """
    Returns `True` for 2xx status codes, `False` otherwise.
    """
    return 200 <= value <= 299

delete #

delete(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, verify: SSLContext | str | bool = True, trust_env: bool = True) -> Response

Sends a DELETE request.

Parameters: See httpx.request.

Note that the data, files, json and content parameters are not available on this function, as DELETE requests should not include a request body.

Source code in .venv/lib/python3.13/site-packages/httpx/_api.py
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
def delete(
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | None = None,
    proxy: ProxyTypes | None = None,
    follow_redirects: bool = False,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    verify: ssl.SSLContext | str | bool = True,
    trust_env: bool = True,
) -> Response:
    """
    Sends a `DELETE` request.

    **Parameters**: See `httpx.request`.

    Note that the `data`, `files`, `json` and `content` parameters are not available
    on this function, as `DELETE` requests should not include a request body.
    """
    return request(
        "DELETE",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        proxy=proxy,
        follow_redirects=follow_redirects,
        verify=verify,
        timeout=timeout,
        trust_env=trust_env,
    )

get #

get(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True) -> Response

Sends a GET request.

Parameters: See httpx.request.

Note that the data, files, json and content parameters are not available on this function, as GET requests should not include a request body.

Source code in .venv/lib/python3.13/site-packages/httpx/_api.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def get(
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | None = None,
    proxy: ProxyTypes | None = None,
    follow_redirects: bool = False,
    verify: ssl.SSLContext | str | bool = True,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    trust_env: bool = True,
) -> Response:
    """
    Sends a `GET` request.

    **Parameters**: See `httpx.request`.

    Note that the `data`, `files`, `json` and `content` parameters are not available
    on this function, as `GET` requests should not include a request body.
    """
    return request(
        "GET",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        proxy=proxy,
        follow_redirects=follow_redirects,
        verify=verify,
        timeout=timeout,
        trust_env=trust_env,
    )

head #

head(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True) -> Response

Sends a HEAD request.

Parameters: See httpx.request.

Note that the data, files, json and content parameters are not available on this function, as HEAD requests should not include a request body.

Source code in .venv/lib/python3.13/site-packages/httpx/_api.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def head(
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | None = None,
    proxy: ProxyTypes | None = None,
    follow_redirects: bool = False,
    verify: ssl.SSLContext | str | bool = True,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    trust_env: bool = True,
) -> Response:
    """
    Sends a `HEAD` request.

    **Parameters**: See `httpx.request`.

    Note that the `data`, `files`, `json` and `content` parameters are not available
    on this function, as `HEAD` requests should not include a request body.
    """
    return request(
        "HEAD",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        proxy=proxy,
        follow_redirects=follow_redirects,
        verify=verify,
        timeout=timeout,
        trust_env=trust_env,
    )

options #

options(url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True) -> Response

Sends an OPTIONS request.

Parameters: See httpx.request.

Note that the data, files, json and content parameters are not available on this function, as OPTIONS requests should not include a request body.

Source code in .venv/lib/python3.13/site-packages/httpx/_api.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def options(
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | None = None,
    proxy: ProxyTypes | None = None,
    follow_redirects: bool = False,
    verify: ssl.SSLContext | str | bool = True,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    trust_env: bool = True,
) -> Response:
    """
    Sends an `OPTIONS` request.

    **Parameters**: See `httpx.request`.

    Note that the `data`, `files`, `json` and `content` parameters are not available
    on this function, as `OPTIONS` requests should not include a request body.
    """
    return request(
        "OPTIONS",
        url,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        proxy=proxy,
        follow_redirects=follow_redirects,
        verify=verify,
        timeout=timeout,
        trust_env=trust_env,
    )

patch #

patch(url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True) -> Response

Sends a PATCH request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_api.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
def patch(
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | None = None,
    proxy: ProxyTypes | None = None,
    follow_redirects: bool = False,
    verify: ssl.SSLContext | str | bool = True,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    trust_env: bool = True,
) -> Response:
    """
    Sends a `PATCH` request.

    **Parameters**: See `httpx.request`.
    """
    return request(
        "PATCH",
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        proxy=proxy,
        follow_redirects=follow_redirects,
        verify=verify,
        timeout=timeout,
        trust_env=trust_env,
    )

post #

post(url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True) -> Response

Sends a POST request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_api.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def post(
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | None = None,
    proxy: ProxyTypes | None = None,
    follow_redirects: bool = False,
    verify: ssl.SSLContext | str | bool = True,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    trust_env: bool = True,
) -> Response:
    """
    Sends a `POST` request.

    **Parameters**: See `httpx.request`.
    """
    return request(
        "POST",
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        proxy=proxy,
        follow_redirects=follow_redirects,
        verify=verify,
        timeout=timeout,
        trust_env=trust_env,
    )

put #

put(url: URL | str, *, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True) -> Response

Sends a PUT request.

Parameters: See httpx.request.

Source code in .venv/lib/python3.13/site-packages/httpx/_api.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
def put(
    url: URL | str,
    *,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    params: QueryParamTypes | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | None = None,
    proxy: ProxyTypes | None = None,
    follow_redirects: bool = False,
    verify: ssl.SSLContext | str | bool = True,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    trust_env: bool = True,
) -> Response:
    """
    Sends a `PUT` request.

    **Parameters**: See `httpx.request`.
    """
    return request(
        "PUT",
        url,
        content=content,
        data=data,
        files=files,
        json=json,
        params=params,
        headers=headers,
        cookies=cookies,
        auth=auth,
        proxy=proxy,
        follow_redirects=follow_redirects,
        verify=verify,
        timeout=timeout,
        trust_env=trust_env,
    )

request #

request(method: str, url: URL | str, *, params: QueryParamTypes | None = None, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, follow_redirects: bool = False, verify: SSLContext | str | bool = True, trust_env: bool = True) -> Response

Sends an HTTP request.

Parameters:

  • method - HTTP method for the new Request object: GET, OPTIONS, HEAD, POST, PUT, PATCH, or DELETE.
  • url - URL for the new Request object.
  • params - (optional) Query parameters to include in the URL, as a string, dictionary, or sequence of two-tuples.
  • content - (optional) Binary content to include in the body of the request, as bytes or a byte iterator.
  • data - (optional) Form data to include in the body of the request, as a dictionary.
  • files - (optional) A dictionary of upload files to include in the body of the request.
  • json - (optional) A JSON serializable object to include in the body of the request.
  • headers - (optional) Dictionary of HTTP headers to include in the request.
  • cookies - (optional) Dictionary of Cookie items to include in the request.
  • auth - (optional) An authentication class to use when sending the request.
  • proxy - (optional) A proxy URL where all the traffic should be routed.
  • timeout - (optional) The timeout configuration to use when sending the request.
  • follow_redirects - (optional) Enables or disables HTTP redirects.
  • verify - (optional) Either True to use an SSL context with the default CA bundle, False to disable verification, or an instance of ssl.SSLContext to use a custom context.
  • trust_env - (optional) Enables or disables usage of environment variables for configuration.

Returns: Response

Usage:

>>> import httpx
>>> response = httpx.request('GET', 'https://httpbin.org/get')
>>> response
<Response [200 OK]>
Source code in .venv/lib/python3.13/site-packages/httpx/_api.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def request(
    method: str,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | None = None,
    proxy: ProxyTypes | None = None,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    follow_redirects: bool = False,
    verify: ssl.SSLContext | str | bool = True,
    trust_env: bool = True,
) -> Response:
    """
    Sends an HTTP request.

    **Parameters:**

    * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`,
    `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`.
    * **url** - URL for the new `Request` object.
    * **params** - *(optional)* Query parameters to include in the URL, as a
    string, dictionary, or sequence of two-tuples.
    * **content** - *(optional)* Binary content to include in the body of the
    request, as bytes or a byte iterator.
    * **data** - *(optional)* Form data to include in the body of the request,
    as a dictionary.
    * **files** - *(optional)* A dictionary of upload files to include in the
    body of the request.
    * **json** - *(optional)* A JSON serializable object to include in the body
    of the request.
    * **headers** - *(optional)* Dictionary of HTTP headers to include in the
    request.
    * **cookies** - *(optional)* Dictionary of Cookie items to include in the
    request.
    * **auth** - *(optional)* An authentication class to use when sending the
    request.
    * **proxy** - *(optional)* A proxy URL where all the traffic should be routed.
    * **timeout** - *(optional)* The timeout configuration to use when sending
    the request.
    * **follow_redirects** - *(optional)* Enables or disables HTTP redirects.
    * **verify** - *(optional)* Either `True` to use an SSL context with the
    default CA bundle, `False` to disable verification, or an instance of
    `ssl.SSLContext` to use a custom context.
    * **trust_env** - *(optional)* Enables or disables usage of environment
    variables for configuration.

    **Returns:** `Response`

    Usage:

    ```
    >>> import httpx
    >>> response = httpx.request('GET', 'https://httpbin.org/get')
    >>> response
    <Response [200 OK]>
    ```
    """
    with Client(
        cookies=cookies,
        proxy=proxy,
        verify=verify,
        timeout=timeout,
        trust_env=trust_env,
    ) as client:
        return client.request(
            method=method,
            url=url,
            content=content,
            data=data,
            files=files,
            json=json,
            params=params,
            headers=headers,
            auth=auth,
            follow_redirects=follow_redirects,
        )

stream #

stream(method: str, url: URL | str, *, params: QueryParamTypes | None = None, content: RequestContent | None = None, data: RequestData | None = None, files: RequestFiles | None = None, json: Any | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, follow_redirects: bool = False, verify: SSLContext | str | bool = True, trust_env: bool = True) -> Iterator[Response]

Alternative to httpx.request() that streams the response body instead of loading it into memory at once.

Parameters: See httpx.request.

See also: Streaming Responses

Source code in .venv/lib/python3.13/site-packages/httpx/_api.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
@contextmanager
def stream(
    method: str,
    url: URL | str,
    *,
    params: QueryParamTypes | None = None,
    content: RequestContent | None = None,
    data: RequestData | None = None,
    files: RequestFiles | None = None,
    json: typing.Any | None = None,
    headers: HeaderTypes | None = None,
    cookies: CookieTypes | None = None,
    auth: AuthTypes | None = None,
    proxy: ProxyTypes | None = None,
    timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
    follow_redirects: bool = False,
    verify: ssl.SSLContext | str | bool = True,
    trust_env: bool = True,
) -> typing.Iterator[Response]:
    """
    Alternative to `httpx.request()` that streams the response body
    instead of loading it into memory at once.

    **Parameters**: See `httpx.request`.

    See also: [Streaming Responses][0]

    [0]: /quickstart#streaming-responses
    """
    with Client(
        cookies=cookies,
        proxy=proxy,
        verify=verify,
        timeout=timeout,
        trust_env=trust_env,
    ) as client:
        with client.stream(
            method=method,
            url=url,
            content=content,
            data=data,
            files=files,
            json=json,
            params=params,
            headers=headers,
            auth=auth,
            follow_redirects=follow_redirects,
        ) as response:
            yield response