Mini Project: API Data Fetch Tool
Build a complete API data fetching tool using everything from Module 10 — HTTP, JSON parsing, error handling, and data processing.
25 min•By Priygop Team•Updated 2026
API Data Fetch Tool
API Data Fetch Tool
import json
from datetime import datetime
# Simulated API responses
MOCK_APIS = {
"/users": [
{"id": 1, "name": "Alice", "email": "alice@test.com", "active": True},
{"id": 2, "name": "Bob", "email": "bob@test.com", "active": False},
{"id": 3, "name": "Charlie", "email": "charlie@test.com", "active": True},
],
"/posts": [
{"id": 1, "title": "Python Tips", "userId": 1, "likes": 42},
{"id": 2, "title": "API Guide", "userId": 1, "likes": 28},
{"id": 3, "title": "Testing 101", "userId": 2, "likes": 35},
],
}
class APIFetchTool:
def __init__(self, base_url):
self.base_url = base_url
self.cache = {}
self.request_count = 0
def fetch(self, endpoint):
"""Fetch data from API with caching."""
if endpoint in self.cache:
print(f" 📦 Cache hit: {endpoint}")
return self.cache[endpoint]
self.request_count += 1
print(f" 🌐 Fetching: {self.base_url}{endpoint}")
# Simulated API call
if endpoint in MOCK_APIS:
data = MOCK_APIS[endpoint]
self.cache[endpoint] = data
return data
else:
raise Exception(f"404: {endpoint} not found")
def fetch_all(self, endpoints):
"""Fetch multiple endpoints."""
results = {}
for ep in endpoints:
try:
results[ep] = self.fetch(ep)
except Exception as e:
print(f" ❌ Error: {e}")
results[ep] = None
return results
def stats(self):
print(f"\n📊 Requests made: {self.request_count}")
print(f"📦 Cached endpoints: {len(self.cache)}")
# Demo
print("=== API Data Fetch Tool ===\n")
tool = APIFetchTool("https://api.example.com")
# Fetch users
users = tool.fetch("/users")
print(f" Found {len(users)} users")
# Fetch again (cached!)
users = tool.fetch("/users")
# Fetch posts
posts = tool.fetch("/posts")
print(f" Found {len(posts)} posts")
# Process data
print("\n--- Active Users ---")
active = [u for u in users if u["active"]]
for user in active:
user_posts = [p for p in posts if p["userId"] == user["id"]]
total_likes = sum(p["likes"] for p in user_posts)
print(f" {user['name']}: {len(user_posts)} posts, {total_likes} likes")
# Try non-existent endpoint
print("\n--- Error Handling ---")
try:
tool.fetch("/comments")
except Exception as e:
print(f" Handled: {e}")
# Stats
tool.stats()
# Export as JSON report
report = {
"generated": datetime.now().isoformat(),
"users": len(users),
"active_users": len(active),
"total_posts": len(posts),
"total_likes": sum(p["likes"] for p in posts),
}
print(f"\n=== Report ===")
print(json.dumps(report, indent=2))Tip
Tip
Build API wrappers as classes with proper error handling. Cache responses to reduce API calls. Use async for high-throughput.
Diagram
Loading diagram…
REST is the standard for modern web APIs
Common Mistake
Warning
Not implementing retry logic for transient API failures. Use exponential backoff: wait 1s, 2s, 4s, 8s between retries.
Quick Quiz
Practice Task
Note
(1) Build a weather API dashboard. (2) Add caching for API responses. (3) Implement retry logic with backoff.