
FastAPI
Path parameters can be required (mandatory) or optional (with defaults). Understanding the difference is crucial for API design.
A required path parameter MUST be provided in the URL, or the endpoint won't match:
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# user_id is REQUIRED
# /users/123 ✅ Works
# /users ❌ Error - endpoint not found
return {"user_id": user_id}Optional path parameters can be omitted. However, in FastAPI, path parameters are always required by default. To make them optional, you need a different approach using route ordering:
# Multiple routes for flexibility
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# Specific user
return {"user_id": user_id}
@app.get("/users/list")
async def list_users():
# List all users - handles the "optional" case
return {"users": []}| Feature | Required | Optional |
|---|---|---|
| Must be in URL | Yes ✅ | No |
| Default value | None | Yes |
| Endpoint matches without it | No | Yes (different endpoint) |
| Error if missing | 404 Not Found | Uses default or alternate route |
from fastapi import FastAPI
app = FastAPI()
# Required: user_id must be provided
@app.get("/users/{user_id}")
async def get_user(user_id: int):
return {"id": user_id, "name": f"User {user_id}"}
# Handles the "list all" case
@app.get("/users")
async def list_users():
return {"users": [
{"id": 1, "name": "User 1"},
{"id": 2, "name": "User 2"}
]}
# Multiple levels
@app.get("/users/{user_id}/posts/{post_id}")
async def get_post(user_id: int, post_id: int):
# Both user_id and post_id are REQUIRED
return {"user_id": user_id, "post_id": post_id}# Required parameter provided ✅
curl http://localhost:8000/users/123
# Returns: {"id": 123, "name": "User 123"}
# Required parameter missing ❌
curl http://localhost:8000/users
# Returns: 404 Not Found
# Use list endpoint instead ✅
curl http://localhost:8000/users
# Returns: {"users": [...]}Path parameters are always required in REST APIs. If you need optional parameters, use:
# ✅ Good: Clear required parameters
@app.get("/products/{product_id}")
async def get_product(product_id: int):
return {"id": product_id}
@app.get("/products")
async def list_products():
return {"products": []}
# ✅ Good: Optional query parameters for filtering
@app.get("/products")
async def search_products(
category: Optional[str] = None,
min_price: Optional[float] = None
):
return {"products": []}Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward