Skip to content

Developer Interface

Helper Functions

Note

Only use these functions if you're testing HTTPX in a console or making a small number of requests. Using a Client will enable HTTP/2 and connection pooling for more efficient and long-lived connections.

httpx2.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:

Name Type Description Default
method str

HTTP method for the new Request object: GET, OPTIONS, HEAD, POST, PUT, PATCH, DELETE, or QUERY.

required
url URL | str

URL for the new Request object.

required
params QueryParamTypes | None

(optional) Query parameters to include in the URL, as a string, dictionary, or sequence of two-tuples.

None
content RequestContent | None

(optional) Binary content to include in the body of the request, as bytes or a byte iterator.

None
data RequestData | None

(optional) Form data to include in the body of the request, as a dictionary.

None
files RequestFiles | None

(optional) A dictionary of upload files to include in the body of the request.

None
json Any | None

(optional) A JSON serializable object to include in the body of the request.

None
headers HeaderTypes | None

(optional) Dictionary of HTTP headers to include in the request.

None
cookies CookieTypes | None

(optional) Dictionary of Cookie items to include in the request.

None
auth AuthTypes | None

(optional) An authentication class to use when sending the request.

None
proxy ProxyTypes | None

(optional) A proxy URL where all the traffic should be routed.

None
timeout TimeoutTypes

(optional) The timeout configuration to use when sending the request.

DEFAULT_TIMEOUT_CONFIG
follow_redirects bool

(optional) Enables or disables HTTP redirects.

False
verify SSLContext | str | bool

