httpx is a fully featured, asynchronous HTTP client for Python, compatible with both HTTP/1.1 and HTTP/2. It offers a requests-like API, making it intuitive for developers familiar with the popular `requests` library, but extends its capabilities significantly, most notably with first-class `async`/`await` support. This allows for efficient handling of concurrent network requests in modern Python applications, especially those built with async frameworks like FastAPI or Starlette.
Key features of httpx include:
- Asynchronous and Synchronous API: You can use `httpx` with `async`/`await` for non-blocking I/O or synchronously for simpler scripts.
- HTTP/1.1 and HTTP/2 Support: It supports both versions of the HTTP protocol, with HTTP/2 being particularly beneficial for performance over a single connection.
- Requests-like API: The API design is very similar to `requests`, making the transition easy.
- Client Sessions: The `httpx.Client` class provides a session-based approach to make multiple requests with shared configurations (like base URL, headers, cookies, timeouts) and connection pooling.
- Streaming Support: For handling large responses efficiently without loading the entire content into memory.
- Timeouts, Retries, Redirects: Comprehensive control over request behavior.
- Authentication and Proxies: Built-in support for various authentication schemes and proxy configurations.
- Rich Request/Response Objects: Detailed access to request and response attributes, including headers, status codes, and body content.
- Command-line Interface (CLI): A built-in CLI for making quick HTTP requests.
`httpx` is often preferred over `requests` in projects requiring asynchronous operations, HTTP/2, or more fine-grained control over network interactions, making it a powerful tool for modern Python development.
Example Code
import httpx
import asyncio
To install: pip install httpx
--- Synchronous Example ---
print("--- Synchronous Example ---")
try:
response = httpx.get("https://httpbin.org/get?sync=true")
response.raise_for_status() Raises an HTTPStatusError for bad responses (4xx or 5xx)
print(f"Sync GET Status: {response.status_code}")
print(f"Sync GET Data: {response.json()['args']}")
except httpx.HTTPStatusError as e:
print(f"Error during synchronous request: {e}")
except httpx.RequestError as e:
print(f"Request error during synchronous request: {e}")
--- Asynchronous Example ---
print("\n--- Asynchronous Example ---")
async def main():
async with httpx.AsyncClient() as client:
try:
Basic GET request
response = await client.get("https://httpbin.org/get?async=true")
response.raise_for_status()
print(f"Async GET Status: {response.status_code}")
print(f"Async GET Data: {response.json()['args']}")
POST request with JSON data
post_data = {"name": "httpx_user", "value": "awesome"}
response = await client.post("https://httpbin.org/post", json=post_data)
response.raise_for_status()
print(f"Async POST Status: {response.status_code}")
print(f"Async POST Data: {response.json()['json']}")
except httpx.HTTPStatusError as e:
print(f"Error during asynchronous request: {e}")
except httpx.RequestError as e:
print(f"Request error during asynchronous request: {e}")
if __name__ == "__main__":
asyncio.run(main())








httpx