๐ง 1. What is an API Request?
An API request is how your Python application communicates with a web server. Typically, you send HTTP requests to interact with resources (like users, posts, products) exposed by an API.
Python has multiple ways to handle these, but the most popular is the requests library.
⚙️ 2. Installing the requests Library
pip install requests
๐งฉ 3. Common HTTP Methods
Method Description Example Use Case
GET Retrieve data Fetch user info from /users
POST Create a resource Submit a new form or post data
PUT Update a resource Update user profile
PATCH Partially update a resource Change only the email field
DELETE Remove a resource Delete a post or user
HEAD Retrieve headers only Check if a resource exists
OPTIONS Describe communication options Check allowed methods for a resource
๐ ️ 4. Basic Usage of requests
1. GET Request
import requests
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
if response.status_code == 200:
data = response.json() # Convert JSON to Python dict
print(data)
else:
print(f"Error: {response.status_code}")
2. POST Request
url = "https://jsonplaceholder.typicode.com/posts"
payload = {"title": "New Post", "body": "This is content", "userId": 1}
response = requests.post(url, json=payload)
if response.status_code == 201:
print("Created:", response.json())
else:
print("Failed to create:", response.status_code)
Use json=payload instead of data=payload for automatic JSON serialization.
3. PUT Request
url = "https://jsonplaceholder.typicode.com/posts/1"
update_data = {"title": "Updated Post", "body": "Updated content", "userId": 1}
response = requests.put(url, json=update_data)
print(response.json())
4. PATCH Request
url = "https://jsonplaceholder.typicode.com/posts/1"
patch_data = {"title": "Partially Updated"}
response = requests.patch(url, json=patch_data)
print(response.json())
5. DELETE Request
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.delete(url)
if response.status_code == 200:
print("Deleted successfully")
else:
print("Failed to delete:", response.status_code)
๐ 5. Handling Headers, Authentication, and Tokens
Custom headers:
headers = {"Authorization": "Bearer your_token_here", "Accept": "application/json"}
response = requests.get(url, headers=headers)
Basic Authentication:
from requests.auth import HTTPBasicAuth
response = requests.get(url, auth=HTTPBasicAuth("username", "password"))
Bearer token authentication:
headers = {"Authorization": "Bearer <token>"}
response = requests.get(url, headers=headers)
๐ 6. Best Practices for API Requests
Handle Errors Gracefully
try:
response = requests.get(url)
response.raise_for_status() # Raises HTTPError for bad responses
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
Use Timeouts
response = requests.get(url, timeout=5) # 5 seconds timeout
Limit Retry Attempts
Use urllib3.util.retry or requests.adapters.HTTPAdapter for retries.
Validate Responses
Always check status_code and expected JSON keys.
Use Session Objects for Efficiency
session = requests.Session()
session.headers.update({"Authorization": "Bearer <token>"})
response = session.get(url)
Secure API Keys
Store in environment variables or secrets manager, never hardcode.
Paginate Large Requests
Use API pagination (limit, offset, or next) to avoid overwhelming the server.
Respect Rate Limits
Follow API documentation to avoid throttling or bans.
Log Requests and Responses
Helps with debugging and monitoring.
๐งฉ 7. Advanced Tips
Asynchronous Requests for performance using httpx or aiohttp:
import httpx
import asyncio
async def fetch(url):
async with httpx.AsyncClient() as client:
response = await client.get(url)
return response.json()
asyncio.run(fetch("https://jsonplaceholder.typicode.com/posts/1"))
Streaming large responses:
with requests.get(url, stream=True) as r:
for chunk in r.iter_content(chunk_size=1024):
process(chunk)
✅ 8. Summary
Python’s requests library makes API requests easy and readable.
GET, POST, PUT, PATCH, DELETE cover the main CRUD operations.
Always handle errors, use timeouts, validate responses, and protect sensitive data.
Advanced usage includes asynchronous requests, streaming, retries, and sessions.
Learn Fullstack Python Training in Hyderabad
Read More
Building Authentication for APIs in Python with JWT
Using Django REST Framework for Building APIs
How to Build a RESTful API with Flask
Introduction to REST APIs with Python
At Our Quality Thought Training Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments