Careeroza
Path Parameters
Declaring Path Parameters
Example
Parts of the path in {braces} become function arguments. The type hint converts and validates the value:
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id, "type": type(user_id).__name__}Requests and responses
GET /users/42
→ 200 {"user_id": 42, "type": "int"}
GET /users/forty-two
→ 422 {"detail": [{"type": "int_parsing", "loc": ["path", "user_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "forty-two"}]}"forty-two" is not an integer, so FastAPI answers with 422 Unprocessable Entity and explains why. Your function is never called.
Route Order
Example
Routes are matched in order: declare fixed paths before parameterised ones.
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/me")
def current_user():
return {"user": "the current user"}
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}Requests and responses
GET /users/me
→ 200 {"user": "the current user"}
GET /users/7
→ 200 {"user_id": 7}Predefined Values with Enum
Example
from enum import Enum
from fastapi import FastAPI
class Level(str, Enum):
basic = "basic"
medium = "medium"
advance = "advance"
app = FastAPI()
@app.get("/levels/{level}")
def get_level(level: Level):
return {"level": level, "is_basic": level is Level.basic}Requests and responses
GET /levels/basic
→ 200 {"level": "basic", "is_basic": true}
GET /levels/expert
→ 422 {"detail": [{"type": "enum", "loc": ["path", "level"], "msg": "Input should be 'basic', 'medium' or 'advance'", "input": "expert", "ctx": {"expected": "'basic', 'medium' or 'advance'"}}]}