### Send a GET request with HTTPCore 2 Source: https://pydantic.dev/docs/httpx2/httpcore2 Example of sending a GET request to example.com and printing the response status, headers, and content. ```python import httpcore2 response = httpcore2.request("GET", "https://www.example.com/") print(response) # print(response.status) # 200 print(response.headers) # [(b'Accept-Ranges', b'bytes'), (b'Age', b'557328'), (b'Cache-Control', b'max-age=604800'), ...] print(response.content) # b'\n\n\nExample Domain\n\n\n ...' ``` -------------------------------- ### AsyncIO example: using httpx2.AsyncClient Source: https://pydantic.dev/docs/httpx2/guides/async Shows how to use HTTPX with the asyncio backend. The example creates an AsyncClient and makes a GET request to https://www.example.com/. ```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()) ``` -------------------------------- ### Trio example: using httpx2.AsyncClient Source: https://pydantic.dev/docs/httpx2/guides/async Shows how to use HTTPX with the trio backend. The trio package must be installed to use this backend. ```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) ``` -------------------------------- ### Client usage example Source: https://pydantic.dev/docs/httpx2/api/api Shows basic usage of the Client class: creating a client and sending a GET request. The client supports connection pooling, HTTP/2, redirects, and cookie persistence. ```python >>> client = httpx2.Client()>>> response = client.get('https://example.org') ``` -------------------------------- ### Install project dependencies Source: https://pydantic.dev/docs/httpx2/community/contributing Installs the project and its dependencies after cloning. Run from the repository root. ```bash $ cd httpx2 $ scripts/install ``` -------------------------------- ### AsyncClient usage example Source: https://pydantic.dev/docs/httpx2/api/api Creates an AsyncClient using an async context manager and sends a GET request to example.org. ```python >>> async with httpx2.AsyncClient() as client: >>> response = await client.get('https://example.org') ``` -------------------------------- ### httpcore2.request() usage example Source: https://pydantic.dev/docs/httpx2/httpcore2/quickstart Example of sending a GET request to https://www.example.com/ using httpcore2.request(). ```python response = httpcore2.request("GET", "https://www.example.com/") ``` -------------------------------- ### Simplified proxy setup with httpx2.Client Source: https://pydantic.dev/docs/httpx2/guides/troubleshooting Simplified proxy setup using a single proxy string with httpx2.Client. ```python proxy = "http://myproxy.org"with httpx2.Client(proxy=proxy) as client: ... ``` -------------------------------- ### Install trio support Source: https://pydantic.dev/docs/httpx2/httpcore2/async Install the optional dependencies for using HTTPCore2 with the trio package. ```bash pip install 'httpcore2[trio]' ``` -------------------------------- ### Live browser example: httpx2.get with document.location.origin Source: https://pydantic.dev/docs/httpx2/advanced/emscripten Interactive example that runs in the browser via Pyodide. It imports httpx2, uses document.location.origin to make a GET request, and prints the status code and first 50 characters of the response. The code is editable and can be re-run to test different addresses. ```python import httpx2 from js import document print("Sending request using httpx2 in the browser:") print("--------------------------------------------") r = httpx2.get(document.location.origin) print("Status = ", r.status_code) print("Response = ", r.text[:50], "...") ``` -------------------------------- ### Install httpx2 with HTTP/2 support Source: https://pydantic.dev/docs/httpx2/get-started Installs httpx2 with optional HTTP/2 support. ```bash pip install 'httpx2[http2]' ``` -------------------------------- ### Install asyncio support Source: https://pydantic.dev/docs/httpx2/httpcore2/async Install the optional dependencies for using HTTPCore2 with Python's asyncio. ```bash pip install 'httpcore2[asyncio]' ``` -------------------------------- ### Run documentation site locally with scripts/docs Source: https://pydantic.dev/docs/httpx2/community/contributing Starts the local documentation site for previewing changes. ```terminal $ scripts/docs ``` -------------------------------- ### Install httpx2 CLI extra Source: https://pydantic.dev/docs/httpx2/get-started Installs the optional command-line client dependency for httpx2. ```bash pip install 'httpx2[cli]' ``` -------------------------------- ### request usage example Source: https://pydantic.dev/docs/httpx2/api/api Shows how to use `httpx2.request` to send a GET request to https://httpbin.org/get and print the response. The output is ``. ```python >>> import httpx2>>> response = httpx2.request('GET', 'https://httpbin.org/get')>>> response ``` -------------------------------- ### Install HTTPCore 2 for HTTP/1.1 support Source: https://pydantic.dev/docs/httpx2/httpcore2 Install the base package for HTTP/1.1 only support. ```bash pip install httpcore2 ``` -------------------------------- ### Install HTTPCore 2 with HTTP/2 support Source: https://pydantic.dev/docs/httpx2/httpcore2 Install the package with the 'http2' extra to enable HTTP/2 support. ```bash pip install 'httpcore2[http2]' ``` -------------------------------- ### AnyIO example: using httpx2.AsyncClient Source: https://pydantic.dev/docs/httpx2/guides/async Shows how to use HTTPX with the anyio backend, which defaults to asyncio but can be set to trio via the backend parameter. The example explicitly uses backend='trio'. ```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') ``` -------------------------------- ### Proxy Configuration Example Source: https://pydantic.dev/docs/httpx2/api/api Creates a Proxy instance and passes it to a Client. The URL is required; optional ssl_context, auth, and headers can be provided. ```python >>> proxy = Proxy("http://proxy.example.com:8030") >>> client = Client(proxy=proxy) ``` -------------------------------- ### Configure logging and make a request Source: https://pydantic.dev/docs/httpx2/httpcore2/logging Sets up basic logging with a custom format and debug level, then makes a GET request to https://www.example.com to trigger debug output. ```python import logging import httpcore2 logging.basicConfig( format="%(levelname)s [%(asctime)s] %(name)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.DEBUG ) httpcore2.request('GET', 'https://www.example.com') ``` -------------------------------- ### Install WebSocket support with pip install 'httpx2[ws]' Source: https://pydantic.dev/docs/httpx2/guides/websockets Install the optional wsproto dependency required for WebSocket support in HTTPX. ```terminal pip install 'httpx2[ws]' ``` -------------------------------- ### Install httpx2 with pip Source: https://pydantic.dev/docs/httpx2/get-started Installs the httpx2 package using pip. ```bash pip install httpx2 ``` -------------------------------- ### Install SOCKS support Source: https://pydantic.dev/docs/httpx2/advanced/proxies Installs the optional SOCKS support for HTTPX using pip. ```bash pip install 'httpx2[socks]' ``` -------------------------------- ### Install httpx2 HTTP/2 dependencies Source: https://pydantic.dev/docs/httpx2/guides/http2 Install the optional HTTP/2 dependencies for httpx2 before enabling HTTP/2 support. ```bash pip install 'httpx2[http2]' ``` -------------------------------- ### Install HTTPCore 2 with SOCKS proxy support Source: https://pydantic.dev/docs/httpx2/httpcore2 Install the package with the 'socks' extra to enable SOCKS proxy support. ```bash pip install 'httpcore2[socks]' ``` -------------------------------- ### Install httpx2 and chardet for auto-detection Source: https://pydantic.dev/docs/httpx2/advanced/text-encodings Shows the pip commands to install httpx2 and chardet before configuring a client with character-set auto-detection. ```bash pip install httpx2 pip install chardet ``` -------------------------------- ### Install httpx2 with brotli and zstd extras Source: https://pydantic.dev/docs/httpx2/get-started Installs httpx2 with optional brotli and zstandard decoder support. ```bash pip install 'httpx2[brotli,zstd]' ``` -------------------------------- ### Make a GET request with httpx2 Source: https://pydantic.dev/docs/httpx2/get-started Demonstrates making a GET request with httpx2 and inspecting the response object, status code, headers, and text. ```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...' ``` -------------------------------- ### Basic GET request with httpx2.Client Source: https://pydantic.dev/docs/httpx2/advanced/clients Shows how to make a simple GET request using httpx2.Client and print the response. The response is a Response object with status 200 OK. ```python >>> with httpx2.Client() as client: ... r = client.get('https://example.com') >>> r ``` -------------------------------- ### Install httpcore2 with HTTP/2 dependencies Source: https://pydantic.dev/docs/httpx2/httpcore2/http2 Install the optional HTTP/2 dependencies for httpcore2 using pip. This is required before enabling HTTP/2 support. ```bash pip install 'httpcore2[http2]' ``` -------------------------------- ### Example of pool.connections output Source: https://pydantic.dev/docs/httpx2/httpcore2/connection-pools Shows an example of the connections attribute, which returns a list of HTTPConnection objects with their state and request counts. ```python >>> pool.connections[ , , ,] ``` -------------------------------- ### Example .netrc file Source: https://pydantic.dev/docs/httpx2/advanced/authentication Example .netrc file used with NetRCAuth. It maps hosts to credentials; when a request is made to a matching host, HTTP basic authentication is applied. ```text machine example.orglogin example-usernamepassword example-passwordmachine python-httpx2.orglogin other-usernamepassword other-password ``` -------------------------------- ### Open a WebSocket session with httpx2.AsyncClient() Source: https://pydantic.dev/docs/httpx2/guides/websockets Open a WebSocket session using the asynchronous client. Uses async with and await, mirroring the synchronous example. ```python >>> async with httpx2.AsyncClient() as client: ... async with client.websocket("wss://example.com/ws") as ws: ... await ws.send_text("Hello!") ... message = await ws.receive_text() ``` -------------------------------- ### Create a connection pool with HTTP/2 enabled Source: https://pydantic.dev/docs/httpx2/httpcore2/http2 Instantiate a ConnectionPool with http2=True to enable HTTP/2 support. This is the basic setup for using HTTP/2. ```python import httpcore2 pool = httpcore2.ConnectionPool(http2=True) ``` -------------------------------- ### Install a trace callback with the "trace" extension Source: https://pydantic.dev/docs/httpx2/httpcore2/extensions The "trace" extension installs a callback handler to monitor internal events. The handler receives event_name and info arguments. When using the async variant, the handler must be an async def function. The exact trace events may change across versions, so pin the package version if relying on them. ```python import httpcore2 def log(event_name, info): print(event_name, info) r = httpcore2.request("GET", "https://www.example.com/", extensions={"trace": log}) # connection.connect_tcp.started {'host': 'www.example.com', 'port': 443, 'local_address': None, 'timeout': None} # connection.connect_tcp.complete {'return_value': } # connection.start_tls.started {'ssl_context': , 'server_hostname': b'www.example.com', 'timeout': None} # connection.start_tls.complete {'return_value': } # http11.send_request_headers.started {'request': } # http11.send_request_headers.complete {'return_value': None} # http11.send_request_body.started {'request': } # http11.send_request_body.complete {'return_value': None} # http11.receive_response_headers.started {'request': } # http11.receive_response_headers.complete {'return_value': (b'HTTP/1.1', 200, b'OK', [(b'Age', b'553715'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Thu, 21 Oct 2021 17:08:42 GMT'), (b'Etag', b'"3147526947+ident"'), (b'Expires', b'Thu, 28 Oct 2021 17:08:42 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECS (nyb/1DCD)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'1256')]}) # http11.receive_response_body.started {'request': } # http11.receive_response_body.complete {'return_value': None} # http11.response_closed.started {} # http11.response_closed.complete {'return_value': None} ``` -------------------------------- ### Make PUT, DELETE, HEAD, and OPTIONS requests Source: https://pydantic.dev/docs/httpx2/get-started/quickstart Make PUT, DELETE, HEAD, and OPTIONS requests, all following the same style as GET and POST. ```python >>> r = httpx2.put('https://httpbin.org/put', data={'key': 'value'}) >>> r = httpx2.delete('https://httpbin.org/delete') >>> r = httpx2.head('https://httpbin.org/get') >>> r = httpx2.options('https://httpbin.org/get') ``` -------------------------------- ### Run proxy.py test proxy Source: https://pydantic.dev/docs/httpx2/httpcore2/proxies Install and run the proxy.py tool to test httpcore2 proxy support. The proxy listens on 127.0.0.1:8080. ```terminal pip install proxy.py proxy --hostname 127.0.0.1 --port 8080 ``` -------------------------------- ### Example debug output Source: https://pydantic.dev/docs/httpx2/httpcore2/logging Shows the debug level output sent to the console when the above configuration is used. The exact formatting may change across versions. ```text DEBUG [2023-01-09 14:44:00] httpcore2.connection - connect_tcp.started host='www.example.com' port=443 local_address=None timeout=None DEBUG [2023-01-09 14:44:00] httpcore2.connection - connect_tcp.complete return_value= DEBUG [2023-01-09 14:44:00] httpcore2.connection - start_tls.started ssl_context= server_hostname='www.example.com' timeout=None DEBUG [2023-01-09 14:44:00] httpcore2.connection - start_tls.complete return_value= DEBUG [2023-01-09 14:44:00] httpcore2.http11 - send_request_headers.started request= DEBUG [2023-01-09 14:44:00] httpcore2.http11 - send_request_headers.complete DEBUG [2023-01-09 14:44:00] httpcore2.http11 - send_request_body.started request= DEBUG [2023-01-09 14:44:00] httpcore2.http11 - send_request_body.complete DEBUG [2023-01-09 14:44:00] httpcore2.http11 - receive_response_headers.started request= DEBUG [2023-01-09 14:44:00] httpcore2.http11 - receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Age', b'572646'), (b'Cache-Control', b'max-age=604800'), (b'Content-Type', b'text/html; charset=UTF-8'), (b'Date', b'Mon, 09 Jan 2023 14:44:00 GMT'), (b'Etag', b'"3147526947+ident"'), (b'Expires', b'Mon, 16 Jan 2023 14:44:00 GMT'), (b'Last-Modified', b'Thu, 17 Oct 2019 07:18:26 GMT'), (b'Server', b'ECS (nyb/1D18)'), (b'Vary', b'Accept-Encoding'), (b'X-Cache', b'HIT'), (b'Content-Length', b'1256')]) DEBUG [2023-01-09 14:44:00] httpcore2.http11 - receive_response_body.started request= DEBUG [2023-01-09 14:44:00] httpcore2.http11 - receive_response_body.complete DEBUG [2023-01-09 14:44:00] httpcore2.http11 - response_closed.started DEBUG [2023-01-09 14:44:00] httpcore2.http11 - response_closed.complete DEBUG [2023-01-09 14:44:00] httpcore2.connection - close.started DEBUG [2023-01-09 14:44:00] httpcore2.connection - close.complete ``` -------------------------------- ### httpcore2.stream() usage example Source: https://pydantic.dev/docs/httpx2/httpcore2/quickstart Example of using httpcore2.stream() as a context manager to send a GET request. The response body is not automatically read; use response.read() or iterate with response.iter_content(). ```python with httpcore2.stream("GET", "https://www.example.com/") as response: ... ``` -------------------------------- ### Set base_url on Client Source: https://pydantic.dev/docs/httpx2/advanced/clients Configures a Client with a base_url to prepend to all outgoing requests. The example shows a GET request to '/headers' resolving to 'http://httpbin.org/headers'. ```python >>> with httpx2.Client(base_url='http://httpbin.org') as client:... r = client.get('/headers')...>>> r.request.url URL('http://httpbin.org/headers') ``` -------------------------------- ### Get SSL object from network stream Source: https://pydantic.dev/docs/httpx2/advanced/extensions Accesses the SSL object from the network stream extension while the connection is open. The underlying connection must remain open to retrieve the ssl_object, and the example prints the TLS version. ```python with httpx2.stream("GET", "https://www.example.com") as response: network_stream = response.extensions["network_stream"] ssl_object = network_stream.get_extra_info("ssl_object") print("TLS version", ssl_object.version()) ``` -------------------------------- ### Implementing a custom network backend for recording Source: https://pydantic.dev/docs/httpx2/httpcore2/network-backends Demonstrates creating a custom NetworkBackend and NetworkStream to record raw network traffic to a file. ```python import httpcore2 class RecordingNetworkStream(httpcore2.NetworkStream): def __init__(self, record_file, stream): self.record_file = record_file self.stream = stream def read(self, max_bytes, timeout=None): data = self.stream.read(max_bytes, timeout=timeout) self.record_file.write(data) return data def write(self, buffer, timeout=None): self.stream.write(buffer, timeout=timeout) def close(self) -> None: self.stream.close() def start_tls( self, ssl_context, server_hostname=None, timeout=None, ): self.stream = self.stream.start_tls( ssl_context, server_hostname=server_hostname, timeout=timeout ) return self def get_extra_info(self, info): return self.stream.get_extra_info(info) class RecordingNetworkBackend(httpcore2.NetworkBackend): """ A custom network backend that records network responses. """ def __init__(self, record_file): self.record_file = record_file self.backend = httpcore2.SyncBackend() def connect_tcp( self, host, port, timeout=None, local_address=None, socket_options=None, ): # Note that we're only using a single record file here, # so even if multiple connections are opened the network # traffic will all write to the same file. # An alternative implementation might automatically use # a new file for each opened connection. stream = self.backend.connect_tcp( host, port, timeout=timeout, local_address=local_address, socket_options=socket_options ) return RecordingNetworkStream(self.record_file, stream) # Once you make the request, the raw HTTP/1.1 response will be available # in the 'network-recording' file. # Try switching to `http2=True` to see the difference when recording HTTP/2 binary network traffic, # or add `headers={'Accept-Encoding': 'gzip'}` to see HTTP content compression. with open("network-recording", "wb") as record_file: network_backend = RecordingNetworkBackend(record_file) with httpcore2.ConnectionPool(network_backend=network_backend) as http: response = http.request("GET", "https://www.example.com/") print(response) ``` -------------------------------- ### get Source: https://pydantic.dev/docs/httpx2/api/api The `get` function sends a `GET` request. It is a helper function for testing HTTPX in a console or making a small number of requests. It does not support request body parameters. ```APIDOC ## `get` ### Description Sends a `GET` request. This is a helper function for 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. ### Signature ```python def get( url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: ssl.SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True, ) -> Response ``` ### Parameters - **url** (`URL` | `str`) - Required - URL for the new `Request` object. - **params** (`QueryParamTypes` | `None`) - Optional, default `None` - Query parameters to include in the URL, as a string, dictionary, or sequence of two-tuples. - **headers** (`HeaderTypes` | `None`) - Optional, default `None` - Dictionary of HTTP headers to include in the request. - **cookies** (`CookieTypes` | `None`) - Optional, default `None` - Dictionary of Cookie items to include in the request. - **auth** (`AuthTypes` | `None`) - Optional, default `None` - An authentication class to use when sending the request. - **proxy** (`ProxyTypes` | `None`) - Optional, default `None` - A proxy URL where all the traffic should be routed. - **follow_redirects** (`bool`) - Optional, default `False` - Enables or disables HTTP redirects. - **verify** (`ssl.SSLContext` | `str` | `bool`) - Optional, default `True` - 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. - **timeout** (`TimeoutTypes`) - Optional, default `DEFAULT_TIMEOUT_CONFIG` - The timeout configuration to use when sending the request. - **trust_env** (`bool`) - Optional, default `True` - Enables or disables usage of environment variables for configuration. Note: The `data`, `files`, `json` and `content` parameters are not available on this function, as `GET` requests should not include a request body. ### Returns - `Response` ``` -------------------------------- ### Show httpx2 CLI help Source: https://pydantic.dev/docs/httpx2/get-started Displays help for the httpx2 command-line client. ```bash httpx2 --help ``` -------------------------------- ### Domain routing with subdomains Source: https://pydantic.dev/docs/httpx2/advanced/transports Proxy all requests to 'example.com' and its subdomains using the pattern 'all://*example.com', letting other requests pass through. ```python mounts = { "all://*example.com": httpx2.HTTPTransport(proxy="http://localhost:8030"), } ``` -------------------------------- ### Domain routing for example.com Source: https://pydantic.dev/docs/httpx2/advanced/transports Proxy all requests on domain 'example.com' using the pattern 'all://example.com', letting other requests pass through. ```python mounts = { "all://example.com": httpx2.HTTPTransport(proxy="http://localhost:8030"), } ``` -------------------------------- ### Client.get method signature Source: https://pydantic.dev/docs/httpx2/api/api Defines the get method for sending a GET request. Parameters are merged with client-level configuration. ```python def 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 ``` -------------------------------- ### Establish a WebSocket connection Source: https://pydantic.dev/docs/httpx2/guides/websockets Demonstrates how to connect to a WebSocket server and handle disconnection using the WebSocketDisconnect exception. ```python >>> from httpx2.websockets import WebSocketDisconnect>>> with client.websocket("wss://example.com/ws") as ws:... try:... message = ws.receive_text()... except WebSocketDisconnect as exc:... print(f"Connection closed: {exc.code} {exc.reason}") ``` -------------------------------- ### List packages depending on httpx Source: https://pydantic.dev/docs/httpx2/get-started/migration Installs pipdeptree and then lists installed packages that depend on httpx, showing which dependencies still require it. ```bash pip install pipdeptree pipdeptree --reverse --packages httpx ``` -------------------------------- ### Create HTTPX client with redirect following enabled Source: https://pydantic.dev/docs/httpx2/guides/compatibility Create an HTTPX client with redirect following enabled by default for all requests made through that client. ```python client = httpx2.Client(follow_redirects=True) ``` -------------------------------- ### GET request with custom headers using httpx2.Client Source: https://pydantic.dev/docs/httpx2/advanced/clients Demonstrates sending a request with custom headers via the client. The headers are passed to the get method and can be accessed from the request object. ```python >>> with httpx2.Client() as client: ... headers = {'X-Custom': 'value'} ... r = client.get('https://example.com', headers=headers) >>> r.request.headers['X-Custom'] 'value' ``` -------------------------------- ### websocket method signature and usage example Source: https://pydantic.dev/docs/httpx2/api/api Opens a WebSocket session using the client's configuration. The session is closed automatically when exiting the context manager. The example shows sending a text message and receiving a response. ```python def 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] ``` ```python 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() ``` -------------------------------- ### AsyncClient.get Source: https://pydantic.dev/docs/httpx2/api/api Send a GET request to the specified URL. ```APIDOC ## AsyncClient.get ### Description Send a `GET` request. Parameters are the same as `httpx2.request`. ### Method Async method ### Signature ``` def 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 - **url** (URL | str) - Required - Request URL. - **params** (QueryParamTypes | None) - Optional - Query parameters. - **headers** (HeaderTypes | None) - Optional - HTTP headers. - **cookies** (CookieTypes | None) - Optional - Cookies. - **auth** (AuthTypes | UseClientDefault | None) - Optional - Authentication class. - **follow_redirects** (bool | UseClientDefault) - Optional - Whether to follow redirects. - **timeout** (TimeoutTypes | UseClientDefault) - Optional - Timeout configuration. - **extensions** (RequestExtensions | None) - Optional - Request extensions. ### Returns `Response` ``` -------------------------------- ### Client.get Source: https://pydantic.dev/docs/httpx2/api/api Sends a GET request to the specified URL. ```APIDOC ## [GET] Client.get ### Description Send a `GET` request. ### Method GET ### Endpoint `Client.get(url, *, params, headers, cookies, auth, follow_redirects, timeout, extensions)` ### Parameters #### Path Parameters - **url** (URL | str) - Required - Request URL. #### Query Parameters - **params** (QueryParamTypes | None) - Optional - Query parameters to include in the URL. #### Request Headers - **headers** (HeaderTypes | None) - Optional - HTTP headers to include. #### Request Cookies - **cookies** (CookieTypes | None) - Optional - Cookie values to include. #### Request Body - **auth** (AuthTypes | UseClientDefault | None) - Optional - Authentication class. Defaults to `USE_CLIENT_DEFAULT`. - **follow_redirects** (bool | UseClientDefault) - Optional - Whether 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. ### Response #### Success Response (200) - **Response** - The response object. #### Response Example ```python response = client.get('https://example.org') ``` ``` -------------------------------- ### Domain routing for HTTP on example.com Source: https://pydantic.dev/docs/httpx2/advanced/transports Proxy HTTP requests on domain 'example.com' using the pattern 'http://example.com', letting HTTPS and other requests pass through. ```python mounts = { "http://example.com": httpx2.HTTPTransport(proxy="http://localhost:8030"), } ``` -------------------------------- ### Making an async GET request with AsyncClient Source: https://pydantic.dev/docs/httpx2/guides/async Shows how to make an asynchronous GET request using an AsyncClient context manager. The response is awaited and the result is a Response object with status 200. Use IPython or `python -m asyncio` to run this interactively. ```python >>> async with httpx2.AsyncClient() as client: ... r = await client.get('https://www.example.com/') ... >>> r ``` -------------------------------- ### get function signature Source: https://pydantic.dev/docs/httpx2/api/api Defines the `httpx2.get` function that sends a GET request. It accepts url and optional parameters like params, headers, cookies, auth, proxy, follow_redirects, verify, timeout, and trust_env. Note that `data`, `files`, `json`, and `content` parameters are not available on this function. ```python def get( url: URL | str, *, params: QueryParamTypes | None = None, headers: HeaderTypes | None = None, cookies: CookieTypes | None = None, auth: AuthTypes | None = None, proxy: ProxyTypes | None = None, follow_redirects: bool = False, verify: ssl.SSLContext | str | bool = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True,) -> Response ``` -------------------------------- ### BasicAuth with httpbin.org returning 200 OK Source: https://pydantic.dev/docs/httpx2/advanced/authentication Basic authentication example using httpbin.org. The response is 200 OK when the credentials match. Basic auth is unencrypted and should typically 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 ``` -------------------------------- ### Accessing AsyncConnectionPool.connections Source: https://pydantic.dev/docs/httpx2/httpcore2/async Example showing how to retrieve the list of active and idle connections currently managed by the pool. ```python >>> pool.connections[ , , ,] ``` -------------------------------- ### Use httpx2 and httpx side by side Source: https://pydantic.dev/docs/httpx2/get-started/migration Shows how to use httpx2 for your own code while passing httpx objects to dependencies that still expect httpx, because the two packages' classes are distinct. ```python import httpx import httpx2 import some_library_still_on_httpx # Your own code: httpx2. client = httpx2.AsyncClient() # A dependency that expects httpx: give it httpx. some_library_still_on_httpx.configure(http_client=httpx.AsyncClient()) ``` -------------------------------- ### Coverage threshold not reached message Source: https://pydantic.dev/docs/httpx2/community/contributing Example of a message shown when tests pass but coverage is below the required threshold. ```text FAIL Required test coverage of 100% not reached. Total coverage: 99.00% ``` -------------------------------- ### Coverage failure message Source: https://pydantic.dev/docs/httpx2/community/contributing Example of a test failure message shown in the coverage report when tests fail. ```text === 1 failed, 435 passed, 1 skipped, 1 xfailed in 11.09s === ```