Introduction
APIs (Application Programming Interfaces) are crucial components in modern software development that allow different software systems to communicate with each other. While there are many libraries for making HTTP requests in Python, HTTPx offers some unique advantages.
In this post, we’ll explore how to use HTTPx for making various types of API integration calls and compare it with the commonly used requests
library.
Installation
To install HTTPx, run the following command:
pip install httpx
Advantages of HTTPx over requests
- Async Support: HTTPx allows you to make asynchronous API calls out of the box.
- Connection pooling: It provides more efficient connection management.
- Request and response streaming: HTTPx supports streaming large requests and responses.
Making Basic GET Requests
Using requests
import requests
response = requests.get('https://jsonplaceholder.typicode.com/todos/1')
print(response.json())
Using HTTPx
import httpx
response = httpx.get('https://jsonplaceholder.typicode.com/todos/1')
print(response.json())
Making POST Requests
Using requests
import requests
import json
payload = {'title': 'foo', 'body': 'bar', 'userId': 1}
response = requests.post('https://jsonplaceholder.typicode.com/posts', json=payload)
print(response.json())
Using HTTPx
import httpx
payload = {'title': 'foo', 'body': 'bar', 'userId': 1}
response = httpx.post('https://jsonplaceholder.typicode.com/posts', json=payload)
print(response.json())
Making Asynchronous API Calls
Using HTTPx
import httpx
import asyncio
async def get_todo():
async with httpx.AsyncClient() as client:
response = await client.get('https://jsonplaceholder.typicode.com/todos/1')
print(response.json())
asyncio.run(get_todo())
Error Handling
Using requests
import requests
from requests.exceptions import HTTPError
try:
response = requests.get('https://jsonplaceholder.typicode.com/todos/12345')
response.raise_for_status()
except HTTPError as e:
print(f"An HTTP error occurred: {e}")
Using HTTPx
import httpx
from httpx import HTTPStatusError
try:
response = httpx.get('https://jsonplaceholder.typicode.com/todos/12345')
response.raise_for_status()
except HTTPStatusError as e:
print(f"An HTTP error occurred: {e}")
Conclusion
HTTPx provides an efficient way to make both synchronous and asynchronous API calls in Python. Its feature set is quite similar to requests
, but it offers additional functionalities like async support and better connection pooling. Whether you’re a beginner or an advanced user, HTTPx can simplify your API interactions in Python.
Feel free to explore the official documentation to dive deeper into its features and capabilities.