### Quick Example: GET, POST, Sessions, and HTTP/2 Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/index.rst Illustrates common httpmorph operations including GET, POST with JSON data, session management with cookies, and initiating HTTP/2 connections. ```python import httpmorph # GET request response = httpmorph.get('https://httpbin.org/get') print(response.json()) # POST with JSON response = httpmorph.post( 'https://httpbin.org/post', json={'key': 'value'} ) # Session with cookies session = httpmorph.Session(browser='chrome') response = session.get('https://example.com') print(session.cookies) # HTTP/2 client = httpmorph.Client(http2=True) response = client.get('https://www.google.com') print(response.http_version) # '2.0' ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/arman-bd/httpmorph/blob/main/docs/README.md Install the necessary dependencies for building the documentation locally. ```bash pip install -r requirements.txt ``` -------------------------------- ### Verify httpmorph Installation Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/installation.rst Import the library, print its version, and test basic functionality by making a GET request. ```python import httpmorph print(httpmorph.__version__) print(httpmorph.version()) # C library version # Test basic functionality response = httpmorph.get('https://httpbin.org/get') assert response.status_code == 200 ``` -------------------------------- ### Install httpmorph Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/index.rst Install the httpmorph library using pip. Ensure you have the necessary build requirements as detailed in the installation guide. ```bash pip install httpmorph ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Install the project in editable mode with development dependencies. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Create and Use an httpmorph Client Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Instantiate a `Client` object for more granular control over requests. This example performs a GET request. ```python client = httpmorph.Client() response = client.get('https://example.com') ``` -------------------------------- ### Install Build Tools on Windows Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Installs necessary build tools for Windows using Chocolatey. Alternatively, manual installation of Visual Studio, CMake, Go, and NASM is possible. ```bash # Install build tools choco install cmake golang nasm visualstudio2022buildtools -y # Or install manually: # - Visual Studio 2019+ (with C++ tools) # - CMake 3.15+ # - Go 1.18+ # - NASM (for BoringSSL assembly optimizations) ``` -------------------------------- ### Clone and Setup HTTPMorph Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Clone the repository, navigate to the directory, and set up vendor dependencies including BoringSSL. ```bash git clone https://github.com/arman-bd/httpmorph.git cd httpmorph ./scripts/setup_vendors.sh ``` -------------------------------- ### Build httpmorph from Source Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/installation.rst Clone the repository, set up vendor dependencies, build Python extensions, and install in development mode. ```bash git clone https://github.com/arman-bd/httpmorph.git cd httpmorph # Build vendor dependencies (BoringSSL, nghttp2) ./scripts/setup_vendors.sh # Build Python extensions python setup.py build_ext --inplace # Install in development mode pip install -e ".[dev]" ``` -------------------------------- ### Install Linux (Ubuntu/Debian) Build Dependencies Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/installation.rst Install build dependencies for Ubuntu/Debian systems using apt-get. ```bash sudo apt-get install cmake ninja-build libssl-dev pkg-config \ autoconf automake libtool libnghttp2-dev ``` -------------------------------- ### Enable HTTP/2 with Client Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Create a `Client` with `http2=True` to enable HTTP/2. This example fetches a URL and prints its HTTP version. ```python client = httpmorph.Client(http2=True) response = client.get('https://www.google.com') print(response.http_version) # '2.0' ``` -------------------------------- ### Install nghttp2 on Fedora/RHEL Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/installation.rst Install the nghttp2 runtime library on Fedora/RHEL systems to resolve import errors. ```bash sudo dnf install libnghttp2 ``` -------------------------------- ### Install Linux (Fedora/RHEL) Build Dependencies Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/installation.rst Install build dependencies for Fedora/RHEL systems using dnf. ```bash sudo dnf install cmake ninja-build openssl-devel pkg-config \ autoconf automake libtool libnghttp2-devel ``` -------------------------------- ### Install macOS Build Dependencies Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/installation.rst Install necessary build tools like cmake, ninja, and libnghttp2 using Homebrew. ```bash brew install cmake ninja libnghttp2 ``` -------------------------------- ### Install Windows Build Dependencies Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/installation.rst Install build dependencies for Windows using Chocolatey. ```bash choco install cmake golang nasm visualstudio2022buildtools -y ``` -------------------------------- ### Install Optional Development Dependencies Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/installation.rst Install development tools like pytest, mypy, and ruff using pip with the [dev] extra. ```bash pip install httpmorph[dev] ``` -------------------------------- ### Install Dependencies on macOS Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Installs required dependencies for building on macOS using Homebrew. ```bash # Install dependencies brew install cmake ninja libnghttp2 ``` -------------------------------- ### Basic GET and Session Usage in httpmorph Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/index.rst Demonstrates a simple GET request and how to use a session with a specified browser profile for subsequent requests. ```python import httpmorph # Simple GET request response = httpmorph.get('https://example.com') print(response.status_code, response.text) # Use a session with browser profile session = httpmorph.Session(browser='chrome') response = session.get('https://example.com') ``` -------------------------------- ### Install nghttp2 on Ubuntu/Debian Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/installation.rst Install the nghttp2 runtime library on Ubuntu/Debian systems to resolve import errors. ```bash sudo apt-get install libnghttp2-14 ``` -------------------------------- ### Library Initialization and Cleanup Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Provides code examples for initializing and cleaning up the HTTPMorph library. Initialization is automatic on import, but explicit calls can be made. ```APIDOC ## Library Initialization and Cleanup ### Description Initialize the library (called automatically on import). ### Code ```python import httpmorph # Initialize the library (optional, as it's called on import) httpmorph.init() # Cleanup library resources httpmorph.cleanup() ``` ``` -------------------------------- ### Install Dependencies on Linux (Fedora/RHEL) Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Installs required build dependencies for Fedora and RHEL-based Linux distributions using dnf. ```bash # Fedora/RHEL sudo dnf install cmake ninja-build openssl-devel pkg-config autoconf automake libtool ``` -------------------------------- ### Perform a Simple GET Request Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Use the `get` function for basic HTTP GET requests. Prints the status code and response text. ```python import httpmorph response = httpmorph.get('https://httpbin.org/get') print(response.status_code) print(response.text) ``` -------------------------------- ### Async GET Request with AsyncClient Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Illustrates how to perform asynchronous HTTP GET requests using AsyncClient and an async context manager. ```python import asyncio import httpmorph async def fetch(): async with httpmorph.AsyncClient() as client: response = await client.get('https://httpbin.org/get') print(response.status_code) return response asyncio.run(fetch()) ``` -------------------------------- ### Get HTTPMorph Package Version Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Retrieves the installed version of the HTTPMorph Python package. ```python print(httpmorph.__version__) ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/installation.rst Install Xcode Command Line Tools on macOS to resolve build errors. ```bash xcode-select --install ``` -------------------------------- ### Basic HTTP Requests with httpmorph Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Perform simple GET and POST requests, and demonstrate session usage. Includes printing response status and text. ```python import httpmorph # Simple GET request response = httpmorph.get('https://icanhazip.com') print(response.status_code) print(response.text) # POST with JSON response = httpmorph.post( 'https://httpbin.org/post', json={'key': 'value'} ) # Using sessions session = httpmorph.Session(browser='chrome') response = session.get('https://example.com') # HTTP/2 support (httpx-like API) client = httpmorph.Client(http2=True) response = client.get('https://www.google.com') print(response.http_version) # '2.0' ``` -------------------------------- ### Basic GET Request with Error Handling Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Demonstrates a basic GET request with comprehensive error handling for timeouts, connection errors, HTTP errors, and general request exceptions. ```python try: response = httpmorph.get('https://example.com', timeout=5) response.raise_for_status() # Raise on 4xx/5xx except httpmorph.Timeout: print('Request timed out') except httpmorph.ConnectionError: print('Connection failed') except httpmorph.HTTPError as e: print(f'HTTP error: {e.response.status_code}') except httpmorph.RequestException as e: print(f'Request failed: {e}') ``` -------------------------------- ### Make a GET request Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Use httpmorph.get() to make a GET request to a specified URL. Additional keyword arguments can be passed for request customization. ```python response = httpmorph.get(url, **kwargs) ``` -------------------------------- ### HTTP Client Methods Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Access all standard HTTP methods (get, post, etc.) directly from an httpmorph.Client instance. ```python response = client.get(url, **kwargs) response = client.post(url, data=None, json=None, **kwargs) ``` -------------------------------- ### Check HTTP Version Used for a Request Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Verify the HTTP version (e.g., HTTP/2.0 or HTTP/1.1) used for a specific request. This example explicitly enables HTTP/2 for the client. ```python client = httpmorph.Client(http2=True) response = client.get('https://www.google.com') if response.http_version == '2.0': print('Using HTTP/2') else: print('Fell back to HTTP/1.1') ``` -------------------------------- ### httpmorph.get() Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Make a GET request to a specified URL. Accepts additional keyword arguments for request customization. ```APIDOC ## GET ### Description Make a GET request to a specified URL. ### Method GET ### Endpoint [url] ### Parameters #### Path Parameters - **url** (str) - URL to request #### Query Parameters - **kwargs** - See `Request Parameters`_ ### Response #### Success Response (200) - **Response** object ``` -------------------------------- ### Get HTTPMorph C Library Version Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Retrieves the version of the underlying C library used by HTTPMorph. ```python print(httpmorph.version()) ``` -------------------------------- ### Access Response Timing Information Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Get detailed timing information for the request, such as total time, connection time, and TLS handshake duration, in microseconds. ```python print(response.total_time_us) # Total time in microseconds print(response.connect_time_us) # Connection time print(response.tls_time_us) # TLS handshake time print(response.first_byte_time_us) # Time to first byte print(response.elapsed) # As timedelta ``` -------------------------------- ### Performing Basic Authentication Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Illustrates how to use basic authentication by providing a username and password tuple. ```python # Basic authentication response = httpmorph.get( 'https://api.example.com', auth=('username', 'password') ) ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/arman-bd/httpmorph/blob/main/docs/README.md Navigate to the docs directory and build the HTML documentation using Sphinx. ```bash cd docs make html ``` -------------------------------- ### Show All Build Targets Source: https://github.com/arman-bd/httpmorph/blob/main/docs/README.md Display a list of all available make targets for the documentation build process. ```bash make help ``` -------------------------------- ### Run All Tests Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Execute the full test suite for the project. ```bash pytest tests/ -v ``` -------------------------------- ### Utilize All HTTP Methods Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Demonstrates the usage of various HTTP methods provided by httpmorph. ```python httpmorph.get(url) httpmorph.post(url, data=...) httpmorph.put(url, data=...) httpmorph.delete(url) httpmorph.head(url) httpmorph.patch(url, data=...) httpmorph.options(url) ``` -------------------------------- ### Initialize Async HTTP Client Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Create an httpmorph.AsyncClient for asynchronous HTTP requests using non-blocking I/O. ```python client = httpmorph.AsyncClient() ``` -------------------------------- ### Initialize HTTP Client Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Create an httpmorph.Client instance for making HTTP requests. Defaults to HTTP/2. ```python client = httpmorph.Client(http2=True) ``` -------------------------------- ### Configure Basic Authentication Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Provide username and password for basic HTTP authentication. ```python # Basic authentication response = httpmorph.get( url, auth=('username', 'password') ) ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Run the test suite and generate an HTML report for code coverage. ```bash pytest tests/ --cov=httpmorph --cov-report=html ``` -------------------------------- ### HTTP/2 Support with Client and Session Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Demonstrates how to use HTTP/2 with both Client and Session objects. Defaults to HTTP/2, similar to Chrome. Can be disabled per-request. ```python # Both Client and Session default to HTTP/2 (http2=True) like Chrome client = httpmorph.Client() response = client.get('https://www.google.com') print(response.http_version) # '2.0' session = httpmorph.Session(browser='chrome') response = session.get('https://www.google.com') print(response.http_version) # '2.0' # Per-request HTTP/2 override (disable for specific request) client = httpmorph.Client() # Defaults to HTTP/2 response = client.get('https://example.com', http2=False) # Disable for this request ``` -------------------------------- ### Upload Multiple Files Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Demonstrates uploading multiple files simultaneously by providing a dictionary of file objects. ```python # Multiple files files = { 'file1': open('report.pdf', 'rb'), 'file2': open('data.csv', 'rb') } response = httpmorph.post(url, files=files) ``` -------------------------------- ### Per-Protocol Proxies Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Configure different proxy servers for HTTP and HTTPS protocols using a dictionary. ```python proxies = { 'http': 'http://http-proxy.example.com:8080', 'https': 'http://https-proxy.example.com:8080' } response = httpmorph.get(url, proxies=proxies) ``` -------------------------------- ### Proxy Authentication (Basic) Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Provide proxy credentials using a tuple for username and password. Alternatively, embed them in the proxy URL. ```python response = httpmorph.get( url, proxy='http://proxy.example.com:8080', proxy_auth=('username', 'password') ) ``` ```python response = httpmorph.get( url, proxy='http://user:pass@proxy.example.com:8080' ) ``` -------------------------------- ### Clean Built Documentation Source: https://github.com/arman-bd/httpmorph/blob/main/docs/README.md Remove previously built documentation files. ```bash make clean ``` -------------------------------- ### Uploading Files with POST Requests Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Illustrates how to upload files using the 'files' parameter in a POST request. ```python files = {'file': ('report.pdf', open('report.pdf', 'rb'))} response = httpmorph.post('https://httpbin.org/post', files=files) ``` -------------------------------- ### Managing Sessions and Cookies Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Shows how to use Sessions to maintain cookies across multiple requests, enabling stateful interactions. ```python session = httpmorph.Session() # Cookies persist across requests session.get('https://example.com/login') session.post('https://example.com/form', data={'key': 'value'}) # Access cookies print(session.cookies) ``` -------------------------------- ### Upload File with Filename and Content Type Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Illustrates how to specify a custom filename and content type for an uploaded file. ```python # With filename and content type files = { 'file': ('report.pdf', open('report.pdf', 'rb'), 'application/pdf') } response = httpmorph.post(url, files=files) ``` -------------------------------- ### Initialize HTTP Session Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Create an httpmorph.Session for persistent cookies and headers. Defaults to HTTP/2 and mimics Chrome. ```python session = httpmorph.Session(browser='chrome', os='macos', http2=True) ``` -------------------------------- ### Make an OPTIONS request Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Use httpmorph.options() to make an OPTIONS request. ```python response = httpmorph.options(url, **kwargs) ``` -------------------------------- ### Initialize HTTPMorph Library Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Initializes the HTTPMorph library. This is called automatically when the library is imported. ```python httpmorph.init() ``` -------------------------------- ### Create Session with Chrome Profile and Specific OS Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Creates an HTTPMorph session using the Chrome 143 profile, simulating a specific operating system like Windows. ```python session = httpmorph.Session(browser='chrome', os='windows') ``` -------------------------------- ### HTTP/2 Client and Session Default Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Shows that both Client and Session default to HTTP/2, and how to verify the HTTP version. ```python # Both Client and Session default to HTTP/2 (http2=True) client = httpmorph.Client() response = client.get('https://www.google.com') print(response.http_version) # '2.0' session = httpmorph.Session(browser='chrome') response = session.get('https://www.google.com') print(response.http_version) # '2.0' ``` -------------------------------- ### HTTP Proxy Configuration Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Configure a standard HTTP proxy for requests. Ensure the proxy URL is correctly formatted. ```python response = httpmorph.get( 'http://example.com', proxy='http://proxy.example.com:8080' ) ``` -------------------------------- ### Connection Pooling Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Demonstrates automatic connection reuse for efficiency. Connections are pooled and reused by default. ```python client = httpmorph.Client() # First request creates connection r1 = client.get('https://example.com/page1') # Second request reuses connection r2 = client.get('https://example.com/page2') ``` ```python with httpmorph.Session() as session: for i in range(100): response = session.get(f'https://example.com/page{i}') # All requests reuse the same connection ``` ```python client = httpmorph.Client() r1 = client.get('https://example.com') print(r1.connect_time_us, r1.tls_time_us) # Non-zero r2 = client.get('https://example.com') print(r2.connect_time_us, r2.tls_time_us) # Much lower or zero ``` -------------------------------- ### Configure HTTP Proxy Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Set up an HTTP proxy for requests, including options for authentication and using a proxy dictionary. ```python # HTTP proxy response = httpmorph.get( url, proxy='http://proxy.example.com:8080' ) ``` ```python # With authentication response = httpmorph.get( url, proxy='http://proxy.example.com:8080', proxy_auth=('user', 'pass') ) ``` ```python # Proxy dict (requests-compatible) proxies = { 'http': 'http://proxy.example.com:8080', 'https': 'https://proxy.example.com:8080' } response = httpmorph.get(url, proxies=proxies) ``` -------------------------------- ### Handling Redirects in HTTP Requests Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Demonstrates how to control redirect behavior and access redirect history. By default, redirects are followed. ```python # Follow redirects (default behavior) response = httpmorph.get('https://example.com/redirect') # Don't follow redirects response = httpmorph.get( 'https://example.com/redirect', allow_redirects=False ) # Check redirect history print(len(response.history)) # Number of redirects ``` -------------------------------- ### Making Requests with Custom Headers Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Shows how to include custom headers in your HTTP requests, such as User-Agent or Authorization. ```python headers = { 'User-Agent': 'MyApp/1.0', 'Authorization': 'Bearer token123' } response = httpmorph.get('https://api.example.com', headers=headers) ``` -------------------------------- ### Controlling Request Timeouts Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Demonstrates how to set timeouts for HTTP requests, either as a single value or separate connect and read timeouts. ```python # Single timeout value response = httpmorph.get('https://example.com', timeout=5) # Separate connect and read timeouts response = httpmorph.get('https://example.com', timeout=(3, 10)) ``` -------------------------------- ### Make a HEAD request Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Use httpmorph.head() to make a HEAD request. ```python response = httpmorph.head(url, **kwargs) ``` -------------------------------- ### Use Session as Context Manager Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Manage an httpmorph.Session using a 'with' statement for automatic resource management. ```python with httpmorph.Session() as session: response = session.get(url) ``` -------------------------------- ### Simulate OS-Specific User Agents Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Set the operating system for the User-Agent string. Other fingerprinting characteristics remain consistent with the browser profile. ```python import httpmorph # macOS (default) session = httpmorph.Session(browser='chrome', os='macos') # User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ... # Windows session = httpmorph.Session(browser='chrome', os='windows') # User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... # Linux session = httpmorph.Session(browser='chrome', os='linux') # User-Agent: Mozilla/5.0 (X11; Linux x86_64) ... ``` -------------------------------- ### Session with Older Chrome Browser Profiles Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Shows how to instantiate a session using older Chrome browser profiles for compatibility testing purposes. ```APIDOC ## Session with Older Chrome Browser Profiles ### Description Instantiate a session using older Chrome browser profiles, such as Chrome 127 or 135, for compatibility testing. ### Usage ```python import httpmorph session = httpmorph.Session(browser='chrome127') session = httpmorph.Session(browser='chrome135') ``` ``` -------------------------------- ### httpmorph.options() Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Make an OPTIONS request to a specified URL. Accepts additional keyword arguments for request customization. ```APIDOC ## OPTIONS ### Description Make an OPTIONS request to a specified URL. Accepts additional keyword arguments for request customization. ### Method OPTIONS ### Endpoint [url] ### Parameters #### Path Parameters - **url** (str) - URL to request #### Query Parameters - **kwargs** - See `Request Parameters`_ ### Response #### Success Response (200) - **Response** object ``` -------------------------------- ### Create and Use an httpmorph Session Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Instantiate a `Session` object to persist cookies and headers across multiple requests. The first request can set cookies, which are automatically included in subsequent requests. ```python session = httpmorph.Session() # First request sets cookies session.get('https://example.com/login') # Subsequent requests include cookies session.get('https://example.com/protected') ``` -------------------------------- ### Upload Single File Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Shows how to upload a single file using the 'files' parameter in a POST request. ```python # Single file files = {'file': open('report.pdf', 'rb')} response = httpmorph.post('https://httpbin.org/post', files=files) ``` -------------------------------- ### Use Async Client as Context Manager Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Manage an httpmorph.AsyncClient using an 'async with' statement for proper resource handling in asynchronous operations. ```python async with httpmorph.AsyncClient() as client: response = await client.get(url) ``` -------------------------------- ### Concurrent Async Requests Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Shows how to make multiple asynchronous requests concurrently using asyncio.gather and AsyncClient. ```python import asyncio import httpmorph async def fetch_all(urls): async with httpmorph.AsyncClient() as client: tasks = [client.get(url) for url in urls] responses = await asyncio.gather(*tasks) return responses urls = [ 'https://httpbin.org/get', 'https://httpbin.org/headers', 'https://httpbin.org/user-agent' ] responses = asyncio.run(fetch_all(urls)) for response in responses: print(response.status_code, response.url) ``` -------------------------------- ### Set Default Timeout with Client Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Configure a default timeout for all requests made by a `Client` instance by setting the `timeout` parameter. ```python client = httpmorph.Client(timeout=10) response = client.get('https://example.com') ``` -------------------------------- ### Download Large File with Streaming Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Stream large responses to avoid loading the entire body into memory. Use `stream=True` and iterate over content chunks. ```python response = httpmorph.get('https://example.com/large-file.zip', stream=True) with open('large-file.zip', 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) ``` -------------------------------- ### Session with Chrome 143 Browser Profile Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Demonstrates how to create an HTTPMorph session using the default Chrome 143 browser profile, including options for specifying the OS. ```APIDOC ## Session with Chrome 143 Browser Profile ### Description Create a session using the default Chrome 143 browser profile. This profile offers high accuracy and specific fingerprint characteristics. You can also specify the operating system. ### Usage ```python import httpmorph # Use Chrome 143 profile (default) session = httpmorph.Session(browser='chrome') # Explicitly use Chrome 143 session = httpmorph.Session(browser='chrome143') # With specific OS session = httpmorph.Session(browser='chrome', os='windows') ``` ``` -------------------------------- ### Request Parameters - Connection Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Parameters for configuring connection settings. ```APIDOC ## Request Parameters - Connection ### Description Parameters for controlling connection behavior. ### Parameters - **timeout** (int/float) - Request timeout in seconds - **proxy** (str) - Proxy URL - **proxy_auth** (tuple) - Proxy authentication: `(username, password)` - **proxies** (dict) - Proxy dict: `{'http': '...', 'https': '...'}` ``` -------------------------------- ### Request Parameters - SSL/TLS Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Parameters for configuring SSL/TLS settings. ```APIDOC ## Request Parameters - SSL/TLS ### Description Parameters for managing SSL/TLS verification and version constraints. ### Parameters - **verify** or **verify_ssl** (bool) - Verify SSL certificates. Default: `True` - **tls_version** (str/tuple) - TLS version constraint (e.g., `"1.2"` or `(min, max)`) ``` -------------------------------- ### Session with Random Browser Profile Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Illustrates how to create a session that randomly selects a browser profile from the available Chrome profiles. ```APIDOC ## Session with Random Browser Profile ### Description Randomly selects a browser profile for each session from the available Chrome profiles. ### Usage ```python import httpmorph # The 'random' option selects a profile randomly session = httpmorph.Session(browser='random') ``` ``` -------------------------------- ### Load CA Certificates Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Load CA certificates from a PEM-formatted file into the HTTP client. Returns True on success. ```python client.load_ca_file(ca_file) ``` -------------------------------- ### Create Session with Default Chrome Profile Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Creates an HTTPMorph session using the default Chrome 143 browser profile. ```python session = httpmorph.Session(browser='chrome') ``` -------------------------------- ### Handle Request Exceptions Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Import the httpmorph library to prepare for handling potential exceptions during HTTP requests. ```python import httpmorph ``` -------------------------------- ### httpmorph.AsyncClient Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst An asynchronous HTTP client using non-blocking I/O. ```APIDOC ## AsyncClient ### Description Async HTTP client using epoll/kqueue. Note: AsyncClient uses non-blocking I/O but DNS resolution is still blocking. ### Constructor `AsyncClient()` ### Methods All HTTP methods return coroutines. Example: ```python client = httpmorph.AsyncClient() response = await client.get(url) ``` ### Context Manager AsyncClient can be used as an async context manager: ```python async with httpmorph.AsyncClient() as client: response = await client.get(url) ``` ``` -------------------------------- ### Async Client for Non-Blocking I/O Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Utilize AsyncClient for non-blocking I/O operations. Requires asyncio and httpmorph imports. ```python import asyncio import httpmorph async def main(): async with httpmorph.AsyncClient() as client: # Non-blocking request response = await client.get('https://httpbin.org/delay/2') print(response.status_code) asyncio.run(main()) ``` -------------------------------- ### Mimic Chrome Browser Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Configure the session to mimic a Chrome browser profile for realistic fingerprinting. Supports default, specific versions, or random selection. ```python # Chrome browser profile (defaults to Chrome 143) session = httpmorph.Session(browser='chrome') response = session.get('https://example.com') ``` ```python # Use specific Chrome version (127-143 supported) session = httpmorph.Session(browser='chrome143') response = session.get('https://example.com') ``` ```python # Random browser selection session = httpmorph.Session(browser='random') ``` -------------------------------- ### HTTP Session Methods Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst All standard HTTP methods are available on an httpmorph.Session instance for making requests within a persistent session. ```python response = session.get(url, **kwargs) response = session.post(url, data=None, json=None, **kwargs) ``` -------------------------------- ### Per-Request HTTP/2 Override Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Demonstrates how to disable HTTP/2 for a specific request by setting the 'http2' parameter to False. ```python # Per-request override (disable HTTP/2 for specific request) client = httpmorph.Client() # Defaults to HTTP/2 response = client.get('https://example.com', http2=False) ``` -------------------------------- ### Use Session as Context Manager Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Use the Session object as a context manager to ensure resources are properly cleaned up. ```python with httpmorph.Session() as session: response = session.get('https://example.com') ``` -------------------------------- ### Set Query Parameters Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Append query parameters to the URL. The library automatically formats them correctly. ```python params = {'key': 'value', 'foo': 'bar'} response = httpmorph.get(url, params=params) # Requests: https://example.com?key=value&foo=bar ``` -------------------------------- ### Make a POST request Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Use httpmorph.post() to make a POST request. You can send data as bytes, string, or a dictionary for form data, or as a JSON object. ```python response = httpmorph.post(url, data=None, json=None, **kwargs) ``` -------------------------------- ### Create Session with Explicit Chrome 143 Profile Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Creates an HTTPMorph session by explicitly specifying the Chrome 143 browser profile. ```python session = httpmorph.Session(browser='chrome143') ``` -------------------------------- ### Using Browser Profiles for Requests Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Make requests mimicking specific browser profiles, including default and version-specific Chrome profiles. ```python # Use Chrome fingerprint (defaults to Chrome 143) response = httpmorph.get('https://example.com', browser='chrome') # Use specific Chrome version (127-143 supported) session = httpmorph.Session(browser='chrome143') response = session.get('https://example.com') # Available browsers: chrome, chrome127-chrome143 ``` -------------------------------- ### Exceptions Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Overview of exceptions raised by the httpmorph library. ```APIDOC ## Exceptions All exceptions inherit from ``RequestException``. ### RequestException Base exception for all httpmorph errors. ### HTTPError Raised when ``raise_for_status()`` is called on a 4xx/5xx response. #### Attributes: - **response** - The Response object ### ConnectionError Raised when connection fails. ### Timeout Raised when request times out. ### TooManyRedirects Raised when max redirects is exceeded. ``` -------------------------------- ### httpmorph.head() Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Make a HEAD request to a specified URL. Accepts additional keyword arguments for request customization. ```APIDOC ## HEAD ### Description Make a HEAD request to a specified URL. Accepts additional keyword arguments for request customization. ### Method HEAD ### Endpoint [url] ### Parameters #### Path Parameters - **url** (str) - URL to request #### Query Parameters - **kwargs** - See `Request Parameters`_ ### Response #### Success Response (200) - **Response** object ``` -------------------------------- ### Request Parameters - HTTP/2 Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Parameter for enabling HTTP/2. ```APIDOC ## Request Parameters - HTTP/2 ### Description Parameter to enable HTTP/2 for a request. ### Parameters - **http2** (bool) - Enable HTTP/2 for this request (overrides client/session default) ``` -------------------------------- ### Request Timing Analysis Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Analyze the performance of a single request by printing connection, TLS, first byte, and total times in milliseconds. ```python response = httpmorph.get('https://example.com') print(f'Connection: {response.connect_time_us / 1000:.2f}ms') print(f'TLS: {response.tls_time_us / 1000:.2f}ms') print(f'First byte: {response.first_byte_time_us / 1000:.2f}ms') print(f'Total: {response.total_time_us / 1000:.2f}ms') ``` -------------------------------- ### Disabling SSL Certificate Verification Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Shows how to disable SSL verification for requests. This is not recommended for production environments due to security risks. ```python # Disable SSL verification (not recommended for production) response = httpmorph.get('https://example.com', verify_ssl=False) ``` -------------------------------- ### SSL Certificate Verification Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Load a custom CA bundle for SSL certificate verification or disable verification (not recommended). ```python import certifi import httpmorph client = httpmorph.Client() client.load_ca_file(certifi.where()) response = client.get('https://example.com') ``` ```python response = httpmorph.get(url, verify=False) ``` -------------------------------- ### Handling HTTP Errors and Timeouts Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Shows how to catch specific httpmorph exceptions like Timeout, ConnectionError, HTTPError, and general RequestException. Use raise_for_status() to trigger HTTPError for bad responses. ```python import httpmorph try: response = httpmorph.get('https://example.com', timeout=5) response.raise_for_status() # Raise exception for 4xx/5xx except httpmorph.Timeout: print("Request timed out") except httpmorph.ConnectionError: print("Failed to connect") except httpmorph.HTTPError as e: print(f"HTTP error: {e.response.status_code}") except httpmorph.RequestException as e: print(f"Request failed: {e}") ``` -------------------------------- ### Run Tests with Specific Markers Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Execute tests filtered by specific markers, such as skipping slow tests or running only proxy tests. ```bash pytest tests/ -m "not slow" # Skip slow tests pytest tests/ -m "not proxy" # Skip proxy tests (default in CI) pytest tests/ -m proxy # Only proxy tests pytest tests/ -m integration # Only integration tests pytest tests/ -m fingerprint # Only fingerprinting tests ``` -------------------------------- ### Async Client Methods Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst All HTTP methods on an AsyncClient return coroutines, enabling asynchronous request handling. ```python response = await client.get(url, **kwargs) response = await client.post(url, data=None, json=None, **kwargs) ``` -------------------------------- ### Make a PUT request Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Use httpmorph.put() to make a PUT request, optionally providing data. ```python response = httpmorph.put(url, data=None, **kwargs) ``` -------------------------------- ### Request Parameters - HTTP Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Common HTTP-specific parameters for making requests. ```APIDOC ## Request Parameters - HTTP ### Description Common parameters accepted by all request methods related to HTTP. ### Parameters #### Query Parameters - **headers** (dict) - HTTP headers - **params** (dict) - URL query parameters - **cookies** (dict) - Cookies to send - **auth** (tuple) - Basic authentication: `(username, password)` ``` -------------------------------- ### httpmorph.post() Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Make a POST request to a specified URL. Supports sending data as form data or JSON. ```APIDOC ## POST ### Description Make a POST request to a specified URL. Supports sending data as form data or JSON. ### Method POST ### Endpoint [url] ### Parameters #### Path Parameters - **url** (str) - URL to request #### Query Parameters - **kwargs** - See `Request Parameters`_ #### Request Body - **data** (bytes/str/dict) - Request body or form data - **json** (dict) - JSON data to send ### Response #### Success Response (200) - **Response** object ``` -------------------------------- ### Accessing Response Data Source: https://github.com/arman-bd/httpmorph/blob/main/README.md Demonstrates how to access status codes, headers, response bodies (as text, bytes, or JSON), request information, timing, and TLS details from an httpmorph response object. ```python response = httpmorph.get('https://httpbin.org/get') # Status and headers print(response.status_code) # 200 print(response.ok) # True print(response.reason) # 'OK' print(response.headers) # {'Content-Type': 'application/json', ...} # Response body print(response.text) # Response as string print(response.body) # Response as bytes print(response.json()) # Parse JSON response # Request info print(response.url) # Final URL after redirects print(response.history) # List of redirect responses # Timing print(response.elapsed) # Response time print(response.total_time_us) # Total time in microseconds # TLS info print(response.tls_version) # TLS version used print(response.tls_cipher) # Cipher suite print(response.ja3_fingerprint) # JA3 fingerprint ``` -------------------------------- ### Print Request Details and Timing Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Access and print details about a completed HTTP request, including URL, status code, headers, and timing breakdown (connect, TLS, total). ```python response = httpmorph.get('https://httpbin.org/get') # Request details (stored in response) print('URL:', response.url) print('Status:', response.status_code) print('Headers:', response.headers) # Timing breakdown print('Connect:', response.connect_time_us / 1000, 'ms') print('TLS:', response.tls_time_us / 1000, 'ms') print('Total:', response.total_time_us / 1000, 'ms') ``` -------------------------------- ### httpmorph.Client Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst An HTTP client for making requests, with HTTP/2 enabled by default. ```APIDOC ## Client ### Description HTTP client for making requests. Defaults to HTTP/2 to match Chrome behavior. ### Constructor `Client(http2=True)` ### Constructor Parameters - **http2** (bool) - Enable HTTP/2. Default: `True` ### Methods All HTTP method functions (get, post, put, delete, head, patch, options) are available as methods on the client instance. Example: ```python client = httpmorph.Client(http2=True) response = client.get(url) ``` ### Other Methods #### `load_ca_file(ca_file)` Load CA certificates from file (PEM format). **Parameters:** - **ca_file** (str) - Path to CA certificate bundle **Returns:** - **bool** - True on success ``` -------------------------------- ### Request Parameters - Redirect Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Parameters for controlling redirect behavior. ```APIDOC ## Request Parameters - Redirect ### Description Parameters to control whether redirects are followed and the maximum number allowed. ### Parameters - **allow_redirects** (bool) - Follow redirects. Default: `True` - **max_redirects** (int) - Maximum number of redirects. Default: `10` ``` -------------------------------- ### HTTPS Proxy with CONNECT Tunneling Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Use CONNECT tunneling for HTTPS requests through a proxy. The proxy URL should be an HTTP URL. ```python response = httpmorph.get( 'https://example.com', proxy='http://proxy.example.com:8080' ) ``` -------------------------------- ### Set Request Headers Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Add custom headers to your HTTP requests. This is useful for setting User-Agent, authentication tokens, or other metadata. ```python headers = {'User-Agent': 'MyApp/1.0'} response = httpmorph.get(url, headers=headers) ``` -------------------------------- ### Implement Retry Logic with Exponential Backoff Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Implement retry logic for requests that might fail due to timeouts or connection errors. Uses exponential backoff for delays between retries. ```python import time import httpmorph def fetch_with_retry(url, max_retries=3): for attempt in range(max_retries): try: response = httpmorph.get(url, timeout=10) response.raise_for_status() return response except (httpmorph.Timeout, httpmorph.ConnectionError): if attempt < max_retries - 1: time.sleep(2 ** attempt) # Exponential backoff else: raise response = fetch_with_retry('https://example.com') ``` -------------------------------- ### Control Redirects Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/quickstart.rst Manage redirect behavior by disabling them entirely or setting a maximum number of redirects. ```python # Disable redirect following response = httpmorph.get(url, allow_redirects=False) ``` ```python # Limit max redirects response = httpmorph.get(url, max_redirects=5) ``` -------------------------------- ### Response Iteration Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Iterate over response body line by line, with options for decoding unicode. ```APIDOC ## Response Iteration ### Description Iterate over response body line by line. Supports decoding lines as text. ### Method N/A (Method on Response object) ### Endpoint N/A ### Parameters #### Query Parameters - **delimiter** (str) - Optional - Line delimiter (default: `\n`) - **decode_unicode** (bool) - Optional - Decode lines as text ### Response #### Success Response (200) - **Yields**: str or bytes ### Request Example ```python response.iter_lines(delimiter=None, decode_unicode=True) ``` ``` -------------------------------- ### Override Session Headers with Per-Request Headers Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Demonstrates how headers provided in a per-request call override headers set at the session level. Ensures specific requests can have unique headers. ```python session = httpmorph.Session() session.headers = {'User-Agent': 'MyApp/1.0'} # Uses session User-Agent session.get('https://example.com') # Overrides session User-Agent for this request session.get('https://example.com', headers={'User-Agent': 'CustomBot/2.0'}) ``` -------------------------------- ### Create Session with Older Chrome Profile Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Creates an HTTPMorph session using an older Chrome browser profile, such as Chrome 127, for compatibility testing. ```python session = httpmorph.Session(browser='chrome127') ``` -------------------------------- ### OS-Specific User Agents Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Customize the User-Agent string for different operating systems like macOS, Windows, and Linux. ```python # macOS user agent (default) session = httpmorph.Session(browser='chrome', os='macos') response = session.get('https://httpbin.org/user-agent') # User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ... ``` ```python # Windows user agent session = httpmorph.Session(browser='chrome', os='windows') response = session.get('https://httpbin.org/user-agent') # User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... ``` ```python # Linux user agent session = httpmorph.Session(browser='chrome', os='linux') response = session.get('https://httpbin.org/user-agent') # User-Agent: Mozilla/5.0 (X11; Linux x86_64) ... ``` -------------------------------- ### Make a PATCH request Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Use httpmorph.patch() to make a PATCH request, optionally providing data. ```python response = httpmorph.patch(url, data=None, **kwargs) ``` -------------------------------- ### Session Reuse for Performance Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Improve performance for multiple requests to the same host by reusing a Session object to maintain connections. ```python # Bad - creates new connection each time for i in range(100): httpmorph.get('https://example.com') # Good - reuses connection session = httpmorph.Session() for i in range(100): session.get('https://example.com') ``` -------------------------------- ### Request Parameters - Body Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Parameters for specifying the request body. ```APIDOC ## Request Parameters - Body ### Description Parameters used to define the request body content. ### Parameters - **data** (bytes/str/dict) - Request body or form data - **json** (dict) - JSON data (auto-serialized with Content-Type header) - **files** (dict) - Files to upload (multipart/form-data) ``` -------------------------------- ### Make a DELETE request Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Use httpmorph.delete() to make a DELETE request. ```python response = httpmorph.delete(url, **kwargs) ``` -------------------------------- ### Iterate Response Lines Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Iterate over response body line by line. Use decode_unicode=True to decode lines as text. ```python response.iter_lines(delimiter=None, decode_unicode=True) ``` -------------------------------- ### Redirect Handling Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Information related to redirect handling during requests. ```APIDOC ## Redirect Handling ### Description Provides details on how redirects are handled and their history. ### Attributes - **history** (list) - List of ``Response`` objects from redirects - **is_redirect** (bool) - True if status is 3xx ``` -------------------------------- ### Response Object Methods Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/api.rst Methods available on the Response object returned by httpmorph requests. ```APIDOC ## Response Object Methods ### `json()` Parse response body as JSON. **Returns:** - Parsed JSON object (dict/list) **Raises:** - `ValueError` if body is not valid JSON ### `raise_for_status()` Raise `HTTPError` if status is 4xx or 5xx. **Raises:** - `HTTPError` ### `iter_content(chunk_size=1024, decode_unicode=False)` Iterate over response body in chunks. **Parameters:** - **chunk_size** (int) - Size of chunks to iterate over. Default: 1024 - **decode_unicode** (bool) - Whether to decode the content as unicode. Default: False ``` -------------------------------- ### HTTP/2 Per-Request Override Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Allows overriding the client's default HTTP/2 setting on a per-request basis. ```python # Client defaults to HTTP/1.1 client = httpmorph.Client(http2=False) # Force HTTP/2 for this request r1 = client.get('https://www.google.com', http2=True) print(r1.http_version) # '2.0' # Use default (HTTP/1.1) for this request r2 = client.get('https://example.com') print(r2.http_version) # '1.1' ``` -------------------------------- ### HTTP/2 ALPN Negotiation Source: https://github.com/arman-bd/httpmorph/blob/main/docs/source/advanced.rst Enables HTTP/2 negotiation via ALPN during the TLS handshake. Falls back to HTTP/1.1 if the server does not support HTTP/2. ```python client = httpmorph.Client(http2=True) response = client.get('https://www.google.com') print(response.http_version) # '2.0' if server supports it ``` ```python client = httpmorph.Client(http2=True) response = client.get('https://old-server.com') print(response.http_version) # May be '1.1' if server lacks HTTP/2 ```