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!
routersYou 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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With