Path and Query Parameters¶
🎯 Goal¶
Understand how to use dynamic values in your API routes via:
- Path parameters: embedded in the URL path
- Query parameters: passed after a
?in the URL
FastAPI uses Python type hints to automatically validate these inputs and generate documentation.
🔗 Path Parameters¶
Path parameters are part of the URL itself and are used to identify specific resources.
🧪 Example: Greeting by Name¶
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello/{name}")
def say_hello(name: str):
return {"message": f"Hello, {name}!"}
{name}is a placeholder in the URL.- FastAPI extracts it and passes it to the function as a
str.
🧭 Try:
/hello/Alice→{"message": "Hello, Alice!"}/hello/Bob→{"message": "Hello, Bob!"}
🔢 Type Conversion and Validation¶
You can specify types like int, float, or bool. FastAPI will:
- Convert the value automatically
- Return a 422 error if the type is invalid
@app.get("/square/{number}")
def square(number: int):
return {"result": number ** 2}
🧭 Try:
/square/5→{"result": 25}/square/five→ ❌ 422 error: invalid integer
❓ Query Parameters¶
Query parameters are passed in the URL after a ?, like /search?term=fastapi.
🧪 Example: Search Endpoint¶
@app.get("/search")
def search(term: str, limit: int = 10):
return {"term": term, "limit": limit}
termis requiredlimitis optional (default = 10)
🧭 Try:
/search?term=fastapi&limit=5→{"term": "fastapi", "limit": 5}/search?term=python→{"term": "python", "limit": 10}
🧠 Optional Parameters¶
You can make parameters optional by giving them default values:
@app.get("/filter")
def filter_items(category: str = "all", active: bool = True):
return {"category": category, "active": active}
🧭 Try:
/filter→{"category": "all", "active": true}/filter?category=books&active=false→{"category": "books", "active": false}
FastAPI automatically converts "false" to False, "true" to True.
🧪 Combined Example: Path + Query¶
@app.get("/users/{user_id}")
def get_user(user_id: int, details: bool = False):
return {"user_id": user_id, "details": details}
🧭 Try:
/users/42→{"user_id": 42, "details": false}/users/42?details=true→{"user_id": 42, "details": true}
🧠 Practice Challenge¶
Try building these endpoints:
/multiply/{x}/{y}→ returns product of two integers/weather?city=Osaka&units=metric→ returns mock weather data/profile/{username}?show_email=true→ returns user profile with optional email