Path and query parameters
In the previous section, we learned what models are and how they are used to validate request bodies. In this section, you’ll learn what path and query parameters are, the role they play in routing, and how to use them.
Path parameters
Path parameters are parameters included in an API route to identify resources. These parameters serve as an identifier and, sometimes, a bridge to enable further operations in a web application.
We currently have routes for adding a todo and retrieving all the todos in our todo application. Let’s create a new route for retrieving a single todo by appending the todo’s ID as a path parameter.
In todo.py
, add the new route:
from fastapi import APIRouter, Path from model import Todo todo_router = APIRouter() todo_list = [] @todo_router.post("/todo") async def add_todo(todo: Todo) -> dict: todo_list.append(todo) return { ...