
FastAPI
Path parameters are variables in the URL that let you pass dynamic values to your endpoints.
Path parameters are parts of the URL that change. For example:
/users/123 ← 123 is the path parameter
/posts/456 ← 456 is the path parameter
/items/my-item ← my-item is the path parameterfrom fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
async def get_user(user_id: int):
return {"user_id": user_id}Now you can visit:
FastAPI validates types automatically:
@app.get("/users/{user_id}")
async def get_user(user_id: int):
# user_id MUST be an integer
# http://localhost:8000/users/abc → Error
return {"user_id": user_id}You can have multiple parameters:
@app.get("/users/{user_id}/posts/{post_id}")
async def get_user_post(user_id: int, post_id: int):
return {
"user_id": user_id,
"post_id": post_id
}Visit: `http://localhost:8000/users/123/posts/456`
Returns: `{"user_id": 123, "post_id": 456}`
Path parameters can be strings:
@app.get("/files/{filename}")
async def get_file(filename: str):
return {"filename": filename}Visit: `http://localhost:8000/files/document.pdf`
Returns: `{"filename": "document.pdf"}`
The URL path should match your parameter names:
# ✅ Correct
@app.get("/users/{user_id}")
async def get_user(user_id: int):
return {"user_id": user_id}
# ❌ Wrong - parameter order in URL matters
@app.get("/posts/{post_id}/users/{user_id}")
# Must have post_id before user_id in URL@app.get("/api/v1/users/{user_id}")
async def get_user(user_id: int):
# Fetch from database
user = db.get_user(user_id)
if not user:
return {"error": "User not found"}
return user
@app.get("/api/v1/posts/{post_id}/comments/{comment_id}")
async def get_comment(post_id: int, comment_id: int):
comment = db.get_comment(post_id, comment_id)
return commentResources
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