← Blog
Two ivory envelopes, one with an orange flap, resting in a lavender mail tray.
Published on
2026-11-18

HTTPX vs Requests: choose a Python HTTP client

Choose Requests when a synchronous HTTP client already fits your Python application. Choose HTTPX when you need an async client, want synchronous and asynchronous interfaces in the same library, or have a specific requirement such as optional HTTP/2 support. The useful comparison is how each client behaves inside your application, including redirects, timeouts, connection reuse, and cleanup.

This guide compares HTTPX 0.28.1 and Requests 2.34.2 using local HTTP connections. The examples and checks ran on Python 3.12.14 on Windows; the async example requires Python 3.11 or later. We tested behavior, including failure cases. We did not measure which library is faster.

Choose the client for the calling application

RequirementRequestsHTTPX
A synchronous script or integration jobA Session is a reasonable starting pointA Client also supports synchronous calls
Outbound calls from async application codeIts normal request API blocks the calling threadAsyncClient provides an awaitable interface
Repeated calls with shared configurationReuse a SessionReuse a Client or AsyncClient
HTTP/2 as a specific requirementDo not assume the standard Requests setup meets itOptional dependencies and explicit enablement are required
Migrating existing request codeKeep behavior that already meets the requirementsCheck defaults and exception handling before replacing calls

HTTPX’s async interface is useful when your program already coordinates waiting operations. It does not make CPU-heavy Python work parallel. Its HTTP/2 support also depends on the server and negotiated protocol; enabling it alone does not prove that a connection used HTTP/2. Our test service did not exercise that protocol.

Both libraries send outbound requests. If you are choosing how to build the API that receives them, that is a separate decision covered in our FastAPI vs Flask comparison. A client change should solve an identified application problem, rather than become a reason to rewrite a working service.

Compare the same local request

Use an isolated Python environment and install the tested versions with python -m pip install httpx==0.28.1 requests==2.34.2. Create a new directory for the example, then save the following as payload.json:

{"items":["alpha","bravo"],"count":2}

From that directory, start python -m http.server 8765 --bind 127.0.0.1. Leave it running in one terminal. This serves files only on the local interface; it is a demonstration server, not the application hosting setup. Python documents the limitations of http.server. Stop it with Ctrl+C when finished.

Save this as compare_sync.py and run python compare_sync.py in a second terminal using the environment where you installed the libraries:

import httpx
import requests

def compare(base_url):
    url = base_url + '/payload.json'
    with requests.Session() as client:
        client.trust_env = False  # Isolate this local demonstration.
        with client.get(url, timeout=(2.0, 5.0),
                        allow_redirects=False) as response:
            response.raise_for_status()
            requests_result = response.json()

    with httpx.Client(timeout=httpx.Timeout(5.0, connect=2.0),
                      follow_redirects=False, trust_env=False) as client:
        response = client.get(url)
        response.raise_for_status()
        httpx_result = response.json()
    return {'requests': requests_result, 'httpx': httpx_result}

if __name__ == '__main__':
    print(compare('http://127.0.0.1:8765'))

Both entries in the returned dictionary contain {"items": ["alpha", "bravo"], "count": 2}. The URL, redirect choice, and timeout settings are explicit. Setting trust_env=False isolates this local exercise from environment-derived settings such as proxies; review the proxy and certificate requirements of your real environment before copying that choice into production.

For repeated calls, keep the client alive across the operation that owns those calls. Our separate HTTP/1.1 test service attached a connection identifier to each response. Two sequential requests within the same Requests Session reused one connection, and two within the same HTTPX Client did too. That observation is specific to the persistent-connection fixture; the simple file server above is not the connection-reuse test.

The Requests Session documentation and HTTPX client documentation describe their pooling and lifetime behavior. Avoid creating a new client inside a hot request loop when the work can share one scoped client.

Make redirects, status handling, and timeouts explicit

In the local redirect test, a Requests GET followed the redirect by default. The equivalent HTTPX GET returned the original 302 response. We also tested the explicit settings in both directions: allow_redirects=False for Requests and follow_redirects=True for HTTPX. A migration that assumes identical defaults can change which response the caller receives.

The status checks differed too. Requests accepted our 302 response when raise_for_status() was called, while HTTPX raised HTTPStatusError. Both returned a response object for the chosen 422 error, and both raised their respective HTTP exception when asked to check its status. Update exception handling as part of the migration, using the HTTPX Requests compatibility guide as a checklist.

Always choose a timeout policy. Requests has no default request timeout unless you provide one. HTTPX documents a default of five seconds of network inactivity. These settings should not be read as a guaranteed deadline for the entire operation. See the Requests timeout guidance and HTTPX timeout categories.

Our delayed-response fixture verified an explicit read timeout in both libraries. We did not simulate a slow connection handshake or stalled upload. A separate async test held an HTTPX streaming response open with a one-connection pool; a second request raised PoolTimeout. Closing the stream returned capacity, and the next request succeeded. This distinguishes waiting for a connection from waiting for response data.

Use AsyncClient with a bounded batch

Save the following as compare_async.py. With the local file server still running, execute python compare_async.py. It reads the same small JSON document four times and returns results in input order.

import asyncio
import httpx

