### Start Local Documentation Development Server Source: https://github.com/kap-sh/zapros/blob/main/CONTRIBUTING.md Run this command to start a local development server for building and previewing documentation. ```bash npm run docs:dev ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/kap-sh/zapros/blob/main/CONTRIBUTING.md Use this command to install all project dependencies, including extras, for development. ```bash uv sync --all-extras ``` -------------------------------- ### Install Zapros Source: https://github.com/kap-sh/zapros/blob/main/docs/quickstart.md Install the Zapros library using pip. ```bash pip install zapros ``` -------------------------------- ### Making Sync GET Request with Query Parameters Source: https://github.com/kap-sh/zapros/blob/main/docs/query-parameters.md Example of a synchronous GET request using Client, passing query parameters as a dictionary. The parameters are appended to the URL and URL-encoded. ```python from zapros import Client with Client() as client: response = client.get( "https://httpbin.org/get", params={ "q": "hello world", "page": "1", }, ) # Sends: GET /get?q=hello+world&page=1 ``` -------------------------------- ### Async Client Setup with RetryMiddleware Source: https://github.com/kap-sh/zapros/blob/main/docs/retries.md Initialize an asynchronous client with the RetryMiddleware wrapping an AsyncStdNetworkHandler for automatic retries. ```python from zapros import ( AsyncClient, RetryMiddleware, AsyncStdNetworkHandler, ) client = AsyncClient( handler=RetryMiddleware(AsyncStdNetworkHandler()) ) ``` -------------------------------- ### Send Request with Custom Headers (Sync) Source: https://github.com/kap-sh/zapros/blob/main/docs/models.md Example of making a synchronous GET request with custom Authorization and Accept headers. ```python from zapros import Client with Client() as client: response = client.get( "https://api.example.com/data", headers={ "Authorization": "Bearer token", "Accept": "application/json", }, ) ``` -------------------------------- ### Install Zapros with WebSocket Support Source: https://github.com/kap-sh/zapros/blob/main/docs/websockets.md Install Zapros with the optional 'wsproto' dependency to enable WebSocket functionality. ```bash pip install zapros[websocket] ``` -------------------------------- ### Setup Async Client with CacheMiddleware Source: https://github.com/kap-sh/zapros/blob/main/docs/caching.md Configure an asynchronous Zapros client with the CacheMiddleware wrapping an AsyncStdNetworkHandler. ```python from zapros import ( AsyncClient, CacheMiddleware, AsyncStdNetworkHandler, ) client = AsyncClient( handler=CacheMiddleware(AsyncStdNetworkHandler()) ) ``` -------------------------------- ### Send Request with Custom Headers (Async) Source: https://github.com/kap-sh/zapros/blob/main/docs/models.md Example of making an asynchronous GET request with custom Authorization and Accept headers. ```python from zapros import AsyncClient async with AsyncClient() as client: response = await client.get( "https://api.example.com/data", headers={ "Authorization": "Bearer token", "Accept": "application/json", }, ) ``` -------------------------------- ### Sync Client Setup with RetryMiddleware Source: https://github.com/kap-sh/zapros/blob/main/docs/retries.md Initialize a synchronous client with the RetryMiddleware wrapping a StdNetworkHandler for automatic retries. ```python from zapros import ( Client, RetryMiddleware, StdNetworkHandler, ) client = Client(handler=RetryMiddleware(StdNetworkHandler())) ``` -------------------------------- ### Making Async GET Request with Query Parameters Source: https://github.com/kap-sh/zapros/blob/main/docs/query-parameters.md Example of an asynchronous GET request using AsyncClient, passing query parameters as a dictionary. The parameters are appended to the URL and URL-encoded. ```python from zapros import AsyncClient async with AsyncClient() as client: response = await client.get( "https://httpbin.org/get", params={ "q": "hello world", "page": "1", }, ) # Sends: GET /get?q=hello+world&page=1 ``` -------------------------------- ### Install Zapros with SOCKS5 Proxy Support Source: https://github.com/kap-sh/zapros/blob/main/docs/python-std.md Installs the Zapros library with the necessary dependencies to enable SOCKS5 proxy support. This is required before configuring or using SOCKS5 proxies. ```bash pip install zapros[socks] ``` -------------------------------- ### Setup Sync Client with CacheMiddleware Source: https://github.com/kap-sh/zapros/blob/main/docs/caching.md Configure a synchronous Zapros client with the CacheMiddleware wrapping a StdNetworkHandler. ```python from zapros import ( Client, CacheMiddleware, StdNetworkHandler, ) client = Client(handler=CacheMiddleware(StdNetworkHandler())) ``` -------------------------------- ### Async Timing Middleware Example Source: https://github.com/kap-sh/zapros/blob/main/docs/handlers.md Implement `AsyncBaseMiddleware` to add timing logic before and after an asynchronous handler call. This example measures and prints the request duration. ```python from typing import cast from zapros import ( AsyncBaseHandler, AsyncBaseMiddleware, AsyncClient, Request, Response, StdNetworkHandler, ) class TimingMiddleware(AsyncBaseMiddleware): def __init__( self, next_handler: AsyncBaseHandler, ) -> None: self.async_next = next_handler async def ahandle(self, request: Request) -> Response: import time start = time.perf_counter() response = await self.async_next.ahandle(request) elapsed = time.perf_counter() - start print( f"{request.method} {request.url} → {response.status} ({elapsed:.3f}s)" ) return response async with AsyncClient( handler=TimingMiddleware(StdNetworkHandler()) ) as client: response = await client.get( "https://api.example.com/users", ) ``` -------------------------------- ### Async MockRouter Example Source: https://github.com/kap-sh/zapros/blob/main/docs/mocking.md Demonstrates how to set up and use MockRouter with an asynchronous client. Import necessary modules and define mocks using Mock.given and Response. Then, create an AsyncClient with MockMiddleware to handle requests. ```python import asyncio from zapros import AsyncClient, Response from zapros.mock import ( Mock, MockMiddleware, MockRouter, ) from zapros.matchers import path router = MockRouter() router.add( Mock.given(path("/health")).respond( Response(status=200) ) ) router.add( Mock.given(path("/status")).respond( Response(status=204) ) ) async def main(): async with AsyncClient( handler=MockMiddleware(router) ) as client: assert ( await client.get( "https://api.example.com/health", ) ).status == 200 assert ( await client.get( "https://api.example.com/status", ) ).status == 204 asyncio.run(main()) ``` -------------------------------- ### Sync Test API with MockMiddleware Source: https://github.com/kap-sh/zapros/blob/main/docs/mocking.md Set up and run a synchronous test using `Client` and `MockMiddleware`. This example shows how to define a mock and verify the client's response. ```python from zapros import Client, Response from zapros.mock import ( Mock, MockMiddleware, MockRouter, ) from zapros.matchers import path def test_api(): router = MockRouter() router.add( Mock .given(path("/users").method("GET")) .respond(Response(status=200, json=[])) .once() ) with Client(handler=MockMiddleware(router)) as client: response = client.get( "https://example.com/users", ) assert response.status == 200 ``` -------------------------------- ### Install Zapros with Caching Feature Source: https://github.com/kap-sh/zapros/blob/main/docs/caching.md Install Zapros including the caching optional feature using pip. ```bash pip install zapros[caching] ``` -------------------------------- ### Install Zapros with pyreqwest Source: https://github.com/kap-sh/zapros/blob/main/docs/rust.md Install zapros with the pyreqwest feature enabled to utilize Rust's reqwest library. ```bash pip install zapros[pyreqwest] ``` -------------------------------- ### Synchronous Timing Middleware Example Source: https://github.com/kap-sh/zapros/blob/main/docs/handlers.md Implement `BaseMiddleware` to add timing logic before and after a synchronous handler call. This example measures and prints the request duration. ```python from typing import cast from zapros import ( BaseHandler, BaseMiddleware, Client, Request, Response, StdNetworkHandler, ) class TimingMiddleware(BaseMiddleware): def __init__(self, next_handler: BaseHandler) -> None: self.next = next_handler def handle(self, request: Request) -> Response: import time start = time.perf_counter() response = self.next.handle(request) elapsed = time.perf_counter() - start print( f"{request.method} {request.url} → {response.status} ({elapsed:.3f}s)" ) return response with Client( handler=TimingMiddleware(StdNetworkHandler()) ) as client: response = client.get( "https://api.example.com/users", ) ``` -------------------------------- ### Async HTTP Cassette Quickstart Source: https://github.com/kap-sh/zapros/blob/main/docs/cassettes.md Record an HTTP interaction once and replay it without network access using an asynchronous client. The first run writes to 'cassettes/github_api.json', subsequent runs replay from disk. ```python import asyncio from zapros import ( AsyncClient, AsyncStdNetworkHandler, ) from zapros import CassetteMiddleware async def main(): handler = CassetteMiddleware( AsyncStdNetworkHandler(), cassette_name="github_api", ) async with AsyncClient(handler=handler) as client: response = await client.get( "https://api.github.com/users/octocat", ) print(response.json) asyncio.run(main()) ``` -------------------------------- ### Custom Matcher Implementation Source: https://github.com/kap-sh/zapros/blob/main/docs/matchers.md Create custom matchers by implementing the Matcher protocol with a `match` method. This example defines a matcher that checks if a request's URL pathname starts with a given prefix. ```python from pywhatwgurl import URL from zapros import Request from zapros.matchers import Matcher class PathPrefixMatcher(Matcher): def __init__(self, prefix: str) -> None: self._prefix = prefix def match(self, request: Request) -> bool: return request.url.pathname.startswith(self._prefix) matcher = PathPrefixMatcher("/api/v1") request = Request(URL("https://api.example.com/api/v1/users"), "GET") assert matcher.match(request) == True request = Request(URL("https://api.example.com/api/v2/users"), "GET") assert matcher.match(request) == False ``` -------------------------------- ### Making Sync GET Request with URL Object Source: https://github.com/kap-sh/zapros/blob/main/docs/query-parameters.md Example of a synchronous GET request where the URL, including query parameters, is constructed using the URL object and then passed to the client. ```python from zapros import Client, URL url = URL("https://api.example.com/users") url.search_params["page"] = "2" with Client() as client: response = client.get(url) ``` -------------------------------- ### Sync HTTP Cassette Quickstart Source: https://github.com/kap-sh/zapros/blob/main/docs/cassettes.md Record an HTTP interaction once and replay it without network access using a synchronous client. The first run writes to 'cassettes/github_api.json', subsequent runs replay from disk. ```python from zapros import ( Client, StdNetworkHandler, ) from zapros import CassetteMiddleware handler = CassetteMiddleware( StdNetworkHandler(), cassette_name="github_api", ) with Client(handler=handler) as client: response = client.get( "https://api.github.com/users/octocat", ) print(response.json) ``` -------------------------------- ### Make a Basic Sync Request Source: https://github.com/kap-sh/zapros/blob/main/docs/quickstart.md Use the Client for synchronous HTTP GET requests. Ensure to close the client after use. ```python from zapros import Client with Client() as client: response = client.get( "https://httpbin.org/get", ) print(response.status) print(response.headers["content-type"]) print(response.text) ``` -------------------------------- ### Get HTTP Response (Sync) Source: https://github.com/kap-sh/zapros/blob/main/docs/models.md Use Client for synchronous HTTP GET requests. Ensure to use `with` for proper client management. ```python from zapros import Client with Client() as client: response = client.get("https://httpbin.org/get") print(response.status) # 200 print( response.headers["content-type"] ) # "application/json" ``` -------------------------------- ### Async Test API with MockMiddleware Source: https://github.com/kap-sh/zapros/blob/main/docs/mocking.md Set up and run an asynchronous test using `AsyncClient` and `MockMiddleware`. This example demonstrates adding a mock expectation and asserting a successful response. ```python import asyncio from zapros import AsyncClient, Response from zapros.mock import ( Mock, MockMiddleware, MockRouter, ) from zapros.matchers import path async def test_api(): router = MockRouter() router.add( Mock .given(path("/users").method("GET")) .respond(Response(status=200, json=[])) .once() ) async with AsyncClient( handler=MockMiddleware(router) ) as client: response = await client.get( "https://example.com/users", ) assert response.status == 200 asyncio.run(test_api()) ``` -------------------------------- ### Making Async GET Request with URL Object Source: https://github.com/kap-sh/zapros/blob/main/docs/query-parameters.md Example of an asynchronous GET request where the URL, including query parameters, is constructed using the URL object and then passed to the client. ```python from zapros import AsyncClient, URL url = URL("https://api.example.com/users") url.search_params["page"] = "2" async with AsyncClient() as client: response = await client.get(url) ``` -------------------------------- ### Sync MockRouter Example Source: https://github.com/kap-sh/zapros/blob/main/docs/mocking.md Illustrates the usage of MockRouter with a synchronous client. Similar to the async version, define mocks and then create a synchronous Client with MockMiddleware to intercept and respond to requests. ```python from zapros import Client, Response from zapros.mock import ( Mock, MockMiddleware, MockRouter, ) from zapros.matchers import path router = MockRouter() router.add( Mock.given(path("/health")).respond( Response(status=200) ) ) router.add( Mock.given(path("/status")).respond( Response(status=204) ) ) with Client(handler=MockMiddleware(router)) as client: assert ( client.get( "https://api.example.com/health", ).status == 200 ) assert ( client.get( "https://api.example.com/status", ).status == 204 ) ``` -------------------------------- ### Async Client Setup with Cookie Middleware Source: https://github.com/kap-sh/zapros/blob/main/docs/cookies.md Sets up an asynchronous Zapros client with the CookieMiddleware. This is used for automatically handling cookies in asynchronous operations. ```python from zapros import ( AsyncClient, CookieMiddleware, AsyncStdNetworkHandler, ) client = AsyncClient( handler=CookieMiddleware(AsyncStdNetworkHandler()) ) ``` -------------------------------- ### Basic Browser Request with Zapros Source: https://github.com/kap-sh/zapros/blob/main/docs/browser.md Create an AsyncClient and make a GET request to a CORS-free endpoint. Top-level await is supported in Pyodide. ```python import zapros async with zapros.AsyncClient() as client: # make a request to a CORS-free endpoint response = await client.get("https://httpbin.org/get") print(response.json) ``` -------------------------------- ### Sync Client Setup with Cookie Middleware Source: https://github.com/kap-sh/zapros/blob/main/docs/cookies.md Sets up a synchronous Zapros client with the CookieMiddleware. This is used for automatically handling cookies in synchronous operations. ```python from zapros import ( Client, CookieMiddleware, StdNetworkHandler, ) client = Client(handler=CookieMiddleware(StdNetworkHandler())) ``` -------------------------------- ### Get HTTP Response (Async) Source: https://github.com/kap-sh/zapros/blob/main/docs/models.md Use AsyncClient for asynchronous HTTP GET requests. Ensure to use `async with` for proper client management. ```python from zapros import AsyncClient async with AsyncClient() as client: response = await client.get("https://httpbin.org/get") print(response.status) # 200 print( response.headers["content-type"] ) # "application/json" ``` -------------------------------- ### Enable HTTP/2 Auto-Negotiation Source: https://github.com/kap-sh/zapros/blob/main/docs/python-std.md Shows how to enable HTTP/2 support for both asynchronous and synchronous clients using standard library handlers. Ensure Zapros is installed with the 'http2' feature. ```python from zapros import AsyncClient, AsyncStdNetworkHandler async with AsyncClient( handler=AsyncStdNetworkHandler(http2=True) ) as client: response = await client.get("https://api.example.com/data") print(response) # ``` ```python from zapros import Client, StdNetworkHandler async with Client( handler=StdNetworkHandler(http2=True) ) as client: response = client.get("https://api.example.com/data") print(response) # ``` -------------------------------- ### Basic GET Request Source: https://github.com/kap-sh/zapros/blob/main/docs/get-requests.md Perform a basic GET request to a specified URL. Use AsyncClient for asynchronous operations and Client for synchronous operations. Ensure the client is properly initialized and closed. ```python import asyncio from zapros import AsyncClient async def main(): async with AsyncClient() as client: response = await client.get( "https://httpbin.org/get", ) print(response.status) asyncio.run(main()) ``` ```python from zapros import Client with Client() as client: response = client.get("https://httpbin.org/get") print(response.status) ``` -------------------------------- ### Basic Async Usage with Caching Source: https://github.com/kap-sh/zapros/blob/main/docs/caching.md Perform an asynchronous GET request using a client configured with CacheMiddleware. The response context will indicate caching status. ```python from zapros import ( AsyncClient, CacheMiddleware, AsyncStdNetworkHandler, ) client = AsyncClient( handler=CacheMiddleware(AsyncStdNetworkHandler()) ) async with client: response = await client.get( "https://api.example.com/data", ) print(response.status) print(response.context.get("caching")) ``` -------------------------------- ### Basic Sync Usage with Caching Source: https://github.com/kap-sh/zapros/blob/main/docs/caching.md Perform a synchronous GET request using a client configured with CacheMiddleware. The response context will indicate caching status. ```python from zapros import ( Client, CacheMiddleware, StdNetworkHandler, ) client = Client(handler=CacheMiddleware(StdNetworkHandler())) with client: response = client.get( "https://api.example.com/data", ) print(response.status) print(response.context.get("caching")) ``` -------------------------------- ### Make a Basic Async Request Source: https://github.com/kap-sh/zapros/blob/main/docs/quickstart.md Use AsyncClient for asynchronous HTTP GET requests. Ensure to close the client after use. ```python import asyncio from zapros import AsyncClient async def main(): async with AsyncClient() as client: response = await client.get( "https://httpbin.org/get", ) print(response.status) print(response.headers["content-type"]) print(response.text) asyncio.run(main()) ``` -------------------------------- ### Parameter Priority in Async Requests Source: https://github.com/kap-sh/zapros/blob/main/docs/query-parameters.md Illustrates how query parameters from different sources (default_params, URL string, params argument) are merged, with higher priority sources overwriting lower ones. This example uses an asynchronous client. ```python async with AsyncClient( default_params={"version": "1"} ) as client: response = await client.get( "https://api.example.com/search?lang=en", params={"q": "zapros"}, ) # Sends: GET /search?version=1&lang=en&q=zapros ``` -------------------------------- ### Parameter Priority in Sync Requests Source: https://github.com/kap-sh/zapros/blob/main/docs/query-parameters.md Illustrates how query parameters from different sources (default_params, URL string, params argument) are merged, with higher priority sources overwriting lower ones. This example uses a synchronous client. ```python with Client(default_params={"version": "1"}) as client: response = client.get( "https://api.example.com/search?lang=en", params={"q": "zapros"}, ) # Sends: GET /search?version=1&lang=en&q=zapros ``` -------------------------------- ### Redirects with 303 See Other (Method Conversion to GET) Source: https://github.com/kap-sh/zapros/blob/main/docs/redirects.md When a 303 See Other redirect occurs, all methods are converted to GET, except HEAD which remains HEAD. This example demonstrates a POST request being converted to GET. ```python import asyncio from zapros import ( AsyncClient, RedirectMiddleware, AsyncStdNetworkHandler, ) async def main(): handler = RedirectMiddleware(AsyncStdNetworkHandler()) async with AsyncClient(handler=handler) as client: response = await client.post( "https://api.example.com/submit", json={"data": "value"}, ) print(response.status) # 200 asyncio.run(main()) ``` ```python from zapros import ( Client, RedirectMiddleware, StdNetworkHandler, ) handler = RedirectMiddleware(StdNetworkHandler()) with Client(handler=handler) as client: response = client.post( "https://api.example.com/submit", json={"data": "value"}, ) print(response.status) # 200 ``` -------------------------------- ### Build Documentation Source: https://github.com/kap-sh/zapros/blob/main/CONTRIBUTING.md Use this command to generate a production build of the documentation. ```bash npm run docs:build ``` -------------------------------- ### Transform Request Keys (Sync) Source: https://github.com/kap-sh/zapros/blob/main/docs/cassettes.md Use `map_network_request` with a modifier function to transform the request before it becomes a cassette key. This example strips query parameters from requests targeting '/api'. ```python from zapros import Client, Request from zapros import ( CassetteMiddleware, CassetteMode, ModifierRouter, ) from zapros.mock import Mock, MockMiddleware from zapros.matchers import path mock_middleware = MockMiddleware() mock_middleware.router.add( Mock.given(path("/api")).respond(status=200, text="ok") ) modifier_router = ModifierRouter() def strip_query( req: Request, ) -> Request: return Request( req.url.without_query(), req.method, ) modifier_router.modifier(path("/api")).map_network_request(strip_query) handler = CassetteMiddleware( mock_middleware, router=modifier_router, mode=CassetteMode.ALL, cassette_name="test", ) with Client(handler=handler) as client: client.get( "https://api.example.com/api?token=secret123", ) ``` -------------------------------- ### Custom Async Cookie Handling Middleware Source: https://github.com/kap-sh/zapros/blob/main/docs/cookies.md Provides an example of a custom asynchronous middleware for handling cookies with custom logic, such as adding signed cookie values. This middleware must implement the AsyncBaseMiddleware protocol. ```python from zapros import ( AsyncBaseMiddleware, Request, Response, ) class MyCookieMiddleware(AsyncBaseMiddleware, BaseMiddleware): def __init__(self, handler): self._handler = handler async def ahandle(self, request: Request) -> Response: request.headers.add( "Cookie", "mycookie=signedvalue", ) return await self._handler.ahandle(request) def handle(self, request: Request) -> Response: request.headers.add( "Cookie", "mycookie=signedvalue", ) return self._handler.handle(request) ``` -------------------------------- ### Transform Request Keys (Async) Source: https://github.com/kap-sh/zapros/blob/main/docs/cassettes.md Use `map_network_request` with a modifier function to transform the request before it becomes a cassette key. This example strips query parameters from requests targeting '/api'. ```python import asyncio from zapros import AsyncClient, Request from zapros import ( CassetteMiddleware, CassetteMode, ModifierRouter, ) from zapros.mock import Mock, MockMiddleware from zapros.matchers import path async def main(): mock_middleware = MockMiddleware() mock_middleware.router.add( Mock.given(path("/api")).respond(status=200, text="ok") ) modifier_router = ModifierRouter() def strip_query( req: Request, ) -> Request: return Request( req.url.without_query(), req.method, ) modifier_router.modifier(path("/api")).map_network_request(strip_query) handler = CassetteMiddleware( mock_middleware, router=modifier_router, mode=CassetteMode.ALL, cassette_name="test", ) async with AsyncClient(handler=handler) as client: await client.get( "https://api.example.com/api?token=secret123", ) asyncio.run(main()) ``` -------------------------------- ### Fluent API for Request Matching Source: https://github.com/kap-sh/zapros/blob/main/docs/matchers.md Chain multiple matchers using a fluent API to define complex request matching criteria. This example demonstrates matching a POST request to a specific path with a JSON content type header. ```python from pywhatwgurl import URL from zapros import Request from zapros.matchers import path matcher = ( path("/api/users") .method("POST") .header("content-type", "application/json") ) request = Request( URL("https://api.example.com/api/users"), "POST", headers={"content-type": "application/json"}, ) assert matcher.match(request) == True ``` -------------------------------- ### Sync Client with FilterPolicy Source: https://github.com/kap-sh/zapros/blob/main/docs/caching.md Sets up a synchronous Zapros client using FilterPolicy to cache responses that pass custom request and response filters. Demonstrates basic usage with a GET request to an example API. ```python from hishel import FilterPolicy from zapros import ( Client, CacheMiddleware, StdNetworkHandler, ) client = Client( handler=CacheMiddleware( StdNetworkHandler(), policy=FilterPolicy(), ) ) with client: response = client.get( "https://api.example.com/data", ) ``` -------------------------------- ### Async Client with FilterPolicy Source: https://github.com/kap-sh/zapros/blob/main/docs/caching.md Sets up an asynchronous Zapros client using FilterPolicy to cache responses that pass custom request and response filters. Demonstrates basic usage with a GET request to an example API. ```python from hishel import FilterPolicy from zapros import ( AsyncClient, CacheMiddleware, AsyncStdNetworkHandler, ) client = AsyncClient( handler=CacheMiddleware( AsyncStdNetworkHandler(), policy=FilterPolicy(), ) ) async with client: response = await client.get( "https://api.example.com/data", ) ``` -------------------------------- ### Basic Client Usage Source: https://github.com/kap-sh/zapros/blob/main/docs/python-std.md Demonstrates the basic usage of asynchronous and synchronous clients with their default standard library handlers. ```python from zapros import AsyncClient async with AsyncClient() as client: response = await client.get("https://api.example.com/data") print(response.text) ``` ```python from zapros import Client with Client() as client: response = client.get("https://api.example.com/data") print(response.text) ``` -------------------------------- ### Preview Production Documentation Build Source: https://github.com/kap-sh/zapros/blob/main/CONTRIBUTING.md This command allows you to preview the production build of the documentation locally. ```bash npm run docs:preview ``` -------------------------------- ### Configure HTTP/1 Options Source: https://github.com/kap-sh/zapros/blob/main/docs/python-std.md Demonstrates how to pass a dictionary of HTTP/1-specific configuration options, such as 'max_connections_per_host', to the standard library handlers. ```python from zapros import AsyncClient, AsyncStdNetworkHandler async with AsyncClient( handler=AsyncStdNetworkHandler(http1={"max_connections_per_host": 10}) ) as client: response = await client.get("https://api.example.com/data") print(response) # ``` ```python from zapros import Client, StdNetworkHandler with Client( handler=StdNetworkHandler(http1={"max_connections_per_host": 10}) ) as client: response = client.get("https://api.example.com/data") print(response) # ``` -------------------------------- ### Configuring AsgiHandler Timeouts Source: https://github.com/kap-sh/zapros/blob/main/docs/asgi.md Shows how to adjust startup and shutdown timeouts for the AsgiHandler to handle applications with longer initialization periods. Set to None for no timeout. ```python from zapros import AsgiHandler handler = AsgiHandler( app, startup_timeout=30.0, shutdown_timeout=5.0, ) ``` -------------------------------- ### Reading GET Response Details Source: https://github.com/kap-sh/zapros/blob/main/docs/get-requests.md Access the response status code, headers, and body text after making a GET request. The `response.text` attribute provides the response body as a string. ```python async with AsyncClient() as client: response = await client.get("https://httpbin.org/get") print(response.status) # 200 print( response.headers["content-type"] ) # application/json print(response.text) # response body as string ``` ```python with Client() as client: response = client.get("https://httpbin.org/get") print(response.status) # 200 print( response.headers["content-type"] ) # application/json print(response.text) # response body as string ``` -------------------------------- ### GET Request with Query Parameters Source: https://github.com/kap-sh/zapros/blob/main/docs/get-requests.md Append query parameters to a GET request URL using the `params` dictionary. If the URL already has parameters, they are merged. Duplicate keys are preserved. ```python async with AsyncClient() as client: response = await client.get( "https://httpbin.org/get", params={ "search": "python", "page": "1", }, ) ``` ```python with Client() as client: response = client.get( "https://httpbin.org/get", params={ "search": "python", "page": "1", }, ) ``` -------------------------------- ### AsgiHandler Configuration Options Source: https://github.com/kap-sh/zapros/blob/main/docs/asgi.md Illustrates various configuration parameters for the AsgiHandler, including client address, root path, HTTP version, and lifespan settings. ```python handler = AsgiHandler( app, client=( "127.0.0.1", 123, ), # Client address tuple (host, port) root_path="", # ASGI root_path for the application http_version="1.1", # HTTP protocol version enable_lifespan=True, # Enable ASGI lifespan protocol startup_timeout=10.0, # Timeout for lifespan startup (seconds) shutdown_timeout=10.0, # Timeout for lifespan shutdown (seconds) ) ``` -------------------------------- ### Redirects with 301/302 (POST to GET, others preserved) Source: https://github.com/kap-sh/zapros/blob/main/docs/redirects.md For 301 Moved Permanently and 302 Found redirects, only POST requests are converted to GET. Other methods like PUT, PATCH, and DELETE are preserved. ```python import asyncio from zapros import ( AsyncClient, RedirectMiddleware, AsyncStdNetworkHandler, ) async def main(): handler = RedirectMiddleware(AsyncStdNetworkHandler()) async with AsyncClient(handler=handler) as client: post_response = await client.post( "https://api.example.com/old", json={}, ) delete_response = await client.delete( "https://api.example.com/old", ) asyncio.run(main()) ``` ```python from zapros import ( Client, RedirectMiddleware, StdNetworkHandler, ) handler = RedirectMiddleware(StdNetworkHandler()) with Client(handler=handler) as client: post_response = client.post( "https://api.example.com/old", json={}, ) delete_response = client.delete( "https://api.example.com/old", ) ``` -------------------------------- ### Custom SSL Context with Sync Client Source: https://github.com/kap-sh/zapros/blob/main/docs/python-std.md Set up a custom SSL context for secure synchronous communication. The 'ssl' module must be imported. ```python import ssl from zapros import Client, StdNetworkHandler, SyncTransport custom_ssl_context = ssl.create_default_context() with Client( handler=StdNetworkHandler( transport=SyncTransport(ssl_context=custom_ssl_context) ) ) as client: ... ``` -------------------------------- ### AsgiHandler Usage with Trio Source: https://github.com/kap-sh/zapros/blob/main/docs/asgi.md Demonstrates how to use AsgiHandler with Trio, emphasizing the requirement to use it as an async context manager within a Trio nursery for proper lifespan management. ```python import trio from litestar import Litestar, get from zapros import AsyncClient from zapros import AsgiHandler @get("/hello") async def hello() -> dict: return {"message": "Hello, World!"} app = Litestar(route_handlers=[hello]) async def main(): async with AsgiHandler(app) as handler: async with AsyncClient(handler=handler) as client: response = await client.get("http://testserver/hello") print(response.json) trio.run(main) ``` -------------------------------- ### Configure Maximum Redirects Source: https://github.com/kap-sh/zapros/blob/main/docs/redirects.md Control the maximum number of redirects to follow by setting the `max_redirects` parameter in RedirectMiddleware. This example sets it to 5. ```python import asyncio from zapros import ( AsyncClient, RedirectMiddleware, AsyncStdNetworkHandler, ) async def main(): base_handler = AsyncStdNetworkHandler() handler = RedirectMiddleware(base_handler, max_redirects=5) async with AsyncClient(handler=handler) as client: response = await client.get( "https://api.example.com/many-redirects", ) if response.status in { 301, 302, 303, 307, 308, }: print("Stopped at redirect limit") asyncio.run(main()) ``` ```python from zapros import ( Client, RedirectMiddleware, StdNetworkHandler, ) base_handler = StdNetworkHandler() handler = RedirectMiddleware(base_handler, max_redirects=5) with Client(handler=handler) as client: response = client.get( "https://api.example.com/many-redirects", ) if response.status in { 301, 302, 303, 307, 308, }: print("Stopped at redirect limit") ``` -------------------------------- ### Create and Access Headers Source: https://github.com/kap-sh/zapros/blob/main/docs/models.md Demonstrates creating a Headers object and accessing its elements with case-insensitivity and default values. ```python from zapros import Headers headers = Headers({"Content-Type": "application/json"}) headers["content-type"] # Works (case-insensitive) headers["CONTENT-TYPE"] # Also works headers.get("Accept", "*/*") # With default "Accept" in headers # True len(headers) # Number of unique headers ``` -------------------------------- ### Dynamic Responses with Callback (Sync) Source: https://github.com/kap-sh/zapros/blob/main/docs/mocking.md Utilize a callback function with MockMiddleware for dynamic response generation in a synchronous client. The callback logic can handle different request conditions to return appropriate responses. ```python from zapros import Client, Response from zapros.mock import ( Mock, MockMiddleware, MockRouter, ) from zapros.matchers import method router = MockRouter() def handler(req): if req.url.pathname == "/notfound": return Response(status=404) return Response(status=200) router.add(Mock.given(method("GET")).callback(handler)) with Client(handler=MockMiddleware(router)) as client: assert ( client.get( "https://api.example.com/notfound", ).status == 404 ) assert ( client.get( "https://api.example.com/anything", ).status == 200 ) ``` -------------------------------- ### Initialize URL Object Source: https://github.com/kap-sh/zapros/blob/main/docs/urls.md Import the URL class from zapros and create a new URL object with a given string. ```python from zapros import URL url = URL("https://api.example.com/users") ``` -------------------------------- ### Transform Response Data Source: https://github.com/kap-sh/zapros/blob/main/docs/cassettes.md Use `map_network_response` with a modifier function to transform the response before it is saved to the cassette. This example removes the 'set-cookie' header from recorded responses. ```python from zapros import Response def redact_headers( resp: Response, ) -> Response: headers = dict(resp.headers) headers.pop("set-cookie", None) return Response( status=resp.status, headers=headers, content=resp.read(), ) router.modifier(path("/login")).map_network_response(redact_headers) ``` -------------------------------- ### Basic Sync Usage with PyreqwestHandler Source: https://github.com/kap-sh/zapros/blob/main/docs/rust.md Demonstrates how to use PyreqwestHandler with Zapros's Client for making synchronous HTTP requests. ```python from pyreqwest.client import SyncClientBuilder from zapros import Client, PyreqwestHandler with Client(handler=PyreqwestHandler()) as client: response = client.get("https://api.example.com/users") print(response.status) print(response.text) ``` -------------------------------- ### Async Basic Usage with Cookie Middleware Source: https://github.com/kap-sh/zapros/blob/main/docs/cookies.md Demonstrates basic usage of an asynchronous client with CookieMiddleware. Cookies are automatically stored after the login request and sent with the profile request. ```python from zapros import ( AsyncClient, CookieMiddleware, AsyncStdNetworkHandler, ) client = AsyncClient( handler=CookieMiddleware(AsyncStdNetworkHandler()) ) async with client: await client.get( "https://api.example.com/login", ) # session cookie stored response = await client.get( "https://api.example.com/profile", ) # session cookie sent automatically ``` -------------------------------- ### Override Proxy Per Request Source: https://github.com/kap-sh/zapros/blob/main/docs/python-std.md Specifies a custom proxy URL for a single asynchronous GET request. This allows overriding environment or handler-level proxy settings for specific requests. ```python response = await client.get( "https://api.example.com/data", context={ "network": { "proxy": { "url": "http://special-proxy.example.com:8080" } } }, ) ``` -------------------------------- ### Handle Multi-value Headers Source: https://github.com/kap-sh/zapros/blob/main/docs/models.md Illustrates how to add and retrieve multiple values for the same header, such as 'Set-Cookie'. ```python headers = Headers() headers.add("Set-Cookie", "session=abc") headers.add("Set-Cookie", "user=john") headers["Set-Cookie"] # "session=abc" (first value) headers.getall("Set-Cookie") # ["session=abc", "user=john"] ``` -------------------------------- ### Override Timeouts Per Request Source: https://github.com/kap-sh/zapros/blob/main/docs/python-std.md Overrides the default total and read timeouts for a specific asynchronous GET request. This allows for fine-grained control over network behavior for individual requests. ```python response = await client.get( "https://api.example.com/data", context={ "timeouts": { "total": 15.0, "read": 5.0, } }, ) ``` -------------------------------- ### Dynamic Responses with Callback (Async) Source: https://github.com/kap-sh/zapros/blob/main/docs/mocking.md Implement dynamic response generation for an asynchronous client using a callback function within MockMiddleware. The callback determines the response based on request details like the URL path. ```python import asyncio from zapros import AsyncClient, Response from zapros.mock import ( Mock, MockMiddleware, MockRouter, ) from zapros.matchers import method router = MockRouter() def handler(req): if req.url.pathname == "/notfound": return Response(status=404) return Response(status=200) router.add(Mock.given(method("GET")).callback(handler)) async def main(): async with AsyncClient( handler=MockMiddleware(router) ) as client: assert ( await client.get( "https://api.example.com/notfound", ) ).status == 404 assert ( await client.get( "https://api.example.com/anything", ) ).status == 200 asyncio.run(main()) ``` -------------------------------- ### Use URL with AsyncClient Source: https://github.com/kap-sh/zapros/blob/main/docs/urls.md Integrate Zapros's URL class with AsyncClient for making asynchronous HTTP GET requests. Ensure the URL is converted to a string before passing to the client. ```python from zapros import AsyncClient, URL url = URL("https://api.example.com/users") url.search_params["page"] = "1" async with AsyncClient() as client: response = await client.get(url.to_string()) ``` -------------------------------- ### Basic Sync Request with Retries Source: https://github.com/kap-sh/zapros/blob/main/docs/retries.md Perform a synchronous GET request using a client configured with RetryMiddleware. The middleware will automatically retry on specific status codes or network errors. ```python from zapros import ( Client, RetryMiddleware, StdNetworkHandler, ) client = Client(handler=RetryMiddleware(StdNetworkHandler())) with client: response = client.get( "https://api.example.com/data", ) ``` -------------------------------- ### Configure Async Standard Network Handler with Proxy Middleware Source: https://github.com/kap-sh/zapros/blob/main/docs/python-std.md Initializes an asynchronous client with a standard network handler wrapped in ProxyMiddleware. This enables proxy support for all outgoing requests. ```python from zapros import AsyncClient, AsyncStdNetworkHandler, ProxyMiddleware client = AsyncClient( handler=ProxyMiddleware(AsyncStdNetworkHandler()) ) ``` -------------------------------- ### Basic Async Request with Retries Source: https://github.com/kap-sh/zapros/blob/main/docs/retries.md Perform an asynchronous GET request using a client configured with RetryMiddleware. The middleware will automatically retry on specific status codes or network errors. ```python from zapros import ( AsyncClient, RetryMiddleware, AsyncStdNetworkHandler, ) client = AsyncClient( handler=RetryMiddleware(AsyncStdNetworkHandler()) ) async with client: response = await client.get( "https://api.example.com/data", ) ``` -------------------------------- ### Basic Async Usage with PyreqwestHandler Source: https://github.com/kap-sh/zapros/blob/main/docs/rust.md Demonstrates how to use AsyncPyreqwestHandler with Zapros's AsyncClient for making asynchronous HTTP requests. ```python from pyreqwest.client import ClientBuilder from zapros import AsyncClient, AsyncPyreqwestHandler async with AsyncClient(handler=AsyncPyreqwestHandler()) as client: response = await client.get("https://api.example.com/users") print(response.status) print(response.text) ``` -------------------------------- ### Configure Sync Standard Network Handler with Proxy Middleware Source: https://github.com/kap-sh/zapros/blob/main/docs/python-std.md Initializes a synchronous client with a standard network handler wrapped in ProxyMiddleware. This enables proxy support for all outgoing requests. ```python from zapros import Client, ProxyMiddleware, StdNetworkHandler client = Client( handler=ProxyMiddleware(StdNetworkHandler()) ) ``` -------------------------------- ### Incorrect Async Client Usage with Sync Multipart Stream Source: https://github.com/kap-sh/zapros/blob/main/docs/guide/async-sync.md This example demonstrates incorrect usage that raises an AsyncSyncMismatchError. An async client is used with a synchronous multipart stream, which is not compatible. ```python from zapros import AsyncClient, Multipart, Part client = AsyncClient() async def main(): await client.get( "https://httpbin.org/get", multipart=Multipart().part( "test", Part.stream(iter([])) ), ) ``` -------------------------------- ### Sync Client with Custom Request and Response Filters Source: https://github.com/kap-sh/zapros/blob/main/docs/caching.md Configures a synchronous Zapros client with a FilterPolicy that caches only GET requests with a 200 status code response. This allows fine-grained control over caching. ```python from hishel import FilterPolicy from zapros import ( Client, CacheMiddleware, StdNetworkHandler, ) policy = FilterPolicy( request_filter=lambda req: req.method == "GET", response_filter=lambda resp: resp.status == 200, ) client = Client( handler=CacheMiddleware( StdNetworkHandler(), policy=policy, ) ) ``` -------------------------------- ### Sync Basic Usage with Cookie Middleware Source: https://github.com/kap-sh/zapros/blob/main/docs/cookies.md Demonstrates basic usage of a synchronous client with CookieMiddleware. Cookies are automatically stored after the login request and sent with the profile request. ```python from zapros import ( Client, CookieMiddleware, StdNetworkHandler, ) client = Client(handler=CookieMiddleware(StdNetworkHandler())) with client: client.get( "https://api.example.com/login", ) # session cookie stored response = client.get( "https://api.example.com/profile", ) # session cookie sent automatically ``` -------------------------------- ### Async Client with Custom Request and Response Filters Source: https://github.com/kap-sh/zapros/blob/main/docs/caching.md Configures an asynchronous Zapros client with a FilterPolicy that caches only GET requests with a 200 status code response. This allows fine-grained control over caching. ```python from hishel import FilterPolicy from zapros import ( AsyncClient, CacheMiddleware, AsyncStdNetworkHandler, ) policy = FilterPolicy( request_filter=lambda req: req.method == "GET", response_filter=lambda resp: resp.status == 200, ) client = AsyncClient( handler=CacheMiddleware( AsyncStdNetworkHandler(), policy=policy, ) ) ``` -------------------------------- ### Basic AsgiHandler Usage with Litestar Source: https://github.com/kap-sh/zapros/blob/main/docs/asgi.md Demonstrates basic usage of AsgiHandler with a Litestar application. Ensure the handler is used within an async context manager for proper resource management. ```python from litestar import Litestar, get from zapros import AsyncClient from zapros import AsgiHandler @get("/hello") async def hello() -> dict: return {"message": "Hello, World!"} app = Litestar(route_handlers=[hello]) handler = AsgiHandler(app) async with AsyncClient(handler=handler) as client: response = await client.get("http://testserver/hello") print(response.json) ``` -------------------------------- ### Building URLs with Query Parameters using URL Object Source: https://github.com/kap-sh/zapros/blob/main/docs/query-parameters.md Shows how to construct a URL object and dynamically add query parameters using dictionary-like access to its `search_params` attribute. ```python from zapros import URL url = URL("https://api.example.com/search") url.search_params["q"] = "zapros" url.search_params["limit"] = "10" print(url) ``` -------------------------------- ### Example Cassette JSON Structure Source: https://github.com/kap-sh/zapros/blob/main/docs/cassettes.md This JSON structure represents a recorded HTTP request and its corresponding response. It includes details like the request method and URI, and the response status, headers, and body. ```json [ { "request": { "method": "GET", "uri": "https://api.example.com/users" }, "response": { "status": 200, "headers": { "content-type": "application/json" }, "body": [ { "id": 1, "name": "Alice" } ] } } ] ``` -------------------------------- ### Initialize Zapros Request Source: https://github.com/kap-sh/zapros/blob/main/docs/models.md Create a Request object with a URL, method, and JSON payload. Headers like Content-Type, Host, and Accept are automatically set. ```python from zapros import Request from pywhatwgurl import URL url = URL("https://api.example.com/users") request = Request(url, "POST", json={"name": "Alice"}) request.headers[ "Content-Type" ] # "application/json" (auto-set) request.headers["Host"] # "api.example.com" (auto-set) request.headers["Accept"] # "*/*" (auto-set) request.body # b'{"name": "Alice"}' ``` -------------------------------- ### AsgiHandler Lifespan Management with Litestar Source: https://github.com/kap-sh/zapros/blob/main/docs/asgi.md Illustrates how to enable and use the ASGI lifespan protocol with AsgiHandler for application startup and shutdown logic. Ensure the handler is properly closed after use. ```python from litestar import Litestar, get from litestar.datastructures import ( State, ) @get("/state") async def get_state( state: State, ) -> dict: return {"value": state.get("initialized", False)} async def on_startup( app: Litestar, ) -> None: app.state.initialized = True app = Litestar( route_handlers=[get_state], on_startup=[on_startup], ) handler = AsgiHandler(app, enable_lifespan=True) try: async with AsyncClient(handler=handler) as client: response = await client.get( "http://testserver/state", ) print(response.json) finally: await handler.aclose() ``` -------------------------------- ### Access Response Headers (Sync) Source: https://github.com/kap-sh/zapros/blob/main/docs/models.md Demonstrates accessing response headers like 'content-type', 'server', and 'set-cookie' in a synchronous context. ```python with Client() as client: response = client.get("https://httpbin.org/get") content_type = response.headers["content-type"] server = response.headers.get("server", "unknown") if "set-cookie" in response.headers: cookies = response.headers.getall("set-cookie") ``` -------------------------------- ### Mocking a Request Never (Async) Source: https://github.com/kap-sh/zapros/blob/main/docs/mocking.md This asynchronous example sets up a mock that should never be triggered. It's useful for tests where you want to ensure a specific API call is not made. The mock is configured using `MockMiddleware` and `MockRouter`. ```python import asyncio from zapros import AsyncClient, Response from zapros.mock import ( Mock, MockMiddleware, MockRouter, ) from zapros.matchers import path router = MockRouter() router.add( Mock .given(path("/api")) .respond(Response(status=200)) .never() ) async def main(): async with AsyncClient( handler=MockMiddleware(router) ) as client: pass # no requests made asyncio.run(main()) ```