Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple routers be registered at once in FastAPI?

Tags:

python

fastapi

I have found in the documentation that routers are registered like this:

app.include_router(router1)
app.include_router(router2)

but this seems unnecessarily verbose if I jut want to include a list of routers (like if i have 100 i have to repeat this 100 times? Is there a way to pass them in a list or something?Thanks!

like image 615
KZiovas Avatar asked Oct 28 '25 13:10

KZiovas


1 Answers

Iterate over a sequence of routers

Simple for loop

You can use a for loop with the list of the routers you want:

for router in router1, router2, router3:
    account.include_router(router)

You would still need to make a list that contains all your routers, one way or another, however.

If you want to store the sequence outside the for loop, it's recommended to use a tuple instead of a list for simplicity of data-structures:

routers = router1, router2, router3

for router in routers:
    account.include_router(router)

Function to extract fastapi.APIRouter from a module

If you have a great number of routes, you can do something like this, assuming they are in a single module, but you can adapt it to multiple modules :

def include_router_from_module(target, module):
    module_attributes = vars(module)
    
    for attribute in module_attributes.values():
        if isinstance(attribute, fastapi.APIRouter):
            target.include_router(attribute)

include_router_from_module(app, your_module)
like image 168
Loïc Ribere Avatar answered Oct 30 '25 03:10

Loïc Ribere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!