How to Use an API with Python: Requests, HTTPX, and OpenAI SDK
A practical Python tutorial for calling RESTful and AI APIs using the Requests library, async HTTPX, and official SDKs with connection pooling, retries, and JSON parsing.
Overview #
A practical Python tutorial for calling RESTful and AI APIs using the Requests library, async HTTPX, and official SDKs with connection pooling, retries, and JSON parsing.
Making HTTP Requests with the requests Library
#
The requests library is the standard for synchronous HTTP in Python. Sending a POST request involves passing the endpoint URL, headers dictionary, and a json= parameter which automatically serializes Python dictionaries into JSON strings.
Asynchronous High-Concurrency Calls with HTTPX #
When dispatching hundreds of simultaneous API requests (such as batch document processing), synchronous code blocks execution. Python's httpx.AsyncClient with asyncio.gather() allows sending concurrent requests without spawning heavy OS threads.
Using the OpenAI Python SDK with API100 Gateway #
Because API100 adheres to the standard OpenAI REST specification, developers can use the official openai Python package. Simply configure base_url='https://api.apihundred.com/v1' to access GPT-6, Claude 5, Gemini 3.8, and DeepSeek-R1 seamlessly.
Code Example: Concurrent Asynchronous API Calls with HTTPX in Python #
import asyncio
import httpx
async def fetch_completion(client, prompt):
response = await client.post(
"https://api.apihundred.com/v1/chat/completions",
headers={"Authorization": "Bearer your_key"},
json={"model": "deepseek-v3", "messages": [{"role": "user", "content": prompt}]}
)
return response.json()["choices"][0]["message"]["content"]
async def main():
prompts = ["Summarize quantum computing", "Explain vector databases", "What is an API gateway?"]
async with httpx.AsyncClient(timeout=30.0) as client:
tasks = [fetch_completion(client, p) for p in prompts]
results = await asyncio.gather(*tasks)
for i, res in enumerate(results):
print(f"Task {i+1} Output: {res[:60]}...")
asyncio.run(main())
Frequently Asked Questions #
Q: What is the difference between requests and httpx in Python?
Requests is strictly synchronous. HTTPX supports both synchronous and async/await syntax, along with native HTTP/2 support.
Q: How do I handle timeouts in Python requests?
Always specify timeout in seconds: requests.post(url, timeout=10) to avoid hanging indefinitely on stalled connections.
Q: Can I use Python typing with API responses?
Yes, combining Pydantic models with API responses gives type validation and auto-complete in VS Code and PyCharm.
Build with API100
Access 100+ AI models through one lightning-fast OpenAI-compatible API with sub-50ms routing overhead and zero markup on cached tokens.