async def fetch_many(base_url, count=4, limit=2):
    if type(count) is not int or not 1 <= count <= 100:
        raise ValueError('count must be an integer from 1 to 100')
    if type(limit) is not int or limit < 1:
        raise ValueError('limit must be a positive integer')
    slots = asyncio.Semaphore(limit)
    limits = httpx.Limits(max_connections=limit,
                          max_keepalive_connections=limit)
    async with httpx.AsyncClient(
        base_url=base_url, limits=limits, trust_env=False,
        timeout=httpx.Timeout(5.0, connect=2.0),
        follow_redirects=False,
    ) as client:
        async def one(index):
            async with slots:
                response = await client.get('/payload.json')
                response.raise_for_status()
                return {'request': index, 'data': response.json()}

        async with asyncio.TaskGroup() as group:
            tasks = [group.create_task(one(i)) for i in range(count)]
        return [task.result() for task in tasks]

if __name__ == '__main__':
    print(asyncio.run(fetch_many('http://127.0.0.1:8765')))

One client owns the batch, a semaphore limits operations inside the request section, and the pool has an explicit connection limit. The batch itself is capped at 100 tasks. The pool controls connections, while the semaphore controls the application operations admitted to that section. Neither is a requests-per-second limiter. HTTPX documents the available connection-pool limits.

With a controlled delay in our test service, four requests overlapped and the observed peak was two active handlers. Setting the limit to one reduced the peak to one. This demonstrates the chosen limit; it does not establish a safe limit for a public API. The TaskGroup owns the tasks, and errors can propagate as an exception group.

The semaphore wait happens before client.get, so HTTPX’s request timeout does not cover time spent waiting for that application slot. If the whole batch needs a deadline, design it at the batch boundary and account for cancellation and cleanup. Increasing the task count alone can increase memory use and waiting time.

Close streaming responses, including early exits

Reading every response into memory is unsuitable for some downloads. These two functions consume chunks and count decoded bytes. Save them as stream_clients.py. Call either function with the local http://127.0.0.1:8765/payload.json URL to try it with the example file.

import httpx
import requests

MAX_BYTES = 1_000_000

def count_requests(url):
    total = 0
    with requests.Session() as client:
        client.trust_env = False
        with client.get(url, stream=True, timeout=(2.0, 5.0),
                        allow_redirects=False) as response:
            response.raise_for_status()
            for chunk in response.iter_content(chunk_size=4096):
                total += len(chunk)
                if total > MAX_BYTES:
                    raise ValueError('Decoded response exceeds the demo limit')
    return total

def count_httpx(url):
    total = 0
    with httpx.Client(timeout=httpx.Timeout(5.0, connect=2.0),
                      follow_redirects=False, trust_env=False) as client:
        with client.stream('GET', url) as response:
            response.raise_for_status()
            for chunk in response.iter_bytes(chunk_size=4096):
                total += len(chunk)
                if total > MAX_BYTES:
                    raise ValueError('Decoded response exceeds the demo limit')
    return total

Both functions enforce a small demonstration limit and close their response contexts if that limit raises an error. The limit applies to bytes delivered by the decoded-content iterator. It is not a general defense against compressed payload expansion or hostile servers; choose response-size and resource controls for the actual workload.

Our checks read a complete finite body, stopped after the first chunk, and rejected an oversized body. After early exit, the recorded response objects were closed and subsequent calls worked. For HTTPX async code, use the corresponding async streaming context and close it on every path too. The one-connection pool test shows why an open response can affect other work.

Read the results within their test scope

The validation passed 52 checks with actual local socket connections. A standard-library file handler served the examples; a separate HTTP/1.1 service supplied controlled redirects, errors, delays, and connection identifiers.

ScenarioObserved result
JSON requests and query parametersBoth clients returned the expected values
Two sequential HTTP/1.1 requestsEach persistent client reused a connection
GET redirect defaultsRequests followed; HTTPX returned 302
Chosen 422 statusBoth raised their own HTTP exception when checked
Explicit read timeoutBoth raised a ReadTimeout
Streaming and early exitFull body counted; early responses closed; oversized body rejected
Async limits and pool capacityPeak of two handlers; an open stream exhausted a one-connection pool

The checks also covered matching JSON request payloads, repeated query parameters, invalid batch sizes, client closure, and fixture shutdown. No resource or unawaited-coroutine warnings were recorded. The tests did not cover HTTPS, HTTP/2, proxies, public API behavior, load capacity, or a cloud deployment. Different outcomes in a production system should be investigated against its own endpoint and configuration.

Migrate the request behavior, then plan the hosting

Before changing libraries, record the methods, payloads, headers, cookies, redirects, streaming behavior, and exceptions your application depends on. Port one request path and compare its successful and failing responses. Keep retry rules deliberate: a timeout can leave the caller uncertain whether a remote operation completed, so repeating a write needs an application-level decision.

For incoming events, our FastAPI webhook receiver guide covers a different part of the system: validation and acceptance at the receiving end. Record outbound request duration and failure categories with structured Python logs, while keeping credentials and sensitive payloads out of them.

If the client belongs to an integration service or recurring application job, use the API hosting guide to compare operating responsibilities, then assess the CPU options in Compute with Hivenet. The customer manages the application, dependencies, process supervision, network configuration, and monitoring. Choose the client for the program’s behavior and size the instance from measurements of the workload.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.