Routers in FastAPI

Posted by Daksh on Wednesday, November 16, 2022

Routers

Routers are used to group the endpoints in different logical ways (structure your application into multiple files and components).

Separation is done on the basis of operations. It can be used to share tags and a prefix between multiple operations. It allows us to share the tags and assign them to all the operations that are assigned to that particual router.

# step 1: create a router
# routers is a directory/package
# items is a file in the routers directory/package
from fastapi import APIRouter

router = APIRouter(
    # this prefix will be auto-applied to all the endpoints in this router
    prefix="/items",
    # this tag will be auto-applied to all the endpoints in this router
    tags=["items"],
    responses={404: {"description": "Not found"}},
)

@router.get("/", tags=["another tag"])
# this endpoint will be auto-prefixed by /items/
# all the endpoints in this router will be auto-tagged and auto-prefixed by items
# there will be two tags for this endpoint: items and another tag
def read_items():
    # do something

@router.post("/create")
# this endpoint will be /items/create
def create_item():
    # do something

# step 2: add the router to the main app
from routers import items
from fastapi import FastAPI

app = FastAPI()

# items.<name-of-the-router-instance>
app.include_router(items.router)

You can also create get and post endpoints in different router files and then include them in the main app.