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.
By Cometflow API Engineering Team • Updated 2026-10-06
Python is the premier language for data science, backend automation, and ETL pipelines. Consuming an HTTP API in Python can be accomplished with either synchronous requests or modern asynchronous httpx with HTTP/2 connection pooling.
1. Synchronous Requests vs. Async HTTPX
- Use
requestswhen: Writing sequential CLI scripts, cron jobs, or simple data ingestion tasks where one request runs at a time. - Use
httpx.AsyncClientwhen: Building FastAPI backends or querying 50+ endpoints concurrently usingasyncio.gather(). - Critical Rule: Always pass an explicit
timeoutparameter. Inrequests, omittingtimeoutallows a hung socket to block your worker thread indefinitely.
2. Production Async Python Example with HTTPX
import httpx
import asyncio
async def fetch_weather_report(city: str, lat: float, lon: float):
url = "https://api.open-meteo.com/v1/forecast"
params = {"latitude": lat, "longitude": lon, "current_weather": "true"}
headers = {"User-Agent": "CometflowPythonClient/1.0", "Accept": "application/json"}
timeout = httpx.Timeout(10.0, connect=5.0)
async with httpx.AsyncClient(timeout=timeout, http2=True) as client:
response = await client.get(url, params=params, headers=headers)
response.raise_for_status() # Raises httpx.HTTPStatusError on 4xx/5xx
data = response.json()
temp = data["current_weather"]["temperature"]
print(f"Current temperature in {city}: {temp}°C")
asyncio.run(fetch_weather_report("Berlin", 52.52, 13.41))
Frequently Asked Questions (FAQ)
Why should I reuse a Session or AsyncClient instead of calling httpx.get() in a loop?
Creating a new client on every call forces a fresh TCP handshake and TLS negotiation for every single request. Reusing a context-managed AsyncClient pools keep-alive sockets and cuts latency by 40% to 70%.