Language: Python
Web
httpx was created by Encode to provide a modern, high-performance HTTP client for Python. It is designed as a next-generation replacement for `requests` with async support and better HTTP/2 handling, making it ideal for modern web applications and APIs.
httpx is a fully featured HTTP client for Python 3, supporting both synchronous and asynchronous requests, connection pooling, and HTTP/2.
pip install httpxconda install -c conda-forge httpxhttpx allows sending HTTP requests synchronously or asynchronously. It supports custom headers, cookies, timeout handling, streaming responses, and HTTP/2 features.
import httpx
response = httpx.get('https://httpbin.org/get')
print(response.status_code)
print(response.json())Performs a simple synchronous GET request and prints the status code and JSON response.
import httpx
import asyncio
async def fetch():
async with httpx.AsyncClient() as client:
r = await client.get('https://httpbin.org/get')
print(r.json())
asyncio.run(fetch())Demonstrates performing an asynchronous GET request using httpx.
import httpx
headers = {'User-Agent': 'my-app/0.0.1'}
cookies = {'session_id': '12345'}
response = httpx.get('https://httpbin.org/headers', headers=headers, cookies=cookies)
print(response.json())Sends custom HTTP headers and cookies in a request.
import httpx
try:
response = httpx.get('https://httpbin.org/delay/10', timeout=5)
except httpx.TimeoutException:
print('Request timed out')Demonstrates handling request timeouts.
import httpx
with httpx.stream('GET', 'https://httpbin.org/stream/20') as response:
for chunk in response.iter_bytes():
print(chunk)Streams the response content in chunks without loading everything into memory.
Use `AsyncClient` for concurrent requests to improve performance.
Reuse client instances to take advantage of connection pooling.
Always set timeouts to avoid hanging requests.
Handle exceptions such as `httpx.RequestError` for robust error management.
Leverage HTTP/2 support for faster multiplexed requests when possible.