Good Code
The good version declares the fixed /me route before the dynamic /{user_id} route.
Lesson 01
Declare specific routes before dynamic path parameters so FastAPI matches requests as intended.
from fastapi import APIRouter
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/me")
async def read_current_user():
return {"user_id": "current"}
@router.get("/{user_id}")
async def read_user(user_id: int):
return {"user_id": user_id}from fastapi import APIRouter
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/{user_id}")
async def read_user(user_id: int):
return {"user_id": user_id}
@router.get("/me")
async def read_current_user():
return {"user_id": "current"}The good version declares the fixed /me route before the dynamic /{user_id} route.
The bad version lets /{user_id} match /me first, so FastAPI tries to parse "me" as an integer and returns a validation error.