FastAPI

Lesson 01

Path operation order

Declare specific routes before dynamic path parameters so FastAPI matches requests as intended.

Good Code

api/users.py
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}

Bad Code

api/users.py
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"}

Review Notes

What to review

Good Code

The good version declares the fixed /me route before the dynamic /{user_id} route.

Bad Code

The bad version lets /{user_id} match /me first, so FastAPI tries to parse "me" as an integer and returns a validation error.

Takeaways

  • FastAPI path operations are evaluated in order, so route order is behavior.