HTTPX is an asynchronous HTTP client for Python, used for making HTTP requests. Here’s a cheat sheet covering some common use cases and syntax for HTTPX:
Installation
pip install httpx
Making GET Requests
import httpx
url = "https://example.com"
response = httpx.get(url)
print(response.status_code)
print(response.text)
Making POST Requests
import httpx
url = "https://example.com"
data = {"key": "value"}
response = httpx.post(url, data=data)
print(response.status_code)
print(response.text)
Custom Headers
import httpx
url = "https://example.com"
headers = {"User-Agent": "MyApp/1.0"}
response = httpx.get(url, headers=headers)
print(response.status_code)
print(response.text)
Timeouts
import httpx
url = "https://example.com"
# Set timeout in seconds
timeout = httpx.Timeout(5.0)
response = httpx.get(url, timeout=timeout)
print(response.status_code)
print(response.text)
Handling Response Content
import httpx
url = "https://example.com"
response = httpx.get(url)
# Access response content as bytes
content_bytes = response.content
# Access response content as JSON
json_data = response.json()
# Access response content as text
text_data = response.text
Handling Errors
import httpx
url = "https://example.com"
try:
response = httpx.get(url)
response.raise_for_status()
print(response.text)
except httpx.HTTPError as exc:
print(f"HTTP error occurred: {exc}")
except Exception as exc:
print(f"An error occurred: {exc}")
Streaming Content
import httpx
url = "https://example.com"
with httpx.stream("GET", url) as response:
for chunk in response.iter_bytes():
print(chunk)
Async Requests
import httpx
import asyncio
async def make_request():
url = "https://example.com"
async with httpx.AsyncClient() as client:
response = await client.get(url)
print(response.status_code)
print(response.text)
# Run the asynchronous function
asyncio.run(make_request())
File Uploads
import httpx
url = "https://example.com"
files = {"file": ("filename.txt", b"file_content", "text/plain")}
response = httpx.post(url, files=files)
print(response.status_code)
print(response.text)
This cheat sheet provides a basic overview of HTTPX and how to make various types of requests using this library. Refer to the official HTTPX documentation for more detailed information and advanced usage.