🌐 REST & APIs Visual Guide

Understanding Web APIs Through Everyday Analogies

🔌 What is an API?

The Restaurant Analogy

API = Application Programming Interface

🍽️ Think of a Restaurant

You (Client): Want to order food but can't go into the kitchen

Menu (API Documentation): Shows what you can order and how to order it

Waiter (API): Takes your order to the kitchen and brings back your food

Kitchen (Server): Prepares the food but you never interact with it directly

In Software Terms:

  • Client = Your app (web, mobile, ML model)
  • API = The interface that accepts requests
  • Server = Where data is stored and processed
  • Response = The data sent back to your app

Real-World Example: Weather App

# You don't have weather data yourself # You ask a weather API for it import requests # API Request: "Give me weather for New York" response = requests.get("https://api.weather.com/current?city=NewYork") # API Response: Here's the weather data! weather = response.json() # {'temperature': 72, 'condition': 'sunny', 'humidity': 65}

Why APIs Matter: Instagram doesn't store all photos on your phone. When you open the app, it uses APIs to fetch your feed, post photos, load comments, etc.

📐 REST: The Rules of Good APIs

REST = Representational State Transfer

REST is a set of guidelines for building APIs that are predictable, scalable, and easy to use.

🏛️ Think of a Library System

Resources: Books are identified by call numbers (URLs)

Actions: Checkout, return, reserve (HTTP methods)

Stateless: Each request is independent - librarian doesn't remember you

Standard Format: All requests follow the same rules

Key REST Principles

Principle What It Means Example
Resources Everything is a "thing" with a URL /users/123, /posts/456, /models/789
HTTP Methods Actions you can do to resources GET (read), POST (create), PUT (update), DELETE (remove)
Stateless Each request is independent Every request includes all needed information (like showing ID each time)
Standard Format Data sent/received in predictable format JSON is the most common format

🎯 HTTP Methods: The Four Core Actions

🏦 ATM Machine Analogy

GET: Check your balance (view only, doesn't change anything)

POST: Deposit money (create something new)

PUT: Update your PIN (modify existing thing)

DELETE: Close account (remove something)

GET

Purpose: Retrieve data

Safe: Yes (doesn't change anything)

Example: View a profile

POST

Purpose: Create new resource

Safe: No (creates something)

Example: Submit a new post

PUT

Purpose: Update existing resource

Safe: No (modifies something)

Example: Edit your bio

DELETE

Purpose: Remove resource

Safe: No (deletes something)

Example: Delete a photo

Real API Examples

# GET: Retrieve user data (read only) GET /api/users/123 Response: {"id": 123, "name": "Alice", "email": "[email protected]"} # POST: Create new user POST /api/users Body: {"name": "Bob", "email": "[email protected]"} Response: {"id": 124, "name": "Bob", "created": true} # PUT: Update user email PUT /api/users/123 Body: {"email": "[email protected]"} Response: {"id": 123, "email": "[email protected]", "updated": true} # DELETE: Remove user DELETE /api/users/123 Response: {"deleted": true, "id": 123}

🚦 HTTP Status Codes: What Happened?

📬 Post Office Analogy

2xx (Success): "Your package was delivered!" ✅

4xx (Client Error): "Wrong address - can't deliver" 🏠❌

5xx (Server Error): "Post office is closed - try later" 🏢❌

200 OK

Request successful, here's your data

201 Created

Successfully created new resource

204 No Content

Success, but no data to return

400 Bad Request

Your request is malformed or invalid

401 Unauthorized

You need to log in first

404 Not Found

That resource doesn't exist

422 Validation Error

Data format is wrong

500 Internal Server Error

Something broke on the server

Status Code Scenarios

# Scenario 1: Successfully get user GET /api/users/123 → 200 OK + user data # Scenario 2: Create new post POST /api/posts → 201 Created + new post data # Scenario 3: User not found GET /api/users/999999 → 404 Not Found # Scenario 4: Invalid data format POST /api/users {"email": "not-an-email"} → 422 Validation Error # Scenario 5: Not logged in DELETE /api/posts/123 → 401 Unauthorized # Scenario 6: Database crashed GET /api/users → 500 Internal Server Error

FastAPI: Building APIs the Modern Way

Why FastAPI?

  • Fast: One of the fastest Python frameworks
  • Easy: Write less code to do more
  • Automatic Docs: Interactive API documentation built-in
  • Type Safe: Catches errors before runtime
  • Modern: Uses Python 3.8+ features like type hints

Your First API in 10 Lines

from fastapi import FastAPI app = FastAPI() # That's it! You have an API! @app.get("/") async def root(): return {"message": "Hello World"} # Run: uvicorn main:app --reload # Visit: http://localhost:8000/docs for interactive documentation!

API Request/Response Flow

Client sends request
FastAPI validates data
Your code processes
Return response
Client receives data

🔗 Connecting to Design Patterns (W4D1)

🏭 Factory Pattern → Create API Responses

# Use Factory to create different model types via API @app.post("/models/create") async def create_model(model_type: str): # Factory pattern from W4D1! model = MLModelFactory.create_model(model_type) return {"model_id": model.id, "type": model_type}

🎯 Strategy Pattern → Different Processing Methods

# Use Strategy to switch algorithms via API parameter @app.post("/predict") async def predict(strategy: str, data: list): # Strategy pattern from W4D1! if strategy == "fast": predictor = FastPredictionStrategy() else: predictor = AccuratePredictionStrategy() result = predictor.predict(data) return {"prediction": result, "strategy": strategy}

👁️ Observer Pattern → API Monitoring

# Observer automatically logs all API calls @app.post("/train") async def train_model(config: dict): # Observer pattern logs training progress model = MonitoredMLModel(base_model) # From W4D1! model.train(data) # Observers automatically log progress return {"status": "trained", "accuracy": model.accuracy}

🔒 Singleton Pattern → Configuration Management

# Singleton ensures one config instance across all API requests config = ConfigurationManager() # Singleton from W4D1! @app.get("/config") async def get_config(): # Same config instance used everywhere return {"settings": config.get_all()}

🎯 Key Takeaways

💡 Real-World Applications

How Companies Use APIs

Company What Their API Does Example Endpoint
Twitter Post tweets, read timeline, search POST /tweets
Spotify Get recommendations, control playback GET /recommendations
Google Maps Get directions, geocode addresses GET /directions
Netflix Stream content, track watching GET /continue-watching
Uber Request rides, track drivers POST /rides