🚀 Lesson 2 — Building APIs in FastAPI (GET, POST, PUT, DELETE + Params)
This lesson is hands-on, practical, and industry-style, preparing you for real backend + AI applications.
🎯 What You Will Learn Today
✔ GET, POST, PUT, DELETE routes
✔ Path parameters
✔ Query parameters
✔ Request body using Pydantic
✔ Status codes & error handling
✔ Real industry example (Users API)
Let’s begin. 🔥
🧠 1. Basic GET Endpoint
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return {"msg": "Welcome to Lesson 2 🚀"}
🛣 2. Path Parameters (Dynamic URLs)
Example:/items/10 → return item with id 10
@app.get("/items/{item_id}")
def get_item(item_id: int):
return {"item_id": item_id}
FastAPI automatically:
- converts
item_idto int - validates it
- sends 422 error if wrong type
🔎 3. Query Parameters
Example:/search?keyword=phone&limit=5
@app.get("/search")
def search(keyword: str, limit: int = 10):
return {"keyword": keyword, "limit": limit}
Here:
keyword→ requiredlimit→ optional (default = 10)
📦 4. Request Body (POST with JSON)
We use Pydantic Models to validate incoming JSON.
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
email: str
POST endpoint:
@app.post("/users")
def create_user(user: User):
return {"status": "User added", "data": user}
Send JSON:
{
"name": "Rajeev",
"age": 29,
"email": "raj@example.com"
}
FastAPI validates:
- age must be int
- email must be str
- name required
🔄 5. PUT API (Update Resource)
@app.put("/users/{user_id}")
def update_user(user_id: int, user: User):
return {"msg": "Updated", "user_id": user_id, "new_data": user}
PUT = replace whole object
PATCH = partial update (we’ll do later)
❌ 6. DELETE API
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
return {"msg": "User deleted", "user_id": user_id}
🚨 7. Error Handling + Status Codes
from fastapi import HTTPException
@app.get("/protected/{id}")
def read(id: int):
if id <= 0:
raise HTTPException(status_code=400, detail="ID must be positive!")
return {"id": id}
🏭 8. Industry Example — Complete User CRUD API
This is exactly what companies expect.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
age: int
email: str
db = {} # temporary in-memory DB
@app.post("/users")
def create_user(user: User):
user_id = len(db) + 1
db[user_id] = user
return {"id": user_id, "data": user}
@app.get("/users/{user_id}")
def get_user(user_id: int):
if user_id not in db:
raise HTTPException(404, "User not found")
return db[user_id]
@app.put("/users/{user_id}")
def update_user(user_id: int, user: User):
if user_id not in db:
raise HTTPException(404, "User not found")
db[user_id] = user
return {"msg": "Updated", "data": user}
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
if user_id not in db:
raise HTTPException(404, "User not found")
del db[user_id]
return {"msg": "Deleted"}
You now have:
✔ Add user
✔ Read user
✔ Update user
✔ Delete user
✔ Handle invalid user
✔ Validate input automatically
🧪 9. Try Everything in Swagger UI
Go to:
http://127.0.0.1:8000/docs
You can run APIs live without Postman.
📌 Lesson 2 Summary
You learned:
- GET, POST, PUT, DELETE
- Path & query parameters
- JSON body validation (Pydantic)
- Error handling
- Complete CRUD example
This is enough to build:
- backend for React/Next.js
- AI/ML model API
- microservices
- app backend
🚀 Ready for Lesson 3 — Pydantic Deep Dive?
Lesson 3 topics:
✔ Advanced validation
✔ Optional fields
✔ Default values
✔ Email validation
✔ Nested models
✔ Enums
✔ Config & constraints
✔ Industry examples
Should I continue with Lesson 3 now?