Routing in FastAPI (GET, POST, PUT, DELETE)
Introduction
Now that your FastAPI project is set up, it’s time to understand the core of any API Routing.Routing defines:
- What URL to access
- What operation to perform
- What response to return
FastAPI makes routing simple, clean, and powerful.
What is Routing?
Routing means mapping a URL path to a Python function.
Example:
-
/users→ get all users -
/users/1→ get user with ID 1
Basic Route Example
from fastapi import FastAPIapp = FastAPI()@app.get("/")def home():return {"message": "Welcome to FastAPI"}
HTTP Methods in FastAPI
FastAPI supports all major HTTP methods:
| Method | Purpose |
|---|---|
| GET | Fetch data |
| POST | Create data |
| PUT | Update data |
| DELETE | Delete data |
GET Request Example
Used to retrieve data:
@app.get("/users")def get_users():return {"users": ["Alice", "Bob"]}
POST Request Example
Used to create data:
@app.post("/users")def create_user():return {"message": "User created"}
PUT Request Example
Used to update data:
@app.put("/users/{user_id}")def update_user(user_id: int):return {"message": f"User {user_id} updated"}
DELETE Request Example
Used to delete data:
@app.delete("/users/{user_id}")def delete_user(user_id: int):return {"message": f"User {user_id} deleted"}
Path Parameters
Path parameters are dynamic values in the URL.
@app.get("/items/{item_id}")def get_item(item_id: int):return {"item_id": item_id}
Example:
/items/10 → returns item_id = 10
Query Parameters
Query parameters are optional values in the URL.
@app.get("/products")def get_products(category: str, limit: int = 10):return {"category": category, "limit": limit}
Example:
/products?category=books&limit=5
Path vs Query Parameters
| Feature | Path Param | Query Param |
|---|---|---|
| Required | Yes | Optional |
| Position | URL path | After ? |
| Example | /items/1 | ?limit=10 |
Combining Path & Query Parameters
@app.get("/orders/{order_id}")def get_order(order_id: int, status: str = "pending"):return {"order_id": order_id, "status": status}
Organizing Routes (Best Practice)
Instead of writing everything in main.py, split routes:
app/routes/user.py
from fastapi import APIRouterrouter = APIRouter()@router.get("/users")def get_users():return {"users": []}
main.py
from fastapi import FastAPIfrom app.routes import userapp = FastAPI()app.include_router(user.router)
Common Mistakes
1. Forgetting type hints (
user_id: int)2. Mixing path & query parameters incorrectly
3. Not organizing routes into separate files
4. Using wrong HTTP method
Key Takeaways
- Routing connects URLs to Python functions
- FastAPI supports all HTTP methods easily
- Path params = required, Query params = optional
- Clean route organization is important
Comments
Post a Comment