### Import and Basic GET Request with HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Demonstrates how to import the HTTPX library and make a basic GET request to retrieve a webpage. It shows the response object received. ```python >>> import httpx >>> r = httpx.get('https://httpbin.org/get') >>> r ``` -------------------------------- ### Authentication Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Explains how to implement Basic and Digest HTTP authentication using HTTPX. ```APIDOC ## Authentication ### Description Describes how to perform Basic and Digest HTTP authentication with the HTTPX library. Includes examples for both authentication schemes. ### Methods - `httpx.get(url, auth=(username, password))`: Performs Basic Authentication. - `httpx.get(url, auth=DigestAuth(username, password))`: Performs Digest Authentication. ### Request Example (Basic Authentication) ```python import httpx r = httpx.get("https://example.com", auth=("my_user", "password123")) print(r.status_code) ``` ### Request Example (Digest Authentication) ```python import httpx auth = httpx.DigestAuth("my_user", "password123") r = httpx.get("https://example.com", auth=auth) print(r.status_code) # Output: ``` ### Parameters - `auth` (tuple or DigestAuth): Credentials for authentication. For Basic Auth, a tuple of (username, password). For Digest Auth, an instance of `httpx.DigestAuth`. ``` -------------------------------- ### Other HTTP Methods (PUT, DELETE, HEAD, OPTIONS) with HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Illustrates how to make HTTP requests using PUT, DELETE, HEAD, and OPTIONS methods with the HTTPX library, following a similar pattern to GET and POST. ```python >>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'}) >>> r = httpx.delete('https://httpbin.org/delete') >>> r = httpx.head('https://httpbin.org/get') >>> r = httpx.options('https://httpbin.org/get') ``` -------------------------------- ### HTTP POST Request with HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Shows how to perform an HTTP POST request using the HTTPX library, including sending data in the request body. ```python >>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'}) ``` -------------------------------- ### Cookies Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Explains how to access cookies from responses and include cookies in outgoing requests using a dict-like `Cookies` instance. ```APIDOC ## Cookies ### Description Provides methods for accessing cookies set in HTTP responses and for including cookies in outgoing HTTP requests. Cookies are managed using a dict-like `Cookies` instance. ### Methods - `httpx.get(url, cookies=cookies_dict)`: Makes a GET request including specified cookies. - `r.cookies`: A `Cookies` instance containing cookies from the response. - `cookies.set(name, value, domain, path)`: Sets a cookie with specified attributes. ### Request Example (Setting and Accessing Cookies) ```python import httpx # Set a cookie in the response r = httpx.get('https://httpbin.org/cookies/set?chocolate=chip') print(r.cookies['chocolate']) # Output: chip # Include cookies in an outgoing request cookies_to_send = {"peanut": "butter"} r = httpx.get('https://httpbin.org/cookies', cookies=cookies_to_send) print(r.json()) # Output: {'cookies': {'peanut': 'butter'}} ``` ### Request Example (Using Cookies Instance) ```python import httpx cookies = httpx.Cookies() cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org') cookies.set('cookie_off_domain', 'nope.', domain='example.org') r = httpx.get('http://httpbin.org/cookies', cookies=cookies) print(r.json()) # Output: {'cookies': {'cookie_on_domain': 'hello, there!'}} ``` ### Response - `r.cookies`: A `httpx.Cookies` object, which behaves like a dictionary for accessing cookies by name. - `r.json()`: Parses the JSON response body. ``` -------------------------------- ### Implement HTTP Authentication with httpx Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Demonstrates how to use HTTPX for Basic and Digest HTTP authentication. It shows how to pass credentials as a tuple for Basic auth and how to instantiate `DigestAuth` for Digest auth. ```python >>> httpx.get("https://example.com", auth=("my_user", "password123")) ``` ```python >>> auth = httpx.DigestAuth("my_user", "password123") >>> httpx.get("https://example.com", auth=auth) ``` -------------------------------- ### Sending Custom Headers with HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Demonstrates how to include custom headers in an outgoing HTTP request using the `headers` keyword argument in HTTPX. ```python >>> url = 'https://httpbin.org/headers' >>> headers = {'user-agent': 'my-app/0.0.1'} >>> r = httpx.get(url, headers=headers) ``` -------------------------------- ### Timeouts Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Covers HTTPX's default timeout settings for network operations and how to configure or disable timeouts. ```APIDOC ## Timeouts ### Description Details HTTPX's default timeout configuration for network operations, ensuring requests do not hang indefinitely. Shows how to adjust the timeout value or disable it completely. ### Methods - `httpx.get(url, timeout=value)`: Makes a GET request with a specified timeout. - `httpx.get(url, timeout=None)`: Makes a GET request with timeouts disabled. ### Request Example (Custom Timeout) ```python import httpx try: httpx.get('https://github.com/', timeout=0.001) except httpx.TimeoutException as e: print(f"Request timed out: {e}") ``` ### Request Example (Disabling Timeout) ```python import httpx # This request will not time out r = httpx.get('https://github.com/', timeout=None) print(r.status_code) ``` ### Parameters - `timeout` (float or None): The timeout value in seconds. `None` disables timeouts. Defaults to 5 seconds for network inactivity. ``` -------------------------------- ### Handle Redirection with httpx Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Illustrates how HTTPX handles redirects by default and how to explicitly enable or disable redirection following using the `follow_redirects` parameter. It also shows how to inspect redirect history. ```python >>> r = httpx.get('http://github.com/') >>> r.status_code 301 >>> r.history [] >>> r.next_request ``` ```python >>> r = httpx.get('http://github.com/', follow_redirects=True) >>> r.url URL('https://github.com/') >>> r.status_code 200 >>> r.history [] ``` -------------------------------- ### Handling JSON Response Content with HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Illustrates how to parse JSON-encoded responses from APIs using the `.json()` method provided by HTTPX. ```python >>> r = httpx.get('https://api.github.com/events') >>> r.json() [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}] ``` -------------------------------- ### Access Response Headers with httpx Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Demonstrates how to access response headers using httpx. It shows the dictionary-like interface for headers and highlights that header access is case-insensitive. ```python >>> r.headers Headers({ 'content-encoding': 'gzip', 'transfer-encoding': 'chunked', 'connection': 'close', 'server': 'nginx/1.0.4', 'x-runtime': '148ms', 'etag': '"e1ca502697e5c9317743dc078f67693f"', 'content-type': 'application/json' }) ``` ```python >>> r.headers['Content-Type'] 'application/json' ``` ```python >>> r.headers.get('content-type') 'application/json' ``` -------------------------------- ### Redirection and History Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Details how HTTPX handles HTTP redirects by default and how to explicitly enable or disable redirection following, inspecting redirect history. ```APIDOC ## Redirection and History ### Description Explains HTTPX's default behavior regarding HTTP redirects and how to control redirection following. It also details how to inspect the history of followed redirects. ### Methods - `httpx.get(url)`: Makes a GET request. By default, does not follow redirects for all methods. - `httpx.get(url, follow_redirects=True)`: Makes a GET request and follows redirects. ### Request Example (Default Redirect Behavior) ```python import httpx r = httpx.get('http://github.com/') print(r.status_code) # Output: 301 print(r.history) # Output: [] print(r.next_request) # Shows the next request to HTTPS ``` ### Request Example (Following Redirects) ```python import httpx r = httpx.get('http://github.com/', follow_redirects=True) print(r.url) # Output: URL('https://github.com/') print(r.status_code) # Output: 200 print(r.history) # Output: [Response [301 Moved Permanently]] ``` ### Response - `r.status_code`: The HTTP status code of the response. - `r.history`: A list of `Response` objects representing any redirects that were followed. - `r.url`: The final URL after following redirects. - `r.next_request`: Information about the next request in a redirect chain (if not following redirects). ``` -------------------------------- ### Configure Timeouts with httpx Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Explains how HTTPX implements default timeouts for network operations to prevent indefinite hanging. It shows how to modify the timeout value or disable it completely. ```python >>> httpx.get('https://github.com/', timeout=0.001) ``` ```python >>> httpx.get('https://github.com/', timeout=None) ``` -------------------------------- ### Perform GET Requests with HTTPX Source: https://context7.com/encode/httpx/llms.txt Demonstrates how to execute synchronous GET requests using the top-level API. Includes examples for handling query parameters, custom headers, and parsing JSON responses. ```python import httpx # Simple GET request response = httpx.get('https://httpbin.org/get') print(response.status_code) print(response.headers['content-type']) print(response.text) print(response.json()) # GET with query parameters params = {'key1': 'value1', 'key2': ['value2', 'value3']} response = httpx.get('https://httpbin.org/get', params=params) print(response.url) # GET with custom headers headers = {'User-Agent': 'my-app/1.0', 'Accept': 'application/json'} response = httpx.get('https://httpbin.org/headers', headers=headers) print(response.json()['headers']['User-Agent']) ``` -------------------------------- ### Manage Cookies with httpx Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Shows how to access cookies set in a response and how to include cookies in outgoing requests using the `cookies` parameter. It also demonstrates the `httpx.Cookies` instance for more advanced cookie management. ```python >>> r = httpx.get('https://httpbin.org/cookies/set?chocolate=chip') >>> r.cookies['chocolate'] 'chip' ``` ```python >>> cookies = {"peanut": "butter"} >>> r = httpx.get('https://httpbin.org/cookies', cookies=cookies) >>> r.json() {'cookies': {'peanut': 'butter'}} ``` ```python >>> cookies = httpx.Cookies() >>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org') >>> cookies.set('cookie_off_domain', 'nope.', domain='example.org') >>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies) >>> r.json() {'cookies': {'cookie_on_domain': 'hello, there!'}} ``` -------------------------------- ### Passing URL Query Parameters with HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Explains how to include URL query parameters in a request using the `params` keyword argument in HTTPX. It also shows how to inspect the generated URL. ```python >>> params = {'key1': 'value1', 'key2': 'value2'} >>> r = httpx.get('https://httpbin.org/get', params=params) >>> r.url URL('https://httpbin.org/get?key2=value2&key1=value1') ``` ```python >>> params = {'key1': 'value1', 'key2': ['value2', 'value3']} >>> r = httpx.get('https://httpbin.org/get', params=params) >>> r.url URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3') ``` -------------------------------- ### Send Multipart File Uploads with httpx Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Demonstrates how to upload files using HTTP multipart encoding with httpx. It shows basic file uploads, setting custom filenames and content types, and including additional form data in the request. ```python >>> with open('report.xls', 'rb') as report_file: ... files = {'upload-file': report_file} ... r = httpx.post("https://httpbin.org/post", files=files) >>> print(r.text) { ... "files": { "upload-file": "<... binary content ...>" }, ... } ``` ```python >>> with open('report.xls', 'rb') as report_file: ... files = {'upload-file': ('report.xls', report_file, 'application/vnd.ms-excel')} ... r = httpx.post("https://httpbin.org/post", files=files) >>> print(r.text) { ... "files": { "upload-file": "<... binary content ...>" }, ... } ``` ```python >>> data = {'message': 'Hello, world!'} >>> with open('report.xls', 'rb') as report_file: ... files = {'file': report_file} ... r = httpx.post("https://httpbin.org/post", data=data, files=files) >>> print(r.text) { ... "files": { "file": "<... binary content ...>" }, "form": { "message": "Hello, world!", }, ... } ``` -------------------------------- ### Handle Request Errors in HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Demonstrates how to catch and handle RequestError exceptions, which occur during HTTP request issuance. It accesses the request URL from the exception object. ```python try: response = httpx.get("https://www.example.com/") except httpx.RequestError as exc: print(f"An error occurred while requesting {exc.request.url!r}.") ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/encode/httpx/blob/master/docs/contributing.md After cloning the repository, navigate into the project directory and run this command to install the project and its dependencies. This prepares your environment for development and testing. ```shell cd httpx scripts/install ``` -------------------------------- ### Accessing Response Text Content with HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Demonstrates how to access the decoded text content of an HTTP response using the `.text` attribute in HTTPX. It also shows how to inspect and override the response encoding. ```python >>> r = httpx.get('https://www.example.org/') >>> r.text '\n\n\nExample Domain...' ``` ```python >>> r.encoding 'UTF-8' ``` ```python >>> r.encoding None >>> r.text '\n\n\nExample Domain...' ``` ```python >>> r.encoding = 'ISO-8859-1' ``` -------------------------------- ### Send Binary Request Data with httpx Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Shows how to send raw binary data in an HTTP request using the `content` parameter in httpx. It also mentions setting custom `Content-Type` headers for binary uploads. ```python >>> content = b'Hello, world' >>> r = httpx.post("https://httpbin.org/post", content=content) ``` -------------------------------- ### Handle All HTTP Errors in HTTPX (Base Class) Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Illustrates catching both RequestError and HTTPStatusError using the base HTTPError class. This provides a general way to handle any HTTP-related errors. ```python try: response = httpx.get("https://www.example.com/") response.raise_for_status() except httpx.HTTPError as exc: print(f"Error while requesting {exc.request.url!r}.") ``` -------------------------------- ### Streaming Responses Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Demonstrates how to stream response content in various formats (bytes, text, lines) and access raw bytes without decoding. Also shows conditional loading of response bodies. ```APIDOC ## Streaming Responses ### Description Handles large downloads by streaming response content instead of loading the entire body into memory. Supports streaming binary content, text content, and text line-by-line. Also allows access to raw bytes without content decoding. ### Methods - `httpx.stream("GET", url)`: Initiates a streaming request. - `r.iter_bytes()`: Iterates over the response body as bytes. - `r.iter_text()`: Iterates over the response body as text. - `r.iter_lines()`: Iterates over the response body line-by-line. - `r.iter_raw()`: Iterates over the raw response bytes without decoding. - `r.read()`: Reads the entire response body. ### Request Example (Streaming Bytes) ```python import httpx with httpx.stream("GET", "https://www.example.com") as r: for data in r.iter_bytes(): print(data) ``` ### Request Example (Streaming Text) ```python import httpx with httpx.stream("GET", "https://www.example.com") as r: for text in r.iter_text(): print(text) ``` ### Request Example (Streaming Lines) ```python import httpx with httpx.stream("GET", "https://www.example.com") as r: for line in r.iter_lines(): print(line) ``` ### Request Example (Streaming Raw Bytes) ```python import httpx with httpx.stream("GET", "https://www.example.com") as r: for chunk in r.iter_raw(): print(chunk) ``` ### Request Example (Conditional Loading) ```python import httpx TOO_LONG = 1000000 # Example value with httpx.stream("GET", "https://www.example.com") as r: if int(r.headers.get('Content-Length', 0)) < TOO_LONG: r.read() print(r.text) ``` ### Response - `response.headers`: Dictionary-like object containing response headers. - `response.text`: The response body decoded as text (available if `r.read()` is called and content is not streamed line-by-line or chunked). ### Notes - Accessing `response.content` or `response.text` is not possible when streaming unless `response.read()` is explicitly called. ``` -------------------------------- ### Handle Response Status Codes with httpx Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Explains how to check and handle HTTP response status codes using httpx. It covers accessing the status code directly, using status code constants, and raising exceptions for non-2xx responses. ```python >>> r = httpx.get('https://httpbin.org/get') >>> r.status_code 200 ``` ```python >>> r.status_code == httpx.codes.OK True ``` ```python >>> not_found = httpx.get('https://httpbin.org/status/404') >>> not_found.status_code 404 >>> not_found.raise_for_status() Traceback (most recent call last): File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 837, in raise_for_status raise HTTPStatusError(message, response=self) httpx._exceptions.HTTPStatusError: 404 Client Error: Not Found for url: https://httpbin.org/status/404 For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404 ``` ```python >>> r.raise_for_status() ``` ```python >>> r = httpx.get('...').raise_for_status() >>> data = httpx.get('...').raise_for_status().json() ``` -------------------------------- ### Accessing Binary Response Content with HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Shows how to access the raw binary content of an HTTP response using the `.content` attribute in HTTPX. It also mentions automatic decoding of gzip, deflate, brotli, and zstd encodings. ```python >>> r.content b'\n\n\nExample Domain...' ``` ```python >>> from PIL import Image >>> from io import BytesIO >>> i = Image.open(BytesIO(r.content)) ``` -------------------------------- ### Async HTTP Request with Trio Source: https://github.com/encode/httpx/blob/master/docs/async.md Performs an asynchronous GET request to 'https://www.example.com/' using httpx and the Trio concurrency library. This requires the 'trio' package to be installed. ```python import httpx import trio async def main(): async with httpx.AsyncClient() as client: response = await client.get('https://www.example.com/') print(response) trio.run(main) ``` -------------------------------- ### Stream Response Content with httpx Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Demonstrates how to stream response content in various formats (bytes, text, lines, raw) using httpx.stream. This is useful for large downloads to avoid loading the entire response into memory. It also shows conditional loading of response bodies. ```python >>> with httpx.stream("GET", "https://www.example.com") as r: ... for data in r.iter_bytes(): ... print(data) ``` ```python >>> with httpx.stream("GET", "https://www.example.com") as r: ... for text in r.iter_text(): ... print(text) ``` ```python >>> with httpx.stream("GET", "https://www.example.com") as r: ... for line in r.iter_lines(): ... print(line) ``` ```python >>> with httpx.stream("GET", "https://www.example.com") as r: ... for chunk in r.iter_raw(): ... print(chunk) ``` ```python >>> with httpx.stream("GET", "https://www.example.com") as r: ... if int(r.headers['Content-Length']) < TOO_LONG: ... r.read() ... print(r.text) ``` -------------------------------- ### Async HTTP Request with AnyIO Source: https://github.com/encode/httpx/blob/master/docs/async.md Executes an asynchronous GET request to 'https://www.example.com/' using httpx and the AnyIO library, which can run on top of either asyncio or trio. This example explicitly uses the 'trio' backend. ```python import httpx import anyio async def main(): async with httpx.AsyncClient() as client: response = await client.get('https://www.example.com/') print(response) anyio.run(main, backend='trio') ``` -------------------------------- ### Install SOCKS Proxy Support Source: https://github.com/encode/httpx/blob/master/docs/advanced/proxies.md This command installs the necessary optional dependencies for HTTPX to support SOCKS proxies. This is a prerequisite for using SOCKS proxy configurations. ```shell $ pip install httpx[socks] ``` -------------------------------- ### Sending Form Encoded Data with HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Explains how to send form-encoded data in the request body for POST and PUT requests using the `data` keyword argument in HTTPX. It covers both single and multiple values for a key. ```python >>> data = {'key1': 'value1', 'key2': 'value2'} >>> r = httpx.post("https://httpbin.org/post", data=data) >>> print(r.text) { ... "form": { "key2": "value2", "key1": "value1" }, ... ``` ```python >>> data = {'key1': ['value1', 'value2']} >>> r = httpx.post("https://httpbin.org/post", data=data) >>> print(r.text) { ... "form": { "key1": [ "value1", "value2" ] }, ... ``` -------------------------------- ### Async HTTP Request with AsyncIO Source: https://github.com/encode/httpx/blob/master/docs/async.md Makes an asynchronous GET request to 'https://www.example.com/' using httpx and Python's built-in asyncio library. Requires the asyncio and httpx libraries to be installed. ```python import asyncio import httpx async def main(): async with httpx.AsyncClient() as client: response = await client.get('https://www.example.com/') print(response) asyncio.run(main()) ``` -------------------------------- ### Send Request with Custom Headers using httpx.Client (Python) Source: https://github.com/encode/httpx/blob/master/docs/advanced/clients.md Demonstrates how to send a GET request with custom headers using an httpx.Client. This example shows how to define a 'headers' dictionary and pass it to the '.get()' method, verifying the header is sent. ```python with httpx.Client() as client: headers = {'X-Custom': 'value'} r = client.get('https://example.com', headers=headers) r.request.headers['X-Custom'] 'value' ``` -------------------------------- ### Make a GET Request with httpx.Client (Python) Source: https://github.com/encode/httpx/blob/master/docs/advanced/clients.md Illustrates how to perform a GET request using an httpx.Client instance. The client object's methods like '.get()' accept the same arguments as the top-level httpx functions, allowing for flexible request customization. ```python with httpx.Client() as client: r = client.get('https://example.com') r ``` -------------------------------- ### Perform Basic Authentication with httpx Source: https://github.com/encode/httpx/blob/master/docs/advanced/authentication.md Illustrates a practical example of using Basic Authentication with httpx to access a protected endpoint. It shows the creation of the BasicAuth object, client instantiation with authentication, and making a GET request. ```python >>> auth = httpx.BasicAuth(username="finley", password="secret") >>> client = httpx.Client(auth=auth) >>> response = client.get("https://httpbin.org/basic-auth/finley/secret") >>> response ``` -------------------------------- ### Install HTTPX with HTTP/2 support Source: https://github.com/encode/httpx/blob/master/README.md Installs HTTPX with optional HTTP/2 support. This requires additional dependencies to enable HTTP/2 protocol capabilities. ```shell pip install httpx[http2] ``` -------------------------------- ### Install HTTPX with command-line client support Source: https://github.com/encode/httpx/blob/master/README.md Installs HTTPX with the optional command-line client dependency. This allows you to use HTTPX directly from your terminal. ```shell pip install 'httpx[cli]' ``` -------------------------------- ### Making Async GET Request with httpx Source: https://github.com/encode/httpx/blob/master/docs/async.md Demonstrates how to make an asynchronous GET request using httpx.AsyncClient within an async context manager. This is the standard way to initiate async requests and handle responses. ```python >>> async with httpx.AsyncClient() as client: ... r = await client.get('https://www.example.com/') ... >>> r ``` -------------------------------- ### Async HTTP/2 Request with httpx Source: https://context7.com/encode/httpx/llms.txt Demonstrates how to create an asynchronous HTTP client with HTTP/2 support enabled and make a GET request. It prints the HTTP version of the response. ```python import httpx import asyncio async def fetch_with_http2(): async with httpx.AsyncClient(http2=True) as client: response = await client.get('https://www.google.com/') print(response.http_version) # "HTTP/2" or "HTTP/1.1" asyncio.run(fetch_with_http2()) ``` -------------------------------- ### Install HTTPX with Brotli and Zstandard support Source: https://github.com/encode/httpx/blob/master/docs/index.md Installs HTTPX with optional support for decoding Brotli and Zstandard compressed responses. This enhances the client's ability to handle various compression formats efficiently. Use pip with the specified extras. ```shell pip install httpx[brotli,zstd] ``` -------------------------------- ### Install HTTPX using pip Source: https://github.com/encode/httpx/blob/master/README.md This command installs the core HTTPX library using pip. It is the standard way to add HTTPX to your Python project. ```shell pip install httpx ``` -------------------------------- ### Initialize and Use httpx.Client as a Context Manager (Python) Source: https://github.com/encode/httpx/blob/master/docs/advanced/clients.md Demonstrates the recommended way to use httpx.Client by initializing it within a 'with' statement, ensuring proper cleanup of connections. This approach is suitable for most use cases requiring efficient network resource management. ```python with httpx.Client() as client: ... ``` -------------------------------- ### Handle HTTPStatus Errors in HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Shows how to catch HTTPStatusError, raised when a response is not a 2xx success code using response.raise_for_status(). It accesses both request URL and response status code. ```python response = httpx.get("https://www.example.com/") try: response.raise_for_status() except httpx.HTTPStatusError as exc: print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.") ``` -------------------------------- ### Handle HTTP Errors Explicitly in HTTPX Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Demonstrates explicit handling of both RequestError and HTTPStatusError in separate except blocks. This allows for distinct error handling logic for each type of HTTP error. ```python try: response = httpx.get("https://www.example.com/") response.raise_for_status() except httpx.RequestError as exc: print(f"An error occurred while requesting {exc.request.url!r}.") except httpx.HTTPStatusError as exc: print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.") ``` -------------------------------- ### Send JSON Encoded Data with httpx Source: https://github.com/encode/httpx/blob/master/docs/quickstart.md Illustrates how to send JSON encoded data in an HTTP request using the `json` parameter in httpx. This is suitable for sending complex data structures. ```python >>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']} >>> r = httpx.post("https://httpbin.org/post", json=data) >>> print(r.text) { ... "json": { "boolean": true, "integer": 123, "list": [ "a", "b", "c" ] }, ... } ``` -------------------------------- ### Build and Send HTTPX Request Instance Source: https://github.com/encode/httpx/blob/master/docs/advanced/clients.md Demonstrates creating a manual httpx.Request instance and sending it using a httpx.Client. It also shows how to modify request headers before sending. ```python request = httpx.Request("GET", "https://example.com") with httpx.Client() as client: response = client.send(request) ... ``` ```python headers = {"X-Api-Key": "...", "X-Client-ID": "ABC123"} with httpx.Client(headers=headers) as client: request = client.build_request("GET", "https://api.example.com") print(request.headers["X-Client-ID"]) # "ABC123" # Don't send the API key for this particular request. del request.headers["X-Api-Key"] response = client.send(request) ... ``` -------------------------------- ### Perform Digest Authentication with httpx Source: https://github.com/encode/httpx/blob/master/docs/advanced/authentication.md Demonstrates how to use Digest Authentication with httpx, a more secure challenge-response mechanism than Basic Authentication. This example shows the setup for DigestAuth and a request to a digest-protected endpoint. ```python >>> auth = httpx.DigestAuth(username="olivia", password="secret") >>> client = httpx.Client(auth=auth) >>> response = client.get("https://httpbin.org/digest-auth/auth/olivia/secret") >>> response >>> response.history [] ``` -------------------------------- ### Run Documentation Locally Source: https://github.com/encode/httpx/blob/master/docs/contributing.md This command builds and serves the documentation site locally. This is useful for previewing changes to the documentation before submitting them. ```shell scripts/docs ``` -------------------------------- ### Accessing Response URL in HTTPX Source: https://github.com/encode/httpx/blob/master/docs/compatibility.md In HTTPX, accessing `response.url` returns a `URL` instance, providing more structured information than a simple string. To get a string representation, explicitly cast it using `str()`. ```python str(response.url) ``` -------------------------------- ### Configure Different Proxies for HTTP and HTTPS Source: https://github.com/encode/httpx/blob/master/docs/advanced/proxies.md This example shows how to use the `mounts` parameter to specify different proxy servers for HTTP and HTTPS traffic. It utilizes `httpx.HTTPTransport` to define custom proxy configurations for each protocol. ```python proxy_mounts = { "http://": httpx.HTTPTransport(proxy="http://localhost:8030"), "https://": httpx.HTTPTransport(proxy="http://localhost:8031"), } with httpx.Client(mounts=proxy_mounts) as client: ... ``` -------------------------------- ### Configure HTTP and SOCKS Proxies in httpx Source: https://context7.com/encode/httpx/llms.txt Provides examples of configuring HTTP and SOCKS proxies for httpx requests. This includes simple proxy settings, proxies with authentication, using different proxies for HTTP and HTTPS, proxy exclusions, and SOCKS proxy configuration. ```python import httpx # Simple proxy for all requests with httpx.Client(proxy='http://localhost:8080') as client: response = client.get('https://httpbin.org/ip') # Proxy with authentication with httpx.Client(proxy='http://user:password@localhost:8080') as client: response = client.get('https://httpbin.org/ip') # Different proxies for HTTP and HTTPS proxy_mounts = { 'http://': httpx.HTTPTransport(proxy='http://localhost:8080'), 'https://': httpx.HTTPTransport(proxy='http://localhost:8081'), } with httpx.Client(mounts=proxy_mounts) as client: response = client.get('https://httpbin.org/ip') # Proxy with exclusions mounts = { 'all://': httpx.HTTPTransport(proxy='http://localhost:8080'), 'all://internal.example.com': None, # No proxy for this domain } with httpx.Client(mounts=mounts) as client: response = client.get('https://httpbin.org/ip') # Uses proxy response = client.get('https://internal.example.com/api') # Direct connection # SOCKS proxy (requires: pip install httpx[socks]) with httpx.Client(proxy='socks5://localhost:1080') as client: response = client.get('https://httpbin.org/ip') ``` -------------------------------- ### Configure HTTP Proxy with Client Initialization Source: https://github.com/encode/httpx/blob/master/docs/advanced/proxies.md This snippet demonstrates how to configure a single HTTP proxy for all client requests by passing the proxy URL during client initialization. This is the simplest method for setting up a proxy. ```python with httpx.Client(proxy="http://localhost:8030") as client: ... ``` -------------------------------- ### AsyncClient Usage Source: https://github.com/encode/httpx/blob/master/docs/async.md Demonstrates how to create and use an AsyncClient for making asynchronous HTTP requests. ```APIDOC ## AsyncClient Usage ### Description This section details how to instantiate and utilize `httpx.AsyncClient` for asynchronous HTTP operations. It covers both context-managed usage with `async with` and explicit client management. ### Method `httpx.AsyncClient()` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import httpx async with httpx.AsyncClient() as client: response = await client.get('https://www.example.com/') print(response.status_code) ``` ### Response #### Success Response (200) - **status_code** (int) - The HTTP status code of the response. #### Response Example ```json { "status_code": 200 } ``` ``` -------------------------------- ### Use base_url with httpx.Client (Python) Source: https://github.com/encode/httpx/blob/master/docs/advanced/clients.md Demonstrates the use of the 'base_url' parameter in the httpx.Client constructor. This allows prepending a base URL to all outgoing requests made with that client instance, simplifying request construction. ```python with httpx.Client(base_url='http://httpbin.org') as client: r = client.get('/headers') r.request.url URL('http://httpbin.org/headers') ``` -------------------------------- ### Send Request Body with DELETE Method in HTTPX Source: https://github.com/encode/httpx/blob/master/docs/compatibility.md HTTP methods like GET, DELETE, HEAD, and OPTIONS are not specified to support request bodies. While HTTPX's corresponding functions (`.get`, `.delete`, etc.) do not accept `content`, `files`, `data`, or `json` arguments, you can use the generic `.request` function to send data with these methods if necessary. ```python import httpx httpx.request( method="DELETE", url="https://www.example.com/", content=b'A request body on a DELETE request.' ) ``` -------------------------------- ### Install httpx and chardet (Shell) Source: https://github.com/encode/httpx/blob/master/docs/advanced/text-encodings.md Provides the shell commands to install the httpx library and the chardet library, which is used for character set auto-detection. ```shell $ pip install httpx $ pip install chardet ``` -------------------------------- ### Instantiate httpx AsyncClient with HTTP/2 enabled Source: https://github.com/encode/httpx/blob/master/docs/http2.md Demonstrates how to create an asynchronous httpx client with HTTP/2 support enabled. This allows for more efficient, concurrent requests when interacting with servers that also support HTTP/2. ```python client = httpx.AsyncClient(http2=True) ``` -------------------------------- ### Construct and send an HTTP Request Source: https://github.com/encode/httpx/blob/master/docs/api.md Demonstrates how to manually construct an HTTPX Request object and send it using an existing client instance. This provides granular control over the request parameters before transmission. ```python request = httpx.Request("GET", "https://example.org", headers={'host': 'example.org'}) response = client.send(request) ``` -------------------------------- ### Basic HTTP GET request with httpx Source: https://github.com/encode/httpx/blob/master/README.md Demonstrates a basic HTTP GET request using the httpx library in Python. It shows how to make a request, access the response status code, headers, and text content. ```python >>> import httpx >>> r = httpx.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...' ``` -------------------------------- ### Proxy Requests to a Domain and its Subdomains with httpx Source: https://github.com/encode/httpx/blob/master/docs/advanced/transports.md This example uses a wildcard ('*') to proxy all requests to 'example.com' and any of its subdomains through 'http://localhost:8030'. ```python mounts = { "all://*example.com": httpx.HTTPTransport(proxy="http://localhost:8030"), } ``` -------------------------------- ### Configure HTTPX Client with Alternative Certificate Store Source: https://github.com/encode/httpx/blob/master/docs/advanced/ssl.md Demonstrates how to configure an `httpx.Client` to use an explicitly specified certificate verification store using the standard SSL context API with `cafile` or `capath`. ```python import httpx import ssl # Use an explicitly configured certificate store. ctx = ssl.create_default_context(cafile="path/to/certs.pem") # Either cafile or capath. client = httpx.Client(verify=ctx) ```