Python Requests & HTTPX: Making API Calls with Code Examples
Learn how to make HTTP API calls in Python using Requests and modern async HTTPX. Code snippets for GET, POST, headers, auth, and connection pooling.
Python is the premier language for data science, AI engineering, and automation. Consuming an http api example in Python can be accomplished with either synchronous requests or modern asynchronous httpx.
Modern Async Python API Example with HTTPX
import httpx
import asyncio
async def fetch_weather_report(city: str):
url = "https://api.example.com/v1/weather"
params = {"city": city, "units": "metric"}
headers = {"User-Agent": "CometflowPythonBot/1.0"}
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.get(url, params=params, headers=headers)
response.raise_for_status() # Raises exception if status is 4xx or 5xx
data = response.json()
print(f"Weather in {city}: {data['temp']}°C")
asyncio.run(fetch_weather_report("London"))
Using asynchronous clients enables Python applications to query hundreds of API endpoints concurrently in seconds without blocking the event loop.