### Install httpx2 Source: https://httpx2.pydantic.dev/ Install the httpx2 library using pip. This is the basic installation for core functionality. ```bash pip install httpx2 ``` -------------------------------- ### Install Project Dependencies Source: https://httpx2.pydantic.dev/contributing Navigate to the project directory and install the project and its dependencies using the provided script. ```bash cd httpx2 scripts/install ``` -------------------------------- ### AsyncIO GET Request with HTTPX Source: https://httpx2.pydantic.dev/async Demonstrates making a GET request using httpx2 within an AsyncIO event loop. Ensure httpx2 is installed. ```python import asyncio import httpx2 async def main(): async with httpx2.AsyncClient() as client: response = await client.get('https://www.example.com/') print(response) asyncio.run(main()) ``` -------------------------------- ### Install SOCKS Proxy Support Source: https://httpx2.pydantic.dev/advanced/proxies Install the necessary third-party library to enable SOCKS proxy functionality in HTTPX. ```bash pip install 'httpx2[socks]' ``` -------------------------------- ### Install httpx2 with HTTP/2 support Source: https://httpx2.pydantic.dev/http2 Install the optional HTTP/2 dependencies for httpx2 using pip. ```bash pip install 'httpx2[http2]' ``` -------------------------------- ### Trio GET Request with HTTPX Source: https://httpx2.pydantic.dev/async Demonstrates making a GET request using httpx2 within a Trio event loop. The 'trio' package must be installed. ```python import httpx2 import trio async def main(): async with httpx2.AsyncClient() as client: response = await client.get('https://www.example.com/') print(response) trio.run(main) ``` -------------------------------- ### Install httpx2 with CLI support Source: https://httpx2.pydantic.dev/ Install httpx2 along with the command-line interface (CLI) dependencies. This enables using httpx2 directly from the terminal. ```bash # The command line client is an optional dependency. pip install 'httpx2[cli]' ``` -------------------------------- ### Import HTTPX2 Source: https://httpx2.pydantic.dev/quickstart Start by importing the httpx2 library to begin making requests. ```python >>> import httpx2 ``` -------------------------------- ### Initialize and Use httpx2 Client Source: https://httpx2.pydantic.dev/api Demonstrates basic initialization of an httpx2.Client and making a GET request. The client can be shared across threads. ```python >>> client = httpx2.Client() >>> response = client.get('https://example.org') ``` -------------------------------- ### Install httpx2 with Brotli and Zstandard support Source: https://httpx2.pydantic.dev/ Install httpx2 with optional support for Brotli and Zstandard compression algorithms. This allows for decoding responses compressed with these methods. ```bash pip install 'httpx2[brotli,zstd]' ``` -------------------------------- ### Display httpx2 CLI help Source: https://httpx2.pydantic.dev/ Use the command-line client to display help information for httpx2. This requires the optional CLI dependencies to be installed. ```bash httpx2 --help ``` -------------------------------- ### AsyncClient Usage Example Source: https://httpx2.pydantic.dev/api Demonstrates the basic usage of `AsyncClient` within an asynchronous context manager. ```python >>> async with httpx2.AsyncClient() as client: >>> response = await client.get('https://example.org') ``` -------------------------------- ### Configure Advanced Logging with dictConfig for httpx2 Source: https://httpx2.pydantic.dev/logging Use `logging.config.dictConfig` for more complex logging setups. This example configures handlers and formatters for both httpx2 and httpcore loggers, directing output to stderr. ```python import logging.config import httpx2 LOGGING_CONFIG = { "version": 1, "handlers": { "default": { "class": "logging.StreamHandler", "formatter": "http", "stream": "ext://sys.stderr" } }, "formatters": { "http": { "format": "% (levelname)s [%(asctime)s] %(name)s - %(message)s", "datefmt": "%Y-%m-%d %H:%M:%S", } }, 'loggers': { 'httpx2': { 'handlers': ['default'], 'level': 'DEBUG', }, 'httpcore': { 'handlers': ['default'], 'level': 'DEBUG', }, } } logging.config.dictConfig(LOGGING_CONFIG) httpx2.get('https://www.example.com') ``` -------------------------------- ### AnyIO GET Request with HTTPX (Trio Backend) Source: https://httpx2.pydantic.dev/async Demonstrates making a GET request using httpx2 with AnyIO, explicitly specifying the 'trio' backend. AnyIO defaults to 'asyncio' if not specified. ```python import httpx2 import anyio async def main(): async with httpx2.AsyncClient() as client: response = await client.get('https://www.example.com/') print(response) anyio.run(main, backend='trio') ``` -------------------------------- ### Install chardet for Auto-detection Source: https://httpx2.pydantic.dev/advanced/text-encodings Installs the necessary packages, httpx2 and chardet, to enable character-set auto-detection. ```bash pip install httpx2 pip install chardet ``` -------------------------------- ### Make a GET request with httpx2 Client Source: https://httpx2.pydantic.dev/advanced/clients Instantiate a client and use its .get() method to send a request. The client is managed using a context manager. ```python >>> with httpx2.Client() as client: ... r = client.get('https://example.com') ... ``` ```python >>> r ``` -------------------------------- ### Basic GET Request with httpx2 Source: https://httpx2.pydantic.dev/ Demonstrates a simple synchronous GET request to a URL and accessing response properties like status code, headers, and text content. Ensure httpx2 is imported before use. ```python >>> import httpx2 >>> r = httpx2.get('https://www.example.org/') >>> r >>> r.status_code 200 >>> r.headers['content-type'] 'text/html; charset=UTF-8' >>> r.text '\n\n\nExample Domain...' ``` -------------------------------- ### Example httpx2 Debug Log Output Source: https://httpx2.pydantic.dev/logging This is an example of the debug-level output generated by httpx2 and httpcore when making a request. It shows connection details, TLS negotiation, and HTTP request/response information. ```text DEBUG [2024-09-28 17:27:40] httpcore.connection - connect_tcp.started host='www.example.com' port=443 local_address=None timeout=5.0 socket_options=None DEBUG [2024-09-28 17:27:41] httpcore.connection - connect_tcp.complete return_value= DEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.started ssl_context=SSLContext(verify=True) server_hostname='www.example.com' timeout=5.0 DEBUG [2024-09-28 17:27:41] httpcore.connection - start_tls.complete return_value= DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_headers.started request= DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_headers.complete DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_body.started request= DEBUG [2024-09-28 17:27:41] httpcore.http11 - send_request_body.complete DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_headers.started request= DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Content-Encoding', b'gzip'), (b'Accept-Ranges', b'bytes'), (b'Age', b'407727'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Sat, 28 Sep 2024 13:27:42 GMT'), (b'Etag', b'"3147526947+gzip"'), (b'Expires', b'Sat, 05 Oct 2024 13:27:42 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECAcc (dcd/7D43)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'648')]) INFO [2024-09-28 17:27:41] httpx2 - HTTP Request: GET https://www.example.com "HTTP/1.1 200 OK" DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_body.started request= DEBUG [2024-09-28 17:27:41] httpcore.http11 - receive_response_body.complete DEBUG [2024-09-28 17:27:41] httpcore.http11 - response_closed.started DEBUG [2024-09-28 17:27:41] httpcore.http11 - response_closed.complete DEBUG [2024-09-28 17:27:41] httpcore.connection - close.started DEBUG [2024-09-28 17:27:41] httpcore.connection - close.complete ``` -------------------------------- ### Install Trace Handler for httpcore Events Source: https://httpx2.pydantic.dev/advanced/extensions Install a callback handler to monitor internal httpcore transport events. The handler receives event names and associated information. For async code, use an `async def` function. ```python import httpx2 def log(event_name, info): print(event_name, info) client = httpx2.Client() response = client.get("https://www.example.com/", extensions={"trace": log}) ``` -------------------------------- ### HTTP Basic Authentication Example Source: https://httpx2.pydantic.dev/advanced/authentication Demonstrates HTTP basic authentication. This scheme is unencrypted and should ideally be used over HTTPS. ```python >>> auth = httpx2.BasicAuth(username="finley", password="secret") >>> client = httpx2.Client(auth=auth) >>> response = client.get("https://httpbin.org/basic-auth/finley/secret") >>> response ``` -------------------------------- ### Make a GET Request Source: https://httpx2.pydantic.dev/quickstart Use httpx2.get() to fetch content from a URL. The response object contains the server's reply. ```python >>> r = httpx2.get('https://httpbin.org/get') >>> r ``` -------------------------------- ### HTTPX2 Proxy Configuration Example Source: https://httpx2.pydantic.dev/troubleshooting This snippet demonstrates a simplified way to configure a proxy for HTTPX client by passing the proxy URL directly to the Client constructor. This is useful when a single proxy is used for all requests. ```python mounts = { "http://": httpx2.HTTPTransport(proxy="http://myproxy.org"), "https://": httpx2.HTTPTransport(proxy="https://myproxy.org"), } ``` -------------------------------- ### Send a GET Request Source: https://httpx2.pydantic.dev/api Sends a `GET` request to the specified URL. Parameters are detailed in `httpx2.request`. ```python 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 with httpx2 Client Source: https://httpx2.pydantic.dev/api Sends a GET request using the httpx2 client. Parameters are detailed in httpx2.request. ```python 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 ``` -------------------------------- ### Clone HTTPX Repository Source: https://httpx2.pydantic.dev/contributing Clone your fork of the HTTPX repository to start development. Replace YOUR-USERNAME with your GitHub username. ```bash git clone https://github.com/YOUR-USERNAME/httpx2 ``` -------------------------------- ### Iterate Through Redirects with Requests Source: https://httpx2.pydantic.dev/compatibility This example shows how to use the `response.next` attribute in the `requests` library to iterate through a sequence of redirects. ```python session = requests.Session() request = requests.Request("GET", ...).prepare() while request is not None: response = session.send(request, allow_redirects=False) request = response.next ``` -------------------------------- ### ASGI Transport Example with Starlette Source: https://httpx2.pydantic.dev/advanced/transports Integrates an httpx2 async client with a Starlette application using the ASGI transport. Ideal for testing asynchronous web applications. ```python from starlette.applications import Starlette from starlette.responses import HTMLResponse from starlette.routing import Route async def hello(request): return HTMLResponse("Hello World!") app = Starlette(routes=[Route("/", hello)]) ``` ```python transport = httpx2.ASGITransport(app=app) async with httpx2.AsyncClient(transport=transport, base_url="http://testserver") as client: r = await client.get("/") assert r.status_code == 200 assert r.text == "Hello World!" ``` -------------------------------- ### Complex Proxy Routing Configuration Source: https://httpx2.pydantic.dev/advanced/transports Combine routing features to build complex proxy configurations. This example shows how to set default proxies, exclude specific domains, and use different proxies for various subdomains and protocols. ```python mounts = { # Route all traffic through a proxy by default... "all://": httpx2.HTTPTransport(proxy="http://localhost:8030"), # But don't use proxies for HTTPS requests to "domain.io"... "https://domain.io": None, # And use another proxy for requests to "example.com" and its subdomains... "all://*example.com": httpx2.HTTPTransport(proxy="http://localhost:8031"), # And yet another proxy if HTTP is used, # and the "internal" subdomain on port 5550 is requested... "http://internal.example.com:5550": httpx2.HTTPTransport(proxy="http://localhost:8032"), } ``` -------------------------------- ### Client.get Source: https://httpx2.pydantic.dev/api Send a GET request to the specified URL with optional parameters for query, headers, cookies, authentication, redirects, and timeout. ```APIDOC ## `get` ### Description Send a `GET` request. ### Method Signature ```python 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 ``` **Parameters** : See `httpx2.request`. ``` -------------------------------- ### WSGI Transport Example with Flask Source: https://httpx2.pydantic.dev/advanced/transports Integrates an httpx2 client with a Flask application using the WSGI transport. Useful for testing web applications. ```python from flask import Flask import httpx2 app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" transport = httpx2.WSGITransport(app=app) with httpx2.Client(transport=transport, base_url="http://testserver") as client: r = client.get("/") assert r.status_code == 200 assert r.text == "Hello World!" ``` -------------------------------- ### Making an Async GET Request Source: https://httpx2.pydantic.dev/async Use `httpx2.AsyncClient` within an `async with` block to make asynchronous HTTP requests. This is the recommended way to manage the client's lifecycle. ```python async with httpx2.AsyncClient() as client: r = await client.get('https://www.example.com/') r ``` -------------------------------- ### AsyncClient.get Source: https://httpx2.pydantic.dev/api Sends an asynchronous GET request to the specified URL, with options for parameters, headers, cookies, authentication, redirects, and timeouts. ```APIDOC ## AsyncClient.get ### Description Send a `GET` request. ### Method `async` ### Endpoint `get(url: URL | str, ...)` ### Parameters * **url** (URL | str) - The URL for the request. * **params** (QueryParamTypes | None) - Optional query parameters. * **headers** (HeaderTypes | None) - Optional headers. * **cookies** (CookieTypes | None) - Optional cookies. * **auth** (AuthTypes | UseClientDefault | None) - Optional authentication. Defaults to `USE_CLIENT_DEFAULT`. * **follow_redirects** (bool | UseClientDefault) - Optional boolean to follow redirects. Defaults to `USE_CLIENT_DEFAULT`. * **timeout** (TimeoutTypes | UseClientDefault) - Optional timeout configuration. Defaults to `USE_CLIENT_DEFAULT`. * **extensions** (RequestExtensions | None) - Optional request extensions. **Parameters**: See `httpx2.request`. ``` -------------------------------- ### Modify Event Hooks After Client Instantiation Source: https://httpx2.pydantic.dev/advanced/event-hooks Demonstrates how to set and modify event hooks using the `.event_hooks` property after the client has been created. This allows for dynamic changes to installed hooks. ```python client = httpx2.Client() client.event_hooks['request'] = [log_request] client.event_hooks['response'] = [log_response, raise_on_4xx_5xx] ``` -------------------------------- ### HTTP Digest Authentication Example Source: https://httpx2.pydantic.dev/advanced/authentication Demonstrates HTTP digest authentication, a challenge-response scheme providing encryption. It requires an extra round-trip for negotiation and can be used over unencrypted HTTP. ```python >>> auth = httpx2.DigestAuth(username="olivia", password="secret") >>> client = httpx2.Client(auth=auth) >>> response = client.get("https://httpbin.org/digest-auth/auth/olivia/secret") >>> response >>> response.history [] ``` -------------------------------- ### Setting HTTP Proxy Source: https://httpx2.pydantic.dev/environment_variables Set the `HTTP_PROXY` environment variable to specify a proxy for HTTP requests. This example shows how to set the variable and then make a request that will be sent through the proxy. ```bash export HTTP_PROXY=http://my-external-proxy.com:1234 ``` ```python import httpx2; httpx2.get('http://example.com') ``` ```python import httpx2; httpx2.get('http://example.com', trust_env=False) ``` -------------------------------- ### Register Request and Response Logging Hooks Source: https://httpx2.pydantic.dev/advanced/event-hooks Installs logging functions for both request and response events. The 'request' hook logs method and URL before sending, and the 'response' hook logs method, URL, and status code after receiving. ```python def log_request(request): print(f"Request event hook: {request.method} {request.url} - Waiting for response") def log_response(response): request = response.request print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}") client = httpx2.Client(event_hooks={'request': [log_request], 'response': [log_response]}) ``` -------------------------------- ### Run Documentation Site Locally Source: https://httpx2.pydantic.dev/contributing Build and serve the documentation site locally for previewing changes. Useful for verifying documentation updates. ```shell $ scripts/docs ``` -------------------------------- ### Send a GET Request with httpx2.get Source: https://httpx2.pydantic.dev/api A convenience function for sending GET requests. It omits parameters like `data`, `files`, and `json` as GET requests should not have a body. ```python 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 ``` -------------------------------- ### httpx2.get Source: https://httpx2.pydantic.dev/api Sends a GET request. This is a convenience function specifically for GET requests. ```APIDOC ## httpx2.get ### Description Sends a `GET` request. ### Method GET ### Endpoint N/A (function call) ### Parameters #### Path Parameters None #### Query Parameters - **params** (QueryParamTypes | None) - Optional - Query parameters to include in the URL, as a string, dictionary, or sequence of two-tuples. #### Request Body None (GET requests should not include a request body) #### Other Parameters - **url** (URL | str) - Required - URL for the new `Request` object. - **headers** (HeaderTypes | None) - Optional - Dictionary of HTTP headers to include in the request. - **cookies** (CookieTypes | None) - Optional - Dictionary of Cookie items to include in the request. - **auth** (AuthTypes | None) - Optional - An authentication class to use when sending the request. - **proxy** (ProxyTypes | None) - Optional - A proxy URL where all the traffic should be routed. - **follow_redirects** (bool) - Optional - Enables or disables HTTP redirects. Defaults to `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. Defaults to `True`. - **timeout** (TimeoutTypes) - Optional - The timeout configuration to use when sending the request. Defaults to `DEFAULT_TIMEOUT_CONFIG`. - **trust_env** (bool) - Optional - Enables or disables usage of environment variables for configuration. Defaults to `True`. ### Request Example ```python import httpx2 response = httpx2.get('https://httpbin.org/get') ``` ### Response #### Success Response (200) - **Response** (Response) - The `Response` object. ``` -------------------------------- ### Configure Client with Proxy Settings Source: https://httpx2.pydantic.dev/api Create a Proxy object and pass it to the Client constructor to configure proxy usage. ```python >>> proxy = Proxy("http://proxy.example.com:8030") >>> client = Client(proxy=proxy) ``` -------------------------------- ### Making Async Requests Source: https://httpx2.pydantic.dev/async Demonstrates how to instantiate and use an `AsyncClient` to make asynchronous HTTP requests using `async with`. ```APIDOC ## Making Async Requests To make asynchronous requests, you'll need an `AsyncClient`. ```python async with httpx2.AsyncClient() as client: r = await client.get('https://www.example.com/') r ``` **Output:** ``` ``` **Tip:** Use IPython or Python with `python -m asyncio` to try this code interactively, as they support executing `async`/`await` expressions in the console. ``` -------------------------------- ### httpx2.Client Initialization Source: https://httpx2.pydantic.dev/api Instantiate an httpx2.Client with various configuration options for making HTTP requests. ```APIDOC ## `Client` ### Description An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc. It can be shared between threads. ### Usage ```python >>> 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". ``` -------------------------------- ### Enable Redirects in HTTPX GET Request Source: https://httpx2.pydantic.dev/compatibility To enable redirects for a specific GET request in HTTPX, set `follow_redirects=True`. This differs from the default behavior of requests. ```python response = client.get(url, follow_redirects=True) ``` -------------------------------- ### Client Context Management Source: https://httpx2.pydantic.dev/async Shows how to use `AsyncClient` with an asynchronous context manager (`async with`) for automatic opening and closing. ```APIDOC ## Opening and closing clients Use `async with httpx2.AsyncClient()` if you want a context-managed client... ```python async with httpx2.AsyncClient() as client: ... ``` **Warning:** In order to get the most benefit from connection pooling, make sure you're not instantiating multiple client instances - for example by using `async with` inside a "hot loop". This can be achieved either by having a single scoped client that's passed throughout wherever it's needed, or by having a single global client instance. ``` -------------------------------- ### SSL Certificate Verification Error Example Source: https://httpx2.pydantic.dev/contributing This example demonstrates a common SSL certificate verification error that occurs when making HTTPS requests to a host not included in the generated SSL/TLS certificate. ```python ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'duckduckgo.com'. (_ssl.c:1108) ``` -------------------------------- ### HTTPX Client Instantiation Source: https://httpx2.pydantic.dev/compatibility This demonstrates the HTTPX equivalent of `requests.Session`, which is `httpx2.Client`. It accepts similar keyword arguments. ```python client = httpx2.Client(**kwargs) ``` -------------------------------- ### Using httpx2.Client as a Context Manager Source: https://httpx2.pydantic.dev/advanced/clients The recommended way to use a Client is as a context manager to ensure proper connection cleanup. ```python with httpx2.Client() as client: ... ``` -------------------------------- ### Instantiate httpx2 AsyncClient with HTTP/2 enabled Source: https://httpx2.pydantic.dev/http2 Enable HTTP/2 support when creating an `httpx2.AsyncClient` instance by setting `http2=True`. ```python client = httpx2.AsyncClient(http2=True) ``` -------------------------------- ### Configure Client with Default Truststore Source: https://httpx2.pydantic.dev/advanced/ssl Instantiates an httpx2 client using the default SSL context, which relies on the operating system's trust store via the 'truststore' package. ```python import ssl import truststore import httpx2 # This SSL context is equivalent to the default `verify=True`. cx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) client = httpx2.Client(verify=ctx) ``` -------------------------------- ### Configure Basic Logging for httpx2 Source: https://httpx2.pydantic.dev/logging Use `logging.basicConfig` to set up basic debug logging for httpx2. This will output detailed network behavior to stdout. ```python import logging import httpx2 logging.basicConfig( format="%(levelname)s [%(asctime)s] %(name)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.DEBUG ) httpx2.get("https://www.example.com") ``` -------------------------------- ### Apply configuration to all requests with httpx2 Client Source: https://httpx2.pydantic.dev/advanced/clients Configure the httpx2.Client with parameters like headers during instantiation to apply them to all subsequent requests made by that client instance. ```python >>> url = 'http://httpbin.org/headers' >>> headers = {'user-agent': 'my-app/0.0.1'} >>> with httpx2.Client(headers=headers) as client: ... r = client.get(url) ... ``` ```python >>> r.json()['headers']['User-Agent'] 'my-app/0.0.1' ``` -------------------------------- ### Configure Client with Client-Side Certificate Source: https://httpx2.pydantic.dev/advanced/ssl Shows how to configure an SSL context to load a client-side certificate chain, optionally specifying a key file and password, for mutual TLS authentication. ```python ctx = ssl.create_default_context() ctx.load_cert_chain(certfile="path/to/client.pem") # Optionally also keyfile or password. client = httpx2.Client(verify=ctx) ``` -------------------------------- ### Configure SOCKS Proxy Client Source: https://httpx2.pydantic.dev/advanced/proxies Initialize an HTTPX client to use a SOCKS proxy, optionally including authentication credentials. ```python httpx2.Client(proxy='socks5://user:pass@host:port') ``` -------------------------------- ### Configure Client with Alternative Certificate Store Source: https://httpx2.pydantic.dev/advanced/ssl Demonstrates configuring an httpx2 client with an explicitly specified certificate verification store using the standard SSL context API. ```python import httpx2 import ssl # Use an explicitly configured certificate store. cx = ssl.create_default_context(cafile="path/to/certs.pem") # Either cafile or capath. client = httpx2.Client(verify=ctx) ``` -------------------------------- ### Other HTTP Request Methods Source: https://httpx2.pydantic.dev/quickstart HTTPX2 supports PUT, DELETE, HEAD, and OPTIONS requests, following a similar pattern to GET and POST. ```python >>> r = httpx2.put('https://httpbin.org/put', data={'key': 'value'}) ``` ```python >>> r = httpx2.delete('https://httpbin.org/delete') ``` ```python >>> r = httpx2.head('https://httpbin.org/get') ``` ```python >>> r = httpx2.options('https://httpbin.org/get') ``` -------------------------------- ### Use httpx2 AsyncClient with HTTP/2 as a context manager Source: https://httpx2.pydantic.dev/http2 Instantiate an `httpx2.AsyncClient` with HTTP/2 enabled within an `async with` block to ensure connections are properly managed and closed. ```python async with httpx2.AsyncClient(http2=True) as client: ... ``` -------------------------------- ### Build and Send a Request Source: https://httpx2.pydantic.dev/api Builds a request using provided parameters and client configuration, then sends it. This is equivalent to building a request separately and then sending it. ```python 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 ``` -------------------------------- ### Requests Session Instantiation Source: https://httpx2.pydantic.dev/compatibility This shows how to instantiate a `requests.Session` object, which is the equivalent of `httpx2.Client` in HTTPX. ```python session = requests.Session(**kwargs) ``` -------------------------------- ### Disabling Proxy with NO_PROXY Source: https://httpx2.pydantic.dev/environment_variables Use the `NO_PROXY` environment variable to exclude specific URLs from proxying. This example sets a global proxy and then bypasses it for local and specific domain requests. ```bash export HTTP_PROXY=http://my-external-proxy.com:1234 export NO_PROXY=http://127.0.0.1,python-httpx2.org ``` ```python import httpx2; httpx2.get('http://example.com') ``` ```python import httpx2; httpx2.get('http://127.0.0.1:5000/my-api') ``` ```python import httpx2; httpx2.get('https://httpx2.pydantic.dev') ``` -------------------------------- ### Register Response Hook to Raise HTTPStatusError Source: https://httpx2.pydantic.dev/advanced/event-hooks Installs a response hook that automatically raises an httpx2.HTTPStatusError for 4xx and 5xx responses. This is useful for ensuring that non-successful status codes are treated as exceptions. ```python def raise_on_4xx_5xx(response): response.raise_for_status() client = httpx2.Client(event_hooks={'response': [raise_on_4xx_5xx]}) ``` -------------------------------- ### Construct Server-wide OPTIONS * Request Source: https://httpx2.pydantic.dev/advanced/extensions Utilize the 'target' extension to construct server-wide OPTIONS * requests. This is typically used for proxy requests. ```python # This will send the following request... # # CONNECT * HTTP/1.1 extensions = {"target": b"*"} response = httpx2.request("CONNECT", "https://www.example.com", extensions=extensions) ``` -------------------------------- ### Connect via Unix Domain Socket (UDS) Source: https://httpx2.pydantic.dev/advanced/transports Use the `uds` option in HTTPTransport to connect to services via a Unix Domain Socket, such as the Docker API. This example demonstrates connecting to the Docker daemon. ```python >>> import httpx2 >>> # Connect to the Docker API via a Unix Socket. >>> transport = httpx2.HTTPTransport(uds="/var/run/docker.sock") >>> client = httpx2.Client(transport=transport) >>> response = client.get("http://docker/info") >>> response.json() {"ID": "...", "Containers": 4, "Images": 74, ...} ``` -------------------------------- ### Route HTTP and HTTPS to Different Proxies Source: https://httpx2.pydantic.dev/advanced/proxies Use a dictionary of mounts to route HTTP and HTTPS requests to distinct proxy servers. ```python proxy_mounts = { "http://": httpx2.HTTPTransport(proxy="http://localhost:8030"), "https://": httpx2.HTTPTransport(proxy="http://localhost:8031"), } with httpx2.Client(mounts=proxy_mounts) as client: ... ``` -------------------------------- ### Client.options Source: https://httpx2.pydantic.dev/api Send an OPTIONS request to the specified URL with optional parameters for query, headers, cookies, authentication, redirects, and timeout. ```APIDOC ## `options` ### Description Send an `OPTIONS` request. ### Method Signature ```python 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 ``` **Parameters** : See `httpx2.request`. ``` -------------------------------- ### Cookies Object Source: https://httpx2.pydantic.dev/api A dictionary-like object for storing and managing cookies. It supports setting, getting, deleting, and clearing cookies, with options for domain and path specificity. It also provides methods for extracting cookies from responses and setting the cookie header for requests. ```APIDOC ## Cookies _A dict-like cookie store._ ### Initialization * `def __init__(cookies: [dict, Cookies, CookieJar])` ### Attributes * `.jar` - **CookieJar** ### Methods * `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_ ``` -------------------------------- ### Monitor Download Progress with tqdm Source: https://httpx2.pydantic.dev/advanced/clients Stream response content and use `response.num_bytes_downloaded` with the `tqdm` library to display a progress bar during downloads. This accounts for potential HTTP compression. ```python import tempfile import httpx2 from tqdm import tqdm with tempfile.NamedTemporaryFile() as download_file: url = "https://speed.hetzner.de/100MB.bin" with httpx2.stream("GET", url) as response: total = int(response.headers["Content-Length"]) with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit="B") as progress: num_bytes_downloaded = response.num_bytes_downloaded for chunk in response.iter_bytes(): download_file.write(chunk) progress.update(response.num_bytes_downloaded - num_bytes_downloaded) num_bytes_downloaded = response.num_bytes_downloaded ``` -------------------------------- ### Managing Cookies with httpx2.Cookies Instance Source: https://httpx2.pydantic.dev/quickstart Illustrates using the `httpx2.Cookies` instance to manage cookies, including setting domain-specific cookies. This provides more control over cookie scope. ```python >>> cookies = httpx2.Cookies() >>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org') >>> cookies.set('cookie_off_domain', 'nope.', domain='example.org') >>> r = httpx2.get('http://httpbin.org/cookies', cookies=cookies) >>> r.json() {'cookies': {'cookie_on_domain': 'hello, there!'}} ``` -------------------------------- ### Configure NetRC Authentication with Default Path Source: https://httpx2.pydantic.dev/advanced/authentication Use the default .netrc file located in the user's home directory for authentication. This is the simplest way to enable NetRC authentication. ```python >>> auth = httpx2.NetRCAuth() >>> client = httpx2.Client(auth=auth) ``` -------------------------------- ### AsyncClient Initialization Source: https://httpx2.pydantic.dev/api Initializes an asynchronous HTTP client. The client can be shared between tasks and supports features like connection pooling, HTTP/2, redirects, and cookie persistence. It can be used as an async context manager. ```APIDOC ## httpx2.AsyncClient ### Description An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc. It can be shared between tasks. ### Usage ```python 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". ``` -------------------------------- ### Configure HTTPX Client with Development Proxy and Custom CA Source: https://httpx2.pydantic.dev/contributing Use this snippet to configure the httpx client to use a local development proxy and a custom CA certificate for SSL verification. Ensure the CA file path is correct. ```python ctx = ssl.create_default_context(cafile="/path/to/client.pem") client = httpx2.Client(proxy="http://127.0.0.1:8080/", verify=ctx) ``` -------------------------------- ### Make a POST Request Source: https://httpx2.pydantic.dev/quickstart Use httpx2.post() to send data to a URL. The data is provided as a dictionary. ```python >>> r = httpx2.post('https://httpbin.org/post', data={'key': 'value'}) ``` -------------------------------- ### Enable Redirects by Default in HTTPX Client Source: https://httpx2.pydantic.dev/compatibility Instantiate an `httpx2.Client` with `follow_redirects=True` to enable automatic redirect following for all requests made by that client instance. ```python client = httpx2.Client(follow_redirects=True) ``` -------------------------------- ### Routing HTTP and HTTPS Through Different Proxies Source: https://httpx2.pydantic.dev/advanced/transports Set up distinct proxy servers for HTTP and HTTPS traffic by defining separate mounts for each scheme. ```python mounts = { "http://": httpx2.HTTPTransport(proxy="http://localhost:8030"), "https://": httpx2.HTTPTransport(proxy="http://localhost:8031"), } ``` -------------------------------- ### Constructing an HTTP Request Source: https://httpx2.pydantic.dev/api Demonstrates how to explicitly construct an httpx2.Request object for more control over outgoing requests. This is useful when you need to define specific headers or other request details. ```python >>> request = httpx2.Request("GET", "https://example.org", headers={'host': 'example.org'}) >>> response = client.send(request) ``` -------------------------------- ### Client.request Source: https://httpx2.pydantic.dev/api Build and send a request with custom method, URL, and various optional parameters for content, headers, authentication, and more. ```APIDOC ## `request` ### Description 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 for how the various parameters are merged with client-level configuration. ### Method Signature ```python 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 ``` ``` -------------------------------- ### Configure Client with Base URL Source: https://httpx2.pydantic.dev/advanced/clients Use `base_url` to prepend a URL to all outgoing requests made by the client. This is useful for setting a common domain for multiple requests. ```python with httpx2.Client(base_url='http://httpbin.org') as client: r = client.get('/headers') r.request.url ``` -------------------------------- ### Explicit Transport Instances Source: https://httpx2.pydantic.dev/async Shows how to use `httpx2.AsyncHTTPTransport` when instantiating a transport instance directly with an `AsyncClient`. ```APIDOC ### Explicit transport instances When instantiating a transport instance directly, you need to use `httpx2.AsyncHTTPTransport`. For instance: ```python >>> import httpx2 >>> transport = httpx2.AsyncHTTPTransport(retries=1) >>> async with httpx2.AsyncClient(transport=transport) as client: >>> ... ``` ``` -------------------------------- ### Configure Client with Certifi CA Bundle Source: https://httpx2.pydantic.dev/advanced/ssl Configures an httpx2 client to use the certifi package's CA bundle for SSL verification instead of the system's trust store. ```python import certifi import httpx2 import ssl # Use the certifi CA bundle. cx = ssl.create_default_context(cafile=certifi.where()) client = httpx2.Client(verify=ctx) ``` -------------------------------- ### Adding Support for Custom Schemes Source: https://httpx2.pydantic.dev/advanced/transports Extend HTTPX2 to support custom URL schemes like 'file://' by mounting a custom transport. ```python # Support URLs like "file:///Users/sylvia_green/websites/new_client/index.html" mounts = {"file://": FileSystemTransport()} client = httpx2.Client(mounts=mounts) ``` -------------------------------- ### Configure NetRC Authentication with NETRC Environment Variable Source: https://httpx2.pydantic.dev/advanced/authentication Configure the path to the .netrc file using the NETRC environment variable. This allows dynamic configuration without changing the code. ```python >>> auth = httpx2.NetRCAuth(file=os.environ.get("NETRC")) >>> client = httpx2.Client(auth=auth) ``` -------------------------------- ### Explicitly Following Redirects Source: https://httpx2.pydantic.dev/quickstart Shows how to explicitly enable redirection following using the `follow_redirects=True` parameter. This is useful when you want the client to automatically handle redirects. ```python >>> r = httpx2.get('http://github.com/', follow_redirects=True) >>> r.url URL('https://github.com/') >>> r.status_code 200 >>> r.history [] ``` -------------------------------- ### Build Request Source: https://httpx2.pydantic.dev/api 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: Request instances. ```python 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 ```