(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.

True
trust_env bool

(optional) Enables or disables usage of environment variables for configuration.

True

Returns:

Type Description
Response

The Response object.

Usage:

>>> import httpx2
>>> response = httpx2.request('GET', 'https://httpbin.org/get')
>>> response
<Response [200 OK]>

httpx2.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 httpx2.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.

httpx2.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 httpx2.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.

httpx2.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 httpx2.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.

httpx2.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 httpx2.request.

httpx2.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 httpx2.request.

httpx2.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 httpx2.request.

httpx2.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 httpx2.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.

httpx2.query

query(
    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 QUERY request.

Parameters: See httpx2.request.

httpx2.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,
) -> Generator[Response]

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

Parameters: See httpx2.request.

See also: Streaming Responses

httpx2.websocket

websocket(
    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,
    subprotocols: list[str] | None = None,
    max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
    queue_size: int = DEFAULT_QUEUE_SIZE,
    keepalive_ping_interval_seconds: float
    | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
    keepalive_ping_timeout_seconds: float
    | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
) -> Generator[WebSocketSession]

Open a WebSocket session.

The session is closed automatically when exiting the context manager.

with httpx2.websocket("ws://localhost:8000/ws") as ws:
    ws.send_text("Hello!")
    message = ws.receive_text()

Parameters: See httpx2.request and httpx2.Client.websocket.

Client

httpx2.Client

Bases: BaseClient

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

It can be shared between threads.

Usage:

>>> client = httpx2.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.
  • mounts - (optional) A dictionary mapping URL patterns to transports, used to route requests through specific transports based on the URL.
  • 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".

headers property writable

headers: Headers

HTTP headers to include when sending requests.

cookies property writable

cookies: Cookies

Cookie values to include when sending requests.

params property writable

params: QueryParams

Query parameters to include in the URL when sending requests.

auth property writable

auth: Auth | None

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

See also Authentication.

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.

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 httpx2.request.

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 httpx2.request.

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 httpx2.request.

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 httpx2.request.

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 httpx2.request.

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 httpx2.request.

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 httpx2.request.

query

query(
    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 QUERY request.

Parameters: See httpx2.request.

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,
) -> Generator[Response]

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

Parameters: See httpx2.request.

See also: Streaming Responses

sse

sse(
    url: URL | str,
    *,
    method: str = "GET",
    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,
) -> Generator[EventSource]

Connect to a server-sent events endpoint and yield an EventSource.

Iterating the EventSource yields ServerSentEvent instances.

Parameters: See httpx2.request.

websocket

websocket(
    url: URL | str,
    *,
    max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
    queue_size: int = DEFAULT_QUEUE_SIZE,
    keepalive_ping_interval_seconds: float
    | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
    keepalive_ping_timeout_seconds: float
    | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
    subprotocols: list[str] | 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,
) -> Generator[WebSocketSession]

Open a WebSocket session, using this client's configuration.

The session is closed automatically when exiting the context manager.

with httpx2.Client() as client:
    with client.websocket("ws://localhost:8000/ws") as ws:
        ws.send_text("Hello!")
        message = ws.receive_text()

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

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 httpx2.Request() is supported as well.

See also: Request instances

close

close() -> None

Close transport and proxies.

AsyncClient

httpx2.AsyncClient

Bases: BaseClient

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

It can be shared between tasks.

Usage:

>>> async with httpx2.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.
  • mounts - (optional) A dictionary mapping URL patterns to transports, used to route requests through specific transports based on the URL.
  • 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".

headers property writable

headers: Headers

HTTP headers to include when sending requests.

cookies property writable

cookies: Cookies

Cookie values to include when sending requests.

params property writable

params: QueryParams

Query parameters to include in the URL when sending requests.

auth property writable

auth: Auth | None

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

See also Authentication.

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.

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 httpx2.request.

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 httpx2.request.

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 httpx2.request.

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 httpx2.request.

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 httpx2.request.

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 httpx2.request.

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 httpx2.request.

query async

query(
    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 QUERY request.

Parameters: See httpx2.request.

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,
) -> AsyncGenerator[Response]

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

Parameters: See httpx2.request.

See also: Streaming Responses

sse async

sse(
    url: URL | str,
    *,
    method: str = "GET",
    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,
) -> AsyncGenerator[EventSource]

Connect to a server-sent events endpoint and yield an EventSource.

Iterating the EventSource yields ServerSentEvent instances.

Parameters: See httpx2.request.

websocket async

websocket(
    url: URL | str,
    *,
    max_message_size_bytes: int = DEFAULT_MAX_MESSAGE_SIZE_BYTES,
    queue_size: int = DEFAULT_QUEUE_SIZE,
    keepalive_ping_interval_seconds: float
    | None = DEFAULT_KEEPALIVE_PING_INTERVAL_SECONDS,
    keepalive_ping_timeout_seconds: float
    | None = DEFAULT_KEEPALIVE_PING_TIMEOUT_SECONDS,
    subprotocols: list[str] | 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,
) -> AsyncGenerator[AsyncWebSocketSession]

Open a WebSocket session, using this client's configuration.

The session is closed automatically when exiting the context manager.

async with httpx2.AsyncClient() as client:
    async with client.websocket("ws://localhost:8000/ws") as ws:
        await ws.send_text("Hello!")
        message = await ws.receive_text()

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

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 httpx2.Request() is supported as well.

See also: Request instances

aclose async

aclose() -> None

Close transport and proxies.

Response

An HTTP response.

  • def __init__(...)
  • .status_code - int
  • .reason_phrase - str
  • .http_version - "HTTP/2" or "HTTP/1.1"
  • .url - URL
  • .headers - Headers
  • .content - bytes
  • .text - str
  • .encoding - str
  • .is_redirect - bool
  • .request - Request
  • .next_request - Optional[Request]
  • .cookies - Cookies
  • .history - List[Response]
  • .elapsed - timedelta
  • The amount of time elapsed between sending the request and calling close() on the corresponding response received for that request. total_seconds() to correctly get the total elapsed seconds.
  • def .raise_for_status() - Response
  • def .json() - Any
  • def .read() - bytes
  • def .iter_raw([chunk_size]) - bytes iterator
  • def .iter_bytes([chunk_size]) - bytes iterator
  • def .iter_text([chunk_size]) - text iterator
  • def .iter_lines() - text iterator
  • def .close() - None
  • def .next() - Response
  • def .aread() - bytes
  • def .aiter_raw([chunk_size]) - async bytes iterator
  • def .aiter_bytes([chunk_size]) - async bytes iterator
  • def .aiter_text([chunk_size]) - async text iterator
  • def .aiter_lines() - async text iterator
  • def .aclose() - None
  • def .anext() - Response

Request

An HTTP request. Can be constructed explicitly for more control over exactly what gets sent over the wire.

>>> request = httpx2.Request("GET", "https://example.org", headers={'host': 'example.org'})
>>> response = client.send(request)
  • def __init__(method, url, [params], [headers], [cookies], [content], [data], [files], [json], [stream])
  • .method - str
  • .url - URL
  • .content - byte, byte iterator, or byte async iterator
  • .headers - Headers
  • .cookies - Cookies

URL

A normalized, IDNA supporting URL.

>>> url = URL("https://example.org/")
>>> url.host
'example.org'
  • def __init__(url, **kwargs)
  • .scheme - str
  • .authority - str
  • .host - str
  • .port - int
  • .path - str
  • .query - str
  • .raw_path - str
  • .fragment - str
  • .is_ssl - bool
  • .is_absolute_url - bool
  • .is_relative_url - bool
  • def .copy_with([scheme], [authority], [path], [query], [fragment]) - URL

Headers

A case-insensitive multi-dict.

>>> headers = Headers({'Content-Type': 'application/json'})
>>> headers['content-type']
'application/json'
  • def __init__(self, headers, encoding=None)
  • def copy() - Headers

Cookies

A dict-like cookie store.

>>> cookies = Cookies()
>>> cookies.set("name", "value", domain="example.org")
  • def __init__(cookies: [dict, Cookies, CookieJar])
  • .jar - CookieJar
  • def extract_cookies(response)
  • def set_cookie_header(request)
  • def set(name, value, [domain], [path])
  • def get(name, [domain], [path])
  • def delete(name, [domain], [path])
  • def clear([domain], [path])
  • Standard mutable mapping interface

Proxy

A configuration of the proxy server.

>>> proxy = Proxy("http://proxy.example.com:8030")
>>> client = Client(proxy=proxy)
  • def __init__(url, [ssl_context], [auth], [headers])
  • .url - URL
  • .auth - tuple[str, str]
  • .headers - Headers
  • .ssl_context - SSLContext

EventSource

httpx2.EventSource

response property

response: Response

ServerSentEvent

httpx2.ServerSentEvent dataclass

event class-attribute instance-attribute

event: str = 'message'

data class-attribute instance-attribute

data: str = ''

id class-attribute instance-attribute

id: str = ''

retry class-attribute instance-attribute

retry: int | None = None

json

json() -> object

WebSocketSession

httpx2.websockets.WebSocketSession

Sync context manager representing an opened WebSocket session.

Attributes:

Name Type Description
subprotocol Optional[str]

Optional protocol that has been accepted by the server.

response Response | None

The webSocket handshake response.

subprotocol instance-attribute

subprotocol: str | None

response instance-attribute

response: Response | None = response

send_text

send_text(data: str) -> None

Send a text message.

Parameters:

Name Type Description Default
data str

The text to send.

required

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send a text message.

ws.send_text("Hello!")

send_bytes

send_bytes(data: bytes) -> None

Send a bytes message.

Parameters:

Name Type Description Default
data bytes

The data to send.

required

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send a bytes message.

ws.send_bytes(b"Hello!")

send_json

send_json(data: Any, mode: JSONMode = 'text') -> None

Send JSON data.

Parameters:

Name Type Description Default
data Any

The data to send. Must be serializable by json.dumps.

required
mode JSONMode

The sending mode. Should either be 'text' or 'bytes'.

'text'

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Examples:

Send JSON data.

data = {"message": "Hello!"}
ws.send_json(data)

receive_text

receive_text(timeout: float | None = None) -> str

Receive text from the server.

Parameters:

Name Type Description Default
timeout float | None

Number of seconds to wait for an event. If None, will block until an event is available.

None

Returns:

Type Description
str

Text data.

Raises:

Type Description
TimeoutError

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event was not a text message.

Examples:

Wait for text until available.

try:
    text = ws.receive_text()
except WebSocketDisconnect:
    print("Connection closed")

Wait for text for 2 seconds.

try:
    event = ws.receive_text(timeout=2.)
except TimeoutError:
    print("No text received.")
except WebSocketDisconnect:
    print("Connection closed")

receive_bytes

receive_bytes(timeout: float | None = None) -> bytes

Receive bytes from the server.

Parameters:

Name Type Description Default
timeout float | None

Number of seconds to wait for an event. If None, will block until an event is available.

None

Returns:

Type Description
bytes

Bytes data.

Raises:

Type Description
TimeoutError

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event was not a bytes message.

Examples:

Wait for bytes until available.

try:
    data = ws.receive_bytes()
except WebSocketDisconnect:
    print("Connection closed")

Wait for bytes for 2 seconds.

try:
    data = ws.receive_bytes(timeout=2.)
except TimeoutError:
    print("No data received.")
except WebSocketDisconnect:
    print("Connection closed")

receive_json

receive_json(
    timeout: float | None = None, mode: JSONMode = "text"
) -> typing.Any

Receive JSON data from the server.

The received data should be parseable by json.loads.

Parameters:

Name Type Description Default
timeout float | None

Number of seconds to wait for an event. If None, will block until an event is available.

None
mode JSONMode

Receive mode. Should either be 'text' or 'bytes'.

'text'

Returns:

Type Description
Any

Parsed JSON data.

Raises:

Type Description
TimeoutError

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event didn't correspond to the specified mode.

Examples:

Wait for data until available.

try:
    data = ws.receive_json()
except WebSocketDisconnect:
    print("Connection closed")

Wait for data for 2 seconds.

try:
    data = ws.receive_json(timeout=2.)
except TimeoutError:
    print("No data received.")
except WebSocketDisconnect:
    print("Connection closed")

ping

ping(payload: bytes = b'') -> threading.Event

Send a Ping message.

Parameters:

Name Type Description Default
payload bytes

Payload to attach to the Ping event. Internally, it's used to track this specific event. If left empty, a random one will be generated.

b''

Returns:

Type Description
Event

An event that can be used to wait for the corresponding Pong response.

Examples:

Send a Ping and wait for the Pong

pong_callback = ws.ping()
# Will block until the corresponding Pong is received.
pong_callback.wait()

close

close(code: int = 1000, reason: str | None = None) -> None

Close the WebSocket session.

Internally, it'll send the [CloseConnection][wsproto.events.CloseConnection] event.

This method is automatically called when exiting the context manager.

Parameters:

Name Type Description Default
code int

The integer close code to indicate why the connection has closed.

1000
reason str | None

Additional reasoning for why the connection has closed.

None

Examples:

Close the WebSocket session.

ws.close()

AsyncWebSocketSession

httpx2.websockets.AsyncWebSocketSession

Bases: AsyncContextManagerMixin

Async context manager representing an opened WebSocket session.

Internally, this session uses an anyio task group to manage background tasks. As a result, exceptions that are not caught inside the context manager and propagate out of the async with block will be wrapped in an ExceptionGroup.

To handle them, use the except* syntax:

async with AsyncWebSocketSession(stream) as ws:
    try:
        data = await ws.receive_text()
    except WebSocketDisconnect:
        # Caught inside the context manager: plain exception.
        print("Connection closed")

# If not caught inside:
try:
    async with AsyncWebSocketSession(stream) as ws:
        data = await ws.receive_text()
except* WebSocketDisconnect:
    # Propagated out of the context manager: wrapped in ExceptionGroup.
    print("Connection closed")

Attributes:

Name Type Description
subprotocol Optional[str]

Optional protocol that has been accepted by the server.

response Response | None

The webSocket handshake response.

subprotocol instance-attribute

subprotocol: str | None

response instance-attribute

response: Response | None = response

send_text async

send_text(data: str) -> None

Send a text message.

Parameters:

Name Type Description Default
data str

The text to send.

required

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Note

Exceptions not caught inside the context manager will be wrapped in an ExceptionGroup. Use except* to catch them outside the async with block.

Examples:

Send a text message.

await ws.send_text("Hello!")

send_bytes async

send_bytes(data: bytes) -> None

Send a bytes message.

Parameters:

Name Type Description Default
data bytes

The data to send.

required

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Note

Exceptions not caught inside the context manager will be wrapped in an ExceptionGroup. Use except* to catch them outside the async with block.

Examples:

Send a bytes message.

await ws.send_bytes(b"Hello!")

send_json async

send_json(data: Any, mode: JSONMode = 'text') -> None

Send JSON data.

Parameters:

Name Type Description Default
data Any

The data to send. Must be serializable by json.dumps.

required
mode JSONMode

The sending mode. Should either be 'text' or 'bytes'.

'text'

Raises:

Type Description
WebSocketNetworkError

A network error occured.

Note

Exceptions not caught inside the context manager will be wrapped in an ExceptionGroup. Use except* to catch them outside the async with block.

Examples:

Send JSON data.

data = {"message": "Hello!"}
await ws.send_json(data)

receive_text async

receive_text(timeout: float | None = None) -> str

Receive text from the server.

Parameters:

Name Type Description Default
timeout float | None

Number of seconds to wait for an event. If None, will block until an event is available.

None

Returns:

Type Description
str

Text data.

Raises:

Type Description
TimeoutError

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event was not a text message.

Note

Exceptions not caught inside the context manager will be wrapped in an ExceptionGroup. Use except* to catch them outside the async with block.

Examples:

Wait for text until available.

try:
    text = await ws.receive_text()
except WebSocketDisconnect:
    print("Connection closed")

Wait for text for 2 seconds.

try:
    event = await ws.receive_text(timeout=2.)
except TimeoutError:
    print("No text received.")
except WebSocketDisconnect:
    print("Connection closed")

receive_bytes async

receive_bytes(timeout: float | None = None) -> bytes

Receive bytes from the server.

Parameters:

Name Type Description Default
timeout float | None

Number of seconds to wait for an event. If None, will block until an event is available.

None

Returns:

Type Description
bytes

Bytes data.

Raises:

Type Description
TimeoutError

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event was not a bytes message.

Note

Exceptions not caught inside the context manager will be wrapped in an ExceptionGroup. Use except* to catch them outside the async with block.

Examples:

Wait for bytes until available.

try:
    data = await ws.receive_bytes()
except WebSocketDisconnect:
    print("Connection closed")

Wait for bytes for 2 seconds.

try:
    data = await ws.receive_bytes(timeout=2.)
except TimeoutError:
    print("No data received.")
except WebSocketDisconnect:
    print("Connection closed")

receive_json async

receive_json(
    timeout: float | None = None, mode: JSONMode = "text"
) -> typing.Any

Receive JSON data from the server.

The received data should be parseable by json.loads.

Parameters:

Name Type Description Default
timeout float | None

Number of seconds to wait for an event. If None, will block until an event is available.

None
mode JSONMode

Receive mode. Should either be 'text' or 'bytes'.

'text'

Returns:

Type Description
Any

Parsed JSON data.

Raises:

Type Description
TimeoutError

No event was received before the timeout delay.

WebSocketDisconnect

The server closed the websocket.

WebSocketNetworkError

A network error occured.

WebSocketInvalidTypeReceived

The received event didn't correspond to the specified mode.

Note

Exceptions not caught inside the context manager will be wrapped in an ExceptionGroup. Use except* to catch them outside the async with block.

Examples:

Wait for data until available.

try:
    data = await ws.receive_json()
except WebSocketDisconnect:
    print("Connection closed")

Wait for data for 2 seconds.

try:
    data = await ws.receive_json(timeout=2.)
except TimeoutError:
    print("No data received.")
except WebSocketDisconnect:
    print("Connection closed")

ping async

ping(payload: bytes = b'') -> anyio.Event

Send a Ping message.

Parameters:

Name Type Description Default
payload bytes

Payload to attach to the Ping event. Internally, it's used to track this specific event. If left empty, a random one will be generated.

b''

Returns:

Type Description
Event

An event that can be used to wait for the corresponding Pong response.

Examples:

Send a Ping and wait for the Pong

pong_callback = await ws.ping()
# Will block until the corresponding Pong is received.
await pong_callback.wait()

close async

close(code: int = 1000, reason: str | None = None) -> None

Close the WebSocket session.

Internally, it'll send the [CloseConnection][wsproto.events.CloseConnection] event.

This method is automatically called when exiting the context manager.

Parameters:

Name Type Description Default
code int

The integer close code to indicate why the connection has closed.

1000
reason str | None

Additional reasoning for why the connection has closed.

None

Examples:

Close the WebSocket session.

await ws.close()