Skip to content

Routers

Default Service Provider#

Pyrannic provides you a service provider which can be used to register automatically your routers.

bootstrap/providers.py
from typing import Type

from app.providers.app import AppServiceProvider

from pyrannic import (
    DatabaseServiceProvider,
    MiddlewaresServiceProvider,
    RoutersServiceProvider,
    ExceptionHandlersServiceProvider,
    ServiceProvider,
)

providers: list[Type[ServiceProvider]] = [
    ExceptionHandlersServiceProvider,
    AppServiceProvider,
    DatabaseServiceProvider,
    RoutersServiceProvider,
    MiddlewaresServiceProvider,
]

With this provider, Pyrannic will get all your modules from the path app/http/routers and search for a router attribute:

app/http/routers/heroes.py
from typing import Annotated

from fastapi import APIRouter, Depends

from app.http.resources.hero import HeroesCollection
from app.repositories.heroes import HeroesRepository

router = APIRouter(tags=["Heroes"])


@router.get("/heroes")
def index(repository: Annotated[HeroesRepository, Depends()]) -> HeroesCollection:
    return HeroesCollection(repository.paginate())

Bootstrapping File#

By default, the provider will register your routers by alphabetic order of the module's name.

But, if you need it, you can customise the order of the registration of your routers creating a new file routers.py in the bootstrap folder of your app. The provider will read the routers list from this file and use it to register them.

bootstrap/routers.py
from fastapi import APIRouter

from app.http.routers.heroes import router as heroes_router
from app.http.routers.villains import router as villains_router


routers: list[APIRouter] = [
    villains_router,
    heroes_router,
]

Custom Service Provider#

To use the default service provider from Pyrannic is not mandatory. You can write your own service provider and register your routes just like you would do it normally in FastAPI.

Custom RoutersServiceProvider
from pyrannic import ServiceProvider
from app.http.routers.heroes import router as heroes_router
from app.http.routers.villains import router as villains_router


class RoutersServiceProvider(ServiceProvider):
    def register(self):
        self.app.include_router(heroes_router)
        self.app.include_router(villains_router)

The property app

The ServiceProvider give you access to the underneath application through the app property. This property is an instance of an ApplicationInterface but, in the end, it is also an instance of a FastAPI application, and you can use all its methods. To know more about the service providers check its documentation.