Introduction 🌟
APIs (Application Programming Interfaces) allow applications to communicate with each other. In Python, API handling is commonly done using the requests module for synchronous calls and aiohttp for asynchronous calls.
Note
💡 Requires understanding of HTTP methods (GET, POST, PUT, DELETE)
💡 Used in mobile apps, web backends, automation, ML pipelines, and more
1. What Is an API? 🤔
An API exposes endpoints that clients can call to retrieve or update data. Example endpoint:
Code Snippet
GET https://api.example.com/usersAPI handling in Python = sending HTTP requests + processing responses.
2. Making a Simple API Request 🌍
basic_get.py
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts")
print(response.status_code)
print(response.json()[:2])✔ Retrieves sample posts from a public API
3. Passing Query Parameters 🔍
query_params.py
params = {"userId": 1}
res = requests.get(
"https://jsonplaceholder.typicode.com/posts",
params=params
)
print(res.json())✔ Builds URL → ?userId=1
4. Sending POST Request (Create Data) ➕
post.py
payload = {"title": "New Post", "body": "Hello!", "userId": 1}
res = requests.post(
"https://jsonplaceholder.typicode.com/posts",
json=payload
)
print(res.json())✔ Sends JSON to the server and receives a response
5. PUT & PATCH (Updating Data) ✏️
PUT = full replace
put.py
res = requests.put(
"https://jsonplaceholder.typicode.com/posts/1",
json={"title": "Updated Title", "body": "Updated content"}
)
print(res.json())PATCH = partial update
patch.py
res = requests.patch(
"https://jsonplaceholder.typicode.com/posts/1",
json={"title": "Partial Update"}
)
print(res.json())6. DELETE Request ❌
delete.py
res = requests.delete(
"https://jsonplaceholder.typicode.com/posts/1"
)
print(res.status_code)7. Working With Response Data 🧩
response_data.py
res = requests.get("https://api.github.com/users/octocat")
data = res.json()
print("Login:", data["login"])
print("ID:", data["id"])✔ Most APIs return JSON → use .json()
8. Error Handling & Status Codes ⚠️
error_handling.py
try:
res = requests.get("https://invalid.url", timeout=3)
res.raise_for_status()
except requests.exceptions.RequestException as e:
print("Error:", e)Note
9. Authentication Methods 🔐
1. API Key
api_key.py
headers = {"X-API-KEY": "your_api_key"}
res = requests.get("https://api.example.com/data", headers=headers)2. Bearer Token
bearer.py
headers = {"Authorization": "Bearer your_token"}
res = requests.get("https://api.example.com/user", headers=headers)3. Basic Auth
basic_auth.py
from requests.auth import HTTPBasicAuth
res = requests.get(
"https://api.example.com/login",
auth=HTTPBasicAuth("username", "password")
)10. Rate Limits & Retry Handling 🔁
retry.py
import time
import requests
for attempt in range(3):
try:
res = requests.get("https://api.example.com/data", timeout=3)
res.raise_for_status()
break
except requests.exceptions.RequestException:
print("Retrying...")
time.sleep(2)Note
11. Uploading & Downloading Files 📤📥
Uploading Files
file_upload.py
files = {"file": open("image.png", "rb")}
res = requests.post("https://api.example.com/upload", files=files)Downloading Large Files (Streaming)
stream_download.py
res = requests.get("https://example.com/bigfile", stream=True)
with open("file.bin", "wb") as f:
for chunk in res.iter_content(1024):
if chunk:
f.write(chunk)12. Sessions — Persistent API Handling 🔄
session.py
s = requests.Session()
s.headers.update({"User-Agent": "MyApp/1.0"})
res1 = s.get("https://httpbin.org/cookies/set?token=123")
res2 = s.get("https://httpbin.org/cookies")
print(res2.json())✔ Maintains cookies & headers across requests
13. Writing a Simple API Wrapper 🧱
wrapper.py
import requests
class JSONPlaceholderAPI:
BASE = "https://jsonplaceholder.typicode.com"
def get_posts(self):
return requests.get(f"{self.BASE}/posts").json()
def get_post(self, post_id):
return requests.get(f"{self.BASE}/posts/{post_id}").json()
api = JSONPlaceholderAPI()
print(api.get_post(1))✔ Useful for building reusable API clients
14. Pagination Handling 📄➡️📄
pagination.py
page = 1
while True:
res = requests.get("https://api.example.com/items", params={"page": page}).json()
if not res["items"]:
break
print(res["items"])
page += 115. Async API Handling with aiohttp ⚡
aiohttp_example.py
import aiohttp
import asyncio
async def fetch():
async with aiohttp.ClientSession() as session:
async with session.get("https://jsonplaceholder.typicode.com/posts") as res:
data = await res.json()
print(data[:2])
asyncio.run(fetch())Note
API Handling Cheat Sheet 📘
| Task | Solution |
|---|---|
| GET request | requests.get() |
| POST JSON | requests.post(json=data) |
| Timeout | timeout=3 |
| Authentication | Keys, Bearer, BasicAuth |
| Session | requests.Session() |
| Async requests | aiohttp |
Best Practices 💡
- ✔ Always handle errors using try/except
- ✔ Use timeouts for reliability
- ✔ Use sessions for repeated authenticated requests
- ✔ Respect API rate limits
- ✔ Validate input/output JSON
- ✔ Avoid sending sensitive data in query params
Conclusion 🎉
You now understand API Handling in Python! Want the next topic? Try Building APIs with FastAPI, OAuth2 Authentication, Webhooks, or Async API Wrappers. Just tell me! 😊