Skip to content
>_devvkit
$devvkit learn --librarie httpx-guide

HTTPX Guide

[python][http][async]
Python
Install
pip install httpx
pip install httpx[http2]

HTTPX is the modern Python HTTP client with both sync and async APIs.

Connection pooling, timeouts, and HTTP/2 support built-in.

Pair with respx for easy HTTP mocking in tests.

Basic Usage

GET requestFetch data.
import httpx
response = httpx.get('https://api.example.com/users')
response.json()
POST (sync)Send data.
httpx.post('https://api.example.com/users', json={'name': 'Alice'})

Async

Async GETAsync request.
async with httpx.AsyncClient() as client:
    resp = await client.get('https://api.example.com/users')
    data = resp.json()
Concurrent asyncParallel requests.
async with httpx.AsyncClient() as client:
    tasks = [client.get(f'/users/{i}') for i in range(10)]
    responses = await asyncio.gather(*tasks)

Client Configuration

Client with poolingReuse connections.
with httpx.Client(base_url='https://api.example.com') as client:
    resp = client.get('/users')
    resp = client.post('/users', json={'name': 'Bob'})
TimeoutRequest timeout.
httpx.get('https://api.example.com', timeout=10.0)

Error Handling

Error handlingRaise on error.
response = httpx.get('https://api.example.com/404')
response.raise_for_status()  # raises HTTPStatusError

Testing

Respx mockMock HTTP for tests.
import respx
@respx.mock
def test_get_user():
    route = respx.get('https://api.example.com/users').mock(return_value=httpx.Response(200, json=[{'id': 1}]))
    resp = httpx.get('https://api.example.com/users')
    assert resp.json()[0]['id'] == 1