Pydantic v2 Schemas: Separate input DTOs (OrderCreateRequest), output responses (OrderResponse), and internal DB models.
Dependency Injection: Use Depends() for database sessions, authenticated user contexts, and configuration access.
Async / Await Disciplined Execution: Use async def only when awaiting IO (database queries, HTTP calls). Use standard def for synchronous, CPU-bound tasks so FastAPI dispatches them to a threadpool.
fromfastapiimportAPIRouter,Depends,HTTPException,statusfrompydanticimportBaseModel,EmailStr,FieldfromtypingimportAnnotatedrouter=APIRouter(prefix="/v1/users",tags=["users"])# DTO SchemasclassUserCreateRequest(BaseModel):email:EmailStrfull_name:str=Field(min_length=2,max_length=100)classUserResponse(BaseModel):id:stremail:EmailStrfull_name:stris_active:boolclassConfig:from_attributes=True# Route Implementation@router.post("/",response_model=UserResponse,status_code=status.HTTP_201_CREATED)asyncdefcreate_user(payload:UserCreateRequest,db:Annotated[any,Depends(get_db_session)],current_admin:Annotated[any,Depends(get_current_admin_user)],):existing=awaitdb.users.find_by_email(payload.email)ifexisting:raiseHTTPException(status_code=status.HTTP_409_CONFLICT,detail="A user with this email already exists.")user=awaitdb.users.create(payload)returnuser