Routing with the APIRouter class
The APIRouter class belongs to the FastAPI package and creates path operations for multiple routes. The APIRouter class encourages modularity and organization of application routing and logic.
The APIRouter class is imported from the fastapi package, and an instance is created. The route methods are created and distributed from the instance created, such as the following:
from fastapi import APIRouter
router = APIRouter()
@router.get("/hello")
async def say_hello() -> dict:
return {"message": "Hello!"}
Let’s create a new path operation with the APIRouter class to create and retrieve todos. In the todos folder from the previous chapter, create a new file, todo.py:
(venv)$ touch todo.py
We’ll start by importing the APIRouter class from the fastapi package and creating an instance:
from fastapi import APIRouter todo_router = APIRouter().
Next, we’ll create...