![image](/static/img/ProfessionslsCommunity.png)
In this article we will se a simple example of FastAPI router group. You cat crate router group for deferent model operation as bellow -
from typing import Union
from fastapi import FastAPI, APIRouter
app = FastAPI()
todo_router = APIRouter(prefix="/todo")
@todo_router.get("/all") #URL: /todo/all
def todo_list():
return todos
@todo_router.get("//position]") # URL: /todo/2
def todo_detail(todo_position: int):
return todos[todo_position]
user_router = APIRouter(prefix="/user")
@user_router.get("/all") # URL: /user/all
def user_list():
return ("users": users)
@user_router.get("/fposition)") # URL: /user/2
def user_detail(position: int):
return ("position": users[position])
app.include_router(todo_router)
app.include_router(user_router)
Above example we see there is two router group called todo
and user
. First you need to create a APIRouter
with prefix. Then you need to register group routes to created APIRouter
. And finally you need to include APIRouter
to main FastAPI
app.