### Make HTTP Requests Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Examples of making various HTTP requests (GET, POST, PUT, PATCH, DELETE, OPTIONS) with query parameters and JSON bodies. Ensure the client is properly built and configured before sending requests. ```python # GET response = await client.get("/path").query({"key": "value"}).build().send() ``` ```python # POST with JSON response = await client.post("/path") \ .body_json({"key": "value"}) \ .build() \ .send() ``` ```python # PUT response = await client.put("/path").body_json({"key": "value"}).build().send() ``` ```python # PATCH response = await client.patch("/path").body_json({"key": "value"}).build().send() ``` ```python # DELETE response = await client.delete("/path").build().send() ``` ```python # Custom method response = await client.request("OPTIONS", "/path").build().send() ``` -------------------------------- ### Asynchronous Client Usage Example Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/client.md Demonstrates how to use the asynchronous Client to perform GET, POST with JSON, and custom method requests. Ensure the client is properly managed using an async context manager. ```python async with ClientBuilder().build() as client: # GET request response = await client.get("https://httpbin.org/get").build().send() # POST with JSON body response = await client.post("https://httpbin.org/post") \ .body_json({"key": "value"}) \ .build() \ .send() # Custom method response = await client.request("OPTIONS", "https://httpbin.org/") \ .build() \ .send() ``` -------------------------------- ### Example Usage of QueryParams with ClientBuilder Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/types.md Shows how to send GET requests with query parameters using both dict-based and tuple-based QueryParams. ```python from pyreqwest.client import ClientBuilder async with ClientBuilder().build() as client: # Dict-based response = await client.get("https://api.example.com/search") \ .query({"q": "python", "limit": 10}) \ .build() \ .send() # Tuple-based (preserves order, allows duplicate keys) response = await client.get("https://api.example.com/search") \ .query([("tag", "python"), ("tag", "http"), ("limit", "10")]) \ .build() \ .send() ``` -------------------------------- ### Async Client Configuration Example Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/client.md Demonstrates how to configure and use an asynchronous HTTP client using the ClientBuilder. This example sets a base URL, default headers, a timeout, and enables error handling for non-success status codes. ```python from pyreqwest.client import ClientBuilder from datetime import timedelta async with ClientBuilder() \ .base_url("https://api.example.com") \ .default_headers({"Authorization": "Bearer token"}) \ .timeout(timedelta(seconds=30)) \ .error_for_status(True) \ .build() as client: response = await client.get("/users").build().send() data = await response.json() ``` -------------------------------- ### Handle HTTP Response Data Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/response.md Example demonstrating how to build a client, send a GET request, and process the asynchronous response. Shows checking status codes and reading response body as JSON, text, or bytes. Also demonstrates accessing headers and the final URL. ```python async with ClientBuilder().error_for_status(True).build() as client: response = await client.get("https://httpbin.org/json").build().send() # Check status if response.status == 200: # Read as JSON data = await response.json() # Or read as text text = await response.text() # Or read as bytes body_bytes = await response.bytes() # Access headers content_type = response.headers.get("content-type") # Access URL after redirects final_url = response.url ``` -------------------------------- ### Sync Client Setup Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/README.md Use SyncClientBuilder for synchronous requests. Configure the base URL before building the client. ```python from pyreqwest.client import SyncClientBuilder with SyncClientBuilder() \ .base_url("https://api.example.com") \ .build() as client: response = client.get("/users").build().send() data = response.json() ``` -------------------------------- ### Synchronous Client Usage Example Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/client.md Illustrates making a synchronous GET request and processing the JSON response. This client is suitable for blocking I/O operations. ```python with SyncClientBuilder().build() as client: response = client.get("https://httpbin.org/get").build().send() print(response.json()) ``` -------------------------------- ### Manual Setup of ClientMocker Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/pytest-plugin.md Illustrates how to manually create and configure a ClientMocker instance using monkeypatch for use in tests. ```python from pyreqwest.pytest_plugin import ClientMocker def test_with_manual_mocker(monkeypatch): mocker = ClientMocker.create_mocker(monkeypatch) mocker.get(path="/data").with_body_json({"key": "value"}) # Configure and test client ``` -------------------------------- ### Async Client Setup Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/README.md Use ClientBuilder for asynchronous requests. Configure base URL, timeout, and error handling before building the client. ```python from pyreqwest.client import ClientBuilder async with ClientBuilder() \ .base_url("https://api.example.com") \ .timeout(timedelta(seconds=30)) \ .error_for_status(True) \ .build() as client: response = await client.get("/users").build().send() data = await response.json() ``` -------------------------------- ### Basic Mocking Example Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/pytest-plugin.md Demonstrates how to mock a GET request to '/api/data' and assert that the response body is JSON. This is useful for testing API integrations without making actual network calls. ```python async def test_basic(client_mocker: ClientMocker) -> None: client_mocker.get(path="/api/data") \ .with_body_json({"message": "hello"}) async with ClientBuilder().build() as client: response = await client.get("http://example.invalid/api/data").build().send() assert await response.json() == {"message": "hello"} ``` -------------------------------- ### Construct URL with Query Parameters Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Example of building a URL object and adding query parameters to it before sending the request. ```python # URL with params from pyreqwest.http import Url url = Url("https://api.example.com") / "search" url = url.with_query({"q": "test"}) await client.get(url).build().send() ``` -------------------------------- ### Example Usage of HeadersType Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/types.md Demonstrates setting HTTP headers using both dict-based and tuple-based HeadersType. ```python from pyreqwest.types import HeadersType # Dict-based headers: HeadersType = { "X-Custom": "value", "Authorization": "Bearer token" } # Tuple-based headers: HeadersType = [ ("X-Custom", "value"), ("Authorization", "Bearer token") ] response = await client.get("https://api.example.com") \ .headers(headers) \ .build() \ .send() ``` -------------------------------- ### Example Usage of ExtensionsType Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/types.md Demonstrates passing arbitrary extensions data and accessing it within a middleware. ```python from pyreqwest.types import ExtensionsType extensions: ExtensionsType = { "request_id": "abc123", "user_id": 42, "metadata": {"custom": "data"} } response = await client.get("https://api.example.com") \ .extensions(extensions) \ .build() \ .send() # Access in middleware async def log_middleware(request: Request, next_handler: Next) -> Response: request_id = request.extensions.get("request_id") return await next_handler.run(request) ``` -------------------------------- ### PartBuilder Example: From File and Stream Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/multipart.md Illustrates creating multipart parts from a file on disk and from a byte stream. It shows how to set the MIME type and filename for each part before adding them to a FormBuilder. ```python from pyreqwest.multipart import PartBuilder, FormBuilder from pathlib import Path from collections.abc import AsyncIterable # From file file_part = await PartBuilder.from_file("image.png") file_part = file_part.mime("image/png").file_name("profile.png") # From stream async def my_stream() -> AsyncIterable[bytes]: yield b"file" yield b"content" stream_part = PartBuilder.from_stream(my_stream()) stream_part = stream_part.mime("text/plain").file_name("generated.txt") # Add to form form = FormBuilder() \ .part("avatar", file_part) \ .part("document", stream_part) # Send response = await client.post("https://httpbin.org/post") \ .multipart(form) \ .build() \ .send() ``` -------------------------------- ### Build and Send Async HTTP Request Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/request.md Demonstrates building and sending an asynchronous HTTP GET request with query parameters. Also shows how to send a POST request with custom headers, basic authentication, and a JSON body. Finally, illustrates direct modification of headers on a built request. ```python from pyreqwest.client import ClientBuilder async with ClientBuilder().build() as client: # Simple request response = await client.get("https://httpbin.org/get") \ .query({"key": "value"}) \ .build() \ .send() # With headers and auth response = await client.post("https://httpbin.org/post") \ .headers({"X-Custom": "header"}) \ .basic_auth("user", "pass") \ .body_json({"data": "value"}) \ .build() \ .send() # Direct header modification req = client.get("https://httpbin.org/get").build() req.headers["X-Custom"] = "modified" ``` -------------------------------- ### Client and SyncClient Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/INDEX.md Documentation for asynchronous ClientBuilder and Client, and synchronous SyncClientBuilder and SyncClient, including all builder methods and usage examples. ```APIDOC ## Client and SyncClient ### Description Documentation for asynchronous `ClientBuilder` and `Client`, and synchronous `SyncClientBuilder` and `SyncClient`. Covers all builder methods with parameters and provides usage examples. ### Modules - `api-reference/client.md` ``` -------------------------------- ### Example Usage of QueryParams Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/types.md Demonstrates how to use QueryParams for single and multiple values for the same parameter, as well as mixed types. ```python from pyreqwest.types import QueryParams # Single value query: QueryParams = {"key": "value"} # Multiple values for same parameter query: QueryParams = {"tags": ["python", "http"]} # Mixed query: QueryParams = {"search": "term", "limit": 10, "tags": ["a", "b"]} ``` -------------------------------- ### Middleware Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/INDEX.md Details on Middleware and SyncMiddleware types, Next and SyncNext handlers, and 7 middleware patterns with examples, including ordering and composition. ```APIDOC ## Middleware ### Description Details on `Middleware` and `SyncMiddleware` types, `Next` and `SyncNext` handlers. Includes 7 middleware patterns with examples, covering middleware ordering and composition. ### Modules - `api-reference/middleware.md` ``` -------------------------------- ### Example Usage of FormParams Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/types.md Shows how to send form-encoded data using FormParams. ```python from pyreqwest.types import FormParams form_data: FormParams = { "username": "john", "password": "secret" } response = await client.post("https://api.example.com/login") \ .body_form(form_data) \ .build() \ .send() ``` -------------------------------- ### Async GET Request with pyreqwest_get Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/simple-request.md Perform an asynchronous GET request using pyreqwest_get. This is a convenient shortcut for making GET requests with optional query parameters. ```python from pyreqwest.simple.request import pyreqwest_get response = await pyreqwest_get("https://httpbin.org/get") \ .query({"key": "value"}) \ .build() \ .send() print(await response.json()) ``` -------------------------------- ### Request Middleware Example Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/request.md Demonstrates how to use the Request object within middleware to inspect, modify headers, and create a copy of the request before passing it to the next handler. ```python async def middleware(request: Request, next_handler: Next) -> Response: print(f"Request: {request.method} {request.url}") # Modify headers request.headers["X-Custom"] = "value" # Copy for retry request_copy = request.copy() return await next_handler.run(request) ``` -------------------------------- ### Perform One-Off GET Request Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Make a single GET request without needing to build a client instance first. The response can be processed to get JSON data. ```python from pyreqwest.simple.request import pyreqwest_get, pyreqwest_post # No client needed for single requests response = await pyreqwest_get("https://api.example.com/data").build().send() data = await response.json() ``` -------------------------------- ### Build and Send Sync HTTP Request Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/request.md Shows how to build and send a synchronous HTTP GET request with query parameters using SyncClientBuilder. ```python with SyncClientBuilder().build() as client: response = client.get("https://httpbin.org/get") \ .query({"key": "value"}) \ .build() \ .send() ``` -------------------------------- ### Mock GET Request with JSON Body Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Create a simple mock for a GET request that returns a JSON body. ```python from pyreqwest.pytest_plugin import ClientMocker async def test_api(client_mocker: ClientMocker) -> None: # Simple mock client_mocker.get(path="/users") \ .with_body_json({"users": []}) ``` -------------------------------- ### pyreqwest_get() Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/simple-request.md Async GET request function. It simplifies making GET requests by taking only the URL and returning a request builder. ```APIDOC ## pyreqwest_get() ### Description Async GET request function. It simplifies making GET requests by taking only the URL and returning a request builder. ### Method GET ### Endpoint N/A (This is a function call, not a direct HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pyreqwest.simple.request import pyreqwest_get response = await pyreqwest_get("https://httpbin.org/get") \ .query({"key": "value"}) \ .build() \ .send() print(await response.json()) ``` ### Response #### Success Response `OneOffRequestBuilder` - Builder for the request #### Response Example (The example shows building and sending the request, the direct return is a builder object.) ``` -------------------------------- ### Using a Custom CookieStore with ClientBuilder Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/cookies.md Shows how to integrate a custom CookieStore with pyreqwest's ClientBuilder to manage cookies across requests. This example demonstrates setting cookies via a login request and automatically including them in a subsequent profile request. ```python from pyreqwest.client import ClientBuilder from pyreqwest.cookie import CookieStore # Create a shared cookie store cookie_store = CookieStore() async with ClientBuilder() \ .cookie_provider(cookie_store) \ .build() as client: # First request sets cookies response = await client.get("https://example.com/login") \ .query({"session": "abc123"}) \ .build() \ .send() # Second request automatically includes cookies response = await client.get("https://example.com/profile") \ .build() \ .send() # Access stored cookies cookies = cookie_store.get_all_any() for cookie in cookies: print(f"{cookie.name}={cookie.value}") ``` -------------------------------- ### Simple One-Off GET Request Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/README.md Perform a simple asynchronous GET request without building a full client. Ensure to await the response and JSON parsing. ```python from pyreqwest.simple.request import pyreqwest_get response = await pyreqwest_get("https://api.example.com/data").build().send() print(await response.json()) ``` -------------------------------- ### Example Usage of Stream Type Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/types.md Illustrates sending data using both async and sync streams for request bodies. ```python from pyreqwest.types import Stream # Async stream async def data_stream() -> AsyncIterable[bytes]: yield b"chunk1" yield b"chunk2" response = await client.post("https://api.example.com/upload") \ .body_stream(data_stream()) \ .build() \ .send() # Sync stream (with simple request) def sync_stream() -> Iterable[bytes]: yield b"chunk1" yield b"chunk2" response = pyreqwest_post("https://api.example.com/upload") \ .body_stream(sync_stream()) \ .build() \ .send() ``` -------------------------------- ### Configure SOCKS5 Proxy with ProxyBuilder Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/proxy.md Use ProxyBuilder.socks5() to configure a SOCKS5 proxy for client requests. The URL must start with 'socks5://'. ```python # SOCKS5 proxy async with ClientBuilder() \ .proxy(ProxyBuilder.socks5("socks5://socks.example.com:1080")) \ .build() as client: response = await client.get("https://api.example.com").build().send() ``` -------------------------------- ### Cookies Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/INDEX.md Information about the Cookie class and properties, CookieStore for automatic management, and examples for default and custom stores. ```APIDOC ## Cookies ### Description Information about the `Cookie` class and its properties, `CookieStore` for automatic management, and examples for default and custom cookie stores. ### Modules - `api-reference/cookies.md` ``` -------------------------------- ### Pytest Plugin Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/INDEX.md Details on the ClientMocker pytest fixture, Mock class with 20+ methods, Matcher types documentation, complete testing examples, and error response mocking. ```APIDOC ## Pytest Plugin ### Description Details on the `ClientMocker` pytest fixture, the `Mock` class with over 20 methods, matcher types documentation, complete testing examples, and how to mock error responses. ### Modules - `api-reference/pytest-plugin.md` ``` -------------------------------- ### Define Middleware Execution Order Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/middleware.md Middleware are executed sequentially in the order they are added to the ClientBuilder. This example illustrates the flow from mw1 to mw3 and back. ```python # Execution order: mw1 -> mw2 -> mw3 -> HTTP handler -> mw3 returns -> mw2 returns -> mw1 returns async with ClientBuilder() \ .with_middleware(mw1) \ .with_middleware(mw2) \ .with_middleware(mw3) \ .build() as client: ... ``` -------------------------------- ### FormBuilder Example: Text Fields and File Upload Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/multipart.md Demonstrates how to use FormBuilder to add simple text fields and a file upload part to a multipart form. Ensure ClientBuilder is used to build the client and the multipart method is called on the request builder. ```python from pyreqwest.multipart import FormBuilder, PartBuilder from pyreqwest.client import ClientBuilder from pathlib import Path async with ClientBuilder().build() as client: # Simple text fields form = FormBuilder() \ .text("username", "john_doe") \ .text("email", "john@example.com") response = await client.post("https://httpbin.org/post") \ .multipart(form) \ .build() \ .send() # With file upload file_path = Path("document.pdf") part = await PartBuilder.from_file(file_path) part = part.mime("application/pdf").file_name("document.pdf") form = FormBuilder() \ .text("description", "Important document") \ .part("file", part) response = await client.post("https://httpbin.org/post") \ .multipart(form) \ .build() \ .send() ``` -------------------------------- ### Pytest ClientMocker Example Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/pytest-plugin.md Demonstrates how to use ClientMocker for various mocking scenarios including path matching, query parameter matching, header matching, body matching, JSON body matching, and custom request matching. It also shows how to assert that a mock was called and retrieve captured requests. ```python from pyreqwest.pytest_plugin import ClientMocker from pyreqwest.client import ClientBuilder async def test_matching(client_mocker: ClientMocker) -> None: # Match by path mock1 = client_mocker.get(path="/api/users") # Match by path pattern mock2 = client_mocker.get(path=r"/api/users/\d+") # Match by query parameters client_mocker.get(path="/search") \ .match_query_param("q", "test") \ .with_body_json({"results": []}) # Match by headers client_mocker.post(path="/data") \ .match_header("content-type", "application/json") \ .with_status(201) # Match by body content client_mocker.post(path="/upload") \ .match_body(b"expected-content") \ .with_body_text("OK") # Match by JSON body client_mocker.post(path="/users") \ .match_body_json({"name": "John"}) \ .with_body_json({"id": 1, "name": "John"}) # Custom matcher def check_auth(request: Request) -> bool: return "authorization" in request.headers client_mocker.get(path="/protected") \ .match_request(check_auth) \ .with_body_json({"secret": "data"}) # Assert calls async with ClientBuilder().build() as client: await client.get("http://example.invalid/api/users").build().send() mock1.assert_called(count=1) assert len(mock1.get_requests()) == 1 ``` -------------------------------- ### HeaderMap Class Usage Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/http-utils.md Illustrates how to use HeaderMap for managing HTTP headers with case-insensitive access. Supports standard dictionary operations like get, set, delete, and iteration. ```python from pyreqwest.client import ClientBuilder async with ClientBuilder().build() as client: req = client.get("https://httpbin.org/headers").build() # Set headers (case-insensitive) req.headers["X-Custom-Header"] = "value1" req.headers["content-type"] = "application/json" # Get headers (case-insensitive) ct = req.headers["Content-Type"] custom = req.headers.get("x-custom-header") # Check existence if "authorization" in req.headers: del req.headers["authorization"] # Iterate for key, value in req.headers.items(): print(f"{key}: {value}") ``` -------------------------------- ### Client Methods Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/client.md The Client class provides methods for making asynchronous HTTP requests. It supports common HTTP methods like GET, POST, PUT, PATCH, DELETE, and HEAD, as well as a generic `request` method for custom methods. ```APIDOC ## Client Asynchronous HTTP client for making requests. ### Methods - **close()**: `Awaitable[None]` - Close the client and release resources. - **get(url: str | Url)**: `RequestBuilder` - Start a GET request. - **post(url: str | Url)**: `RequestBuilder` - Start a POST request. - **put(url: str | Url)**: `RequestBuilder` - Start a PUT request. - **patch(url: str | Url)**: `RequestBuilder` - Start a PATCH request. - **delete(url: str | Url)**: `RequestBuilder` - Start a DELETE request. - **head(url: str | Url)**: `RequestBuilder` - Start a HEAD request. - **request(method: str, url: str | Url)**: `RequestBuilder` - Start a custom HTTP method request. ### Example ```python async with ClientBuilder().build() as client: # GET request response = await client.get("https://httpbin.org/get").build().send() # POST with JSON body response = await client.post("https://httpbin.org/post") \ .body_json({"key": "value"}) \ .build() \ .send() # Custom method response = await client.request("OPTIONS", "https://httpbin.org/") \ .build() \ .send() ``` ``` -------------------------------- ### Simple Sync Request Source: https://github.com/markussintonen/pyreqwest/blob/main/README.md Provides a simplified interface for making synchronous HTTP GET requests, suitable for basic scripting needs. This method does not reuse connections and is less optimized than the full client API. ```python # Sync example from pyreqwest.simple.sync_request import pyreqwest_get response = pyreqwest_get("https://httpbun.com/get").query({"q": "val"}).send() print(response.json()) ``` -------------------------------- ### Simple Async Request Source: https://github.com/markussintonen/pyreqwest/blob/main/README.md Offers a simplified interface for making asynchronous HTTP GET requests, intended for straightforward use cases like scripts. For performance-critical applications, the full client API is recommended due to connection reuse and other optimizations. ```python # Async example from pyreqwest.simple.request import pyreqwest_get response = await pyreqwest_get("https://httpbun.com/get").query({"q": "val"}).send() print(await response.json()) ``` -------------------------------- ### Handle Synchronous HTTP Response Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/response.md Example of using a synchronous client to send a request and process the response. Demonstrates accessing the status code and content type header, and parsing the JSON body. ```python with SyncClientBuilder().build() as client: response = client.get("https://httpbin.org/json").build().send() data = response.json() print(response.status, response.headers.get("content-type")) ``` -------------------------------- ### Create Async and Sync Clients Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates how to build asynchronous and synchronous clients with custom configurations like base URL, default headers, and timeouts. Use `ClientBuilder` for async and `SyncClientBuilder` for sync operations. ```python from pyreqwest.client import ClientBuilder, SyncClientBuilder from datetime import timedelta # Async client async with ClientBuilder() \ .base_url("https://api.example.com") \ .default_headers({"Authorization": "Bearer token"}) \ .timeout(timedelta(seconds=30)) \ .error_for_status(True) \ .build() as client: response = await client.get("/users").build().send() # Sync client with SyncClientBuilder().base_url("https://api.example.com").build() as client: response = client.get("/users").build().send() ``` -------------------------------- ### Async and Sync Client Usage Source: https://github.com/markussintonen/pyreqwest/blob/main/README.md Demonstrates how to build and use both asynchronous and synchronous HTTP clients. The `error_for_status(True)` option ensures that non-2xx responses raise an exception. Context managers are recommended for resource management. ```python from pyreqwest.client import ClientBuilder, SyncClientBuilder async def example_async(): async with ClientBuilder().error_for_status(True).build() as client: response = await client.get("https://httpbun.com/get").query({"q": "val"}).build().send() print(await response.json()) def example_sync(): with SyncClientBuilder().error_for_status(True).build() as client: print(client.get("https://httpbun.com/get").query({"q": "val"}).build().send().json()) ``` -------------------------------- ### Synchronous GET Request Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/simple-request.md Use `pyreqwest_get` for synchronous GET requests. This function simplifies making GET requests and allows for query parameter customization before sending the request. ```python from pyreqwest.simple.sync_request import pyreqwest_get response = pyreqwest_get("https://httpbin.org/get") \ .query({"key": "value"}) \ .build() \ .send() print(response.json()) ``` -------------------------------- ### pyreqwest_get() Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/simple-request.md Synchronous GET request function. Simplifies making GET requests to a specified URL. ```APIDOC ## pyreqwest_get() ### Description Synchronous GET request. ### Method Signature ```python def pyreqwest_get(url: str | Url) -> SyncOneOffRequestBuilder: ... ``` ### Example ```python from pyreqwest.simple.sync_request import pyreqwest_get response = pyreqwest_get("https://httpbin.org/get") \ .query({"key": "value"}) \ .build() \ .send() print(response.json()) ``` ``` -------------------------------- ### Configure Authentication Methods in Python Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/README.md Demonstrates how to apply basic authentication, bearer token authentication per request, and set default authorization headers for all requests using ClientBuilder. ```python # Basic auth per-request response = await client.get("/protected") \ .basic_auth("username", "password") \ .build() \ .send() ``` ```python # Bearer token response = await client.get("/protected") \ .bearer_auth("my-token") \ .build() \ .send() ``` ```python # Default headers for all requests async with ClientBuilder() \ .default_headers({"Authorization": "Bearer token"}) \ .build() as client: response = await client.get("/protected").build().send() ``` -------------------------------- ### Mock GET Request with Query Parameter Matching Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Mock a GET request that only matches if a specific query parameter is present. ```python # With query matching client_mocker.get(path="/search") \ .match_query_param("q", "test") \ .with_body_json({"results": []}) ``` -------------------------------- ### Perform One-Off Synchronous GET Request Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Execute a single GET request synchronously using a dedicated function. This is useful for environments where async is not available or desired. ```python # Sync version from pyreqwest.simple.sync_request import pyreqwest_get as sync_get response = sync_get("https://api.example.com/data").build().send() ``` -------------------------------- ### Set Query Parameters with Dictionary Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates setting query parameters using a dictionary. ```python # Dict .query({"key": "value", "limit": 10}) ``` -------------------------------- ### Basic Authentication Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Shows how to configure basic authentication with a username and password for a request. ```python response = await client.get("/path") \ .basic_auth("username", "password") \ .build() \ .send() ``` -------------------------------- ### Send Form-Encoded Request Body Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Example of sending data as form-encoded key-value pairs. ```python # Form-encoded .body_form({"username": "john", "password": "secret"}) ``` -------------------------------- ### Configure HTTP Proxy Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Set up an HTTP proxy by providing the proxy URL to the `proxy` method in `ClientBuilder`. ```python from pyreqwest.proxy import ProxyBuilder # HTTP proxy async with ClientBuilder() \ .proxy("http://proxy.example.com:8080") \ .build() as client: ... ``` -------------------------------- ### Send JSON Request Body Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Example of sending a JSON payload as the request body. ```python # JSON .body_json({"key": "value"}) ``` -------------------------------- ### Synchronous Client Builder Configuration Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/client.md Shows how to configure and build a synchronous HTTP client using SyncClientBuilder. This includes setting a base URL and a timeout. The client is managed using a standard context manager. ```python from pyreqwest.client import SyncClientBuilder with SyncClientBuilder() \ .base_url("https://api.example.com") \ .timeout(timedelta(seconds=30)) \ .build() as client: response = client.get("/users").build().send() data = response.json() ``` -------------------------------- ### Iterate and Print Cookies from CookieStore Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/cookies.md Demonstrates how to retrieve all cookies from a CookieStore and print their details. Requires importing CookieStore. ```python from pyreqwest.cookie import CookieStore store = CookieStore() for cookie in store.get_all_any(): print(f"Name: {cookie.name}") print(f"Value: {cookie.value}") print(f"Secure: {cookie.secure}") print(f"HttpOnly: {cookie.http_only}") ``` -------------------------------- ### Set Query Parameters with Tuples Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Illustrates setting query parameters using a list of tuples to preserve order. ```python # Tuples (order-preserving) .query([("tag", "python"), ("tag", "http")]) ``` -------------------------------- ### Multipart Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/INDEX.md Documentation for FormBuilder for multipart forms, PartBuilder for file uploads, streaming part support, and usage examples. ```APIDOC ## Multipart ### Description Documentation for `FormBuilder` for multipart forms, `PartBuilder` for file uploads, streaming part support, and usage examples. ### Modules - `api-reference/multipart.md` ``` -------------------------------- ### Bearer Token Authentication Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Illustrates how to set a bearer token for authentication. ```python response = await client.get("/path") \ .bearer_auth("token") \ .build() \ .send() ``` -------------------------------- ### Simple Request Functions Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/INDEX.md Documentation for one-off async and sync request functions, including pyreqwest_get, pyreqwest_post, and guidance on when to use simple vs. persistent clients. ```APIDOC ## Simple Request Functions ### Description Documentation for one-off asynchronous and synchronous request functions, such as `pyreqwest_get` and `pyreqwest_post`. Provides guidance on when to use simple requests versus persistent clients. ### Modules - `api-reference/simple-request.md` ``` -------------------------------- ### HTTP Method Matcher Type Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/types.md An alias for the Matcher type, specifically used for matching HTTP methods like GET, POST, etc. ```python MethodMatcher = Matcher ``` -------------------------------- ### Define and Apply Request Middleware Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Shows how to define a custom middleware function and apply it to a client. ```python async def my_middleware(request: Request, next_handler: Next) -> Response: request.headers["X-Middleware"] = "value" response = await next_handler.run(request) response.headers["X-Response"] = "modified" return response # Add to client async with ClientBuilder() \ .with_middleware(my_middleware) \ .build() as client: ... ``` -------------------------------- ### Apply Middleware to Specific Request Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates how to apply middleware to an individual request rather than the entire client. ```python # Add to specific request response = await client.get("/path") \ .with_middleware(my_middleware) \ .build() \ .send() ``` -------------------------------- ### Configure HTTP and SOCKS5 Proxies in Python Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/README.md Set up HTTP or SOCKS5 proxies for requests, including the ability to specify hosts that should bypass the proxy. This is essential for network environments with proxy requirements. ```python from pyreqwest.proxy import ProxyBuilder # HTTP proxy async with ClientBuilder() \ .proxy("http://proxy.example.com:8080") \ .build() as client: response = await client.get("https://api.example.com").build().send() ``` ```python # SOCKS5 proxy with no-proxy list async with ClientBuilder() \ .proxy(ProxyBuilder.socks5("socks5://socks.example.com:1080") \ .no_proxy_hosts(["localhost", "internal.example.com"])) .build() as client: response = await client.get("https://api.example.com").build().send() ``` -------------------------------- ### Using the Default Cookie Store with ClientBuilder Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/cookies.md Demonstrates enabling the default cookie store functionality within pyreqwest's ClientBuilder. This allows the client to automatically manage cookies without explicit configuration of a CookieStore instance. ```python from pyreqwest.client import ClientBuilder from pyreqwest.cookie import CookieStore # Or use default cookie store on client async with ClientBuilder() \ .default_cookie_store(True) \ .build() as client: response = await client.get("https://example.com/login") \ .build() \ .send() # Cookies are automatically managed by client response = await client.get("https://example.com/profile") \ .build() \ .send() ``` -------------------------------- ### Configure Custom Cookie Store Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Use a custom `CookieStore` instance by passing it to `cookie_provider` in `ClientBuilder`. ```python store = CookieStore() async with ClientBuilder() \ .cookie_provider(store) \ .build() as client: ... ``` -------------------------------- ### Handle ConnectError Exception Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/errors.md Demonstrates how to catch and handle a ConnectError when establishing a connection to a non-existent domain. ```python from pyreqwest.exceptions import ConnectError try: response = await client.get("https://nonexistent.invalid").build().send() except ConnectError as e: print(f"Cannot connect: {e.message}") ``` -------------------------------- ### Use String URL for Proxy Configuration Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/proxy.md A proxy can be configured directly using a string representation of the proxy URL, including authentication credentials. ```python # String representation of proxy URL proxy_url = "http://user:pass@proxy.example.com:8080" async with ClientBuilder() \ .proxy(proxy_url) \ .build() as client: response = await client.get("https://api.example.com").build().send() ``` -------------------------------- ### ProxyBuilder Instance Methods Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/proxy.md These instance methods allow further customization of the proxy configuration. ```APIDOC ## ProxyBuilder.no_proxy_hosts() ### Description Specify hosts to bypass the proxy. ### Method `no_proxy_hosts(hosts: str | list[str])` ### Parameters #### Path Parameters - **hosts** (str | list[str]) - Required - A string or list of strings representing hosts to bypass. ### Returns `Self` ## ProxyBuilder.custom() ### Description Use a custom proxy handler. ### Method `custom(handler: ProxyCustomHandler)` ### Parameters #### Path Parameters - **handler** (ProxyCustomHandler) - Required - The custom proxy handler to use. ### Returns `Self` ``` -------------------------------- ### Stream Response Body Chunks Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/response.md Example of streaming an asynchronous response body using `ResponseBodyReader`. Shows iterating over chunks, reading all bytes at once with a limit, and reading chunk by chunk until EOF. ```python async with ClientBuilder().build() as client: response = await client.get("https://example.com/large-file").build().send() reader = await response.stream() # Stream chunks async for chunk in reader.stream(): print(f"Received chunk of {len(chunk)} bytes") # Or read all at once with limit all_bytes = await reader.bytes() # Or chunk by chunk while True: chunk = await reader.chunk() if chunk is None: break process(chunk) ``` -------------------------------- ### Content Metrics Overview Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/MANIFEST.md This section provides a summary of the documentation's content metrics, including lines of text, word count, number of code examples, tables, source references, and diagrams. ```text Total Lines: 4,500+ Total Words: 40,000+ Code Examples: 100+ Tables: 50+ Source References: All files located Diagrams: 2 (error hierarchy, module structure) ``` -------------------------------- ### Set Query Parameters with Multiple Values Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Shows how to provide multiple values for a single query parameter key. ```python # Multiple values .query({"tags": ["python", "http"]}) ``` -------------------------------- ### Set Custom Headers Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates how to set custom headers for an HTTP request using the `headers` method. ```python response = await client.get("/path") \ .headers({"X-Custom": "value"}) \ .build() \ .send() ``` -------------------------------- ### Multiple Responses Mocking Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/pytest-plugin.md Shows how to mock sequential responses for different requests, including matching headers for authentication. This is useful for testing multi-step workflows. ```python async def test_sequence(client_mocker: ClientMocker) -> None: mock1 = client_mocker.post(path="/login") \ .with_body_json({"token": "abc123"}) mock2 = client_mocker.get(path="/profile") \ .match_header("authorization", "Bearer abc123") \ .with_body_json({"name": "John"}) async with ClientBuilder().build() as client: # First request login_resp = await client.post("http://example.invalid/login").build().send() token = (await login_resp.json())["token"] # Second request with auth profile_resp = await client.get("http://example.invalid/profile") \ .bearer_auth(token) \ .build() \ .send() assert await profile_resp.json() == {"name": "John"} assert mock1.get_call_count() == 1 assert mock2.get_call_count() == 1 ``` -------------------------------- ### Custom JSON Dumps with Datetime Handling Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/types.md Example of a custom JSON dumps function that handles datetime objects by converting them to ISO format strings. This is useful when the default JSON encoder does not support specific types. ```python from pyreqwest.client.types import JsonDumps import json from datetime import datetime def dumps_with_datetime(ctx) -> bytes: def default(obj): if isinstance(obj, datetime): return obj.isoformat() raise TypeError return json.dumps(ctx.data, default=default).encode() async with ClientBuilder() \ .json_handler(dumps=dumps_with_datetime) \ .build() as client: response = await client.post("https://api.example.com") \ .body_json({"created": datetime.now()}) \ .build() \ .send() ``` -------------------------------- ### Catch Specific pyreqwest Errors Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/errors.md Catch specific pyreqwest exceptions to handle different error scenarios gracefully. This example shows how to differentiate between server errors, timeouts, connection issues, and general request failures. ```python from pyreqwest.exceptions import ( StatusError, RequestTimeoutError, ConnectError, RequestError, ) try: response = await client.get("https://api.example.com").build().send() except StatusError as e: print(f"Server error {e.details['status']}") except RequestTimeoutError: print("Request timed out") except ConnectError: print("Cannot connect to server") except RequestError as e: print(f"Request failed: {e.message}") ``` -------------------------------- ### Asynchronous Response Body Reader Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/response.md Provides methods for streaming an asynchronous response body. Use `bytes()` or `text()` with an optional limit, `chunk()` to read piece by piece, `json()` to parse, or `stream()` to get an async iterator over chunks. ```python class ResponseBodyReader: async def bytes(self, limit: int | None = None) -> bytes: ... async def chunk(self) -> bytes | None: ... async def text(self, limit: int | None = None) -> str: ... async def json(self) -> Any: ... def stream(self) -> AsyncIterable[bytes]: ... ``` -------------------------------- ### HTTP Utilities Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/INDEX.md Documentation for Url class with path/query manipulation, HeaderMap with case-insensitive access, Header view classes, and Mime type representation. ```APIDOC ## HTTP Utilities ### Description Documentation for the `Url` class with path/query manipulation, `HeaderMap` with case-insensitive access, header view classes, and MIME type representation. ### Modules - `api-reference/http-utils.md` ``` -------------------------------- ### Configure Default Cookie Store Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/QUICK_REFERENCE.md Enable the default cookie store by passing `True` to `default_cookie_store` in `ClientBuilder`. ```python from pyreqwest.cookie import CookieStore # Default cookie store async with ClientBuilder() \ .default_cookie_store(True) \ .build() as client: ... ``` -------------------------------- ### Configure Proxy for All Schemes with ProxyBuilder Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/proxy.md Use ProxyBuilder.all() to configure a proxy that applies to all request schemes (HTTP, HTTPS, etc.). ```python # Proxy for all schemes async with ClientBuilder() \ .proxy(ProxyBuilder.all("http://proxy.example.com:3128")) \ .build() as client: response = await client.get("https://api.example.com").build().send() ``` -------------------------------- ### Proxy Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/INDEX.md Details on ProxyBuilder static constructors, HTTP, HTTPS, SOCKS5 support, no-proxy hosts configuration, and URL format documentation. ```APIDOC ## Proxy ### Description Details on `ProxyBuilder` static constructors, support for HTTP, HTTPS, and SOCKS5 proxies, no-proxy hosts configuration, and URL format documentation. ### Modules - `api-reference/proxy.md` ``` -------------------------------- ### Configure HTTP Proxy with ProxyBuilder Source: https://github.com/markussintonen/pyreqwest/blob/main/_autodocs/api-reference/proxy.md Use ProxyBuilder.http() to configure an HTTP proxy for client requests. Ensure the proxy URL is correctly formatted. ```python from pyreqwest.client import ClientBuilder from pyreqwest.proxy import ProxyBuilder from pyreqwest.http import Url # HTTP proxy async with ClientBuilder() \ .proxy(ProxyBuilder.http("http://proxy.example.com:8080")) \ .build() as client: response = await client.get("https://api.example.com").build().send() ```