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