We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

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 request· Fetch 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 GET· Async request.
async with httpx.AsyncClient() as client:
    resp = await client.get('https://api.example.com/users')
    data = resp.json()
Concurrent async· Parallel 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 pooling· Reuse connections.
with httpx.Client(base_url='https://api.example.com') as client:
    resp = client.get('/users')
    resp = client.post('/users', json={'name': 'Bob'})
Timeout· Request timeout.
httpx.get('https://api.example.com', timeout=10.0)

Error Handling

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

Testing

Respx mock· Mock 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