4 - Path Parameters and Numeric Validations#
In the same way that we can declare validations and metadata for query parameters with Query, we can declare validations and metadata with Path.
from typing import Annotated
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/items6/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")],
q: Annotated[str | None, Query(alias="item-query")] = None,
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
import requests
url = 'http://127.0.0.1:8000'
params = {
'item-query': 'chu'
}
requests.get(url + '/items6/895', params=params).json()
{'item_id': 895, 'q': 'chu'}
Number Validations#
With Query and Path, we can declare number restraints:
gt: Greater thanlt: Less thange: Greater than or equal tole: Less than or equal to
@app.get("/items7/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get", ge=1, lt=10000)], q: str
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
params = {
'q': 'pikachu'
}
requests.get(url + '/items7/995', params=params).json()
{'item_id': 995, 'q': 'pikachu'}