APIRouter to help you structure larger applications in a clean, modular way.
Application Structure
For bigger applications, you typically organize code like this:APIRouter
TheAPIRouter class works similarly to FastAPI - it allows you to define path operations that can later be included in your main application.
Creating a Router
Create a router in a separate file (e.g.,routers/users.py):
Router with Prefix and Tags
You can configure routers with common parameters:Including Routers
In your main application file (main.py), include the routers:
When using
prefix, don’t include leading slashes in your router’s path operations. The prefix is automatically prepended.Router Parameters
TheAPIRouter accepts several parameters:
1
prefix
A path prefix for all routes in the router. Must start with
/ and not end with /.2
tags
Tags to apply to all path operations in the router for OpenAPI documentation.
3
dependencies
Dependencies to apply to all path operations in the router.
4
responses
Additional responses to show in OpenAPI documentation.
include_router() Parameters
When including a router in your app, you can override or add to the router’s configuration:Parameters specified in
include_router() are added to those defined in the router itself. Both sets of tags, dependencies, and responses will be applied.Multiple Routers
You can include the same router multiple times with different configurations:Nested Routers
You can also include routers within other routers:Benefits
1
Modularity
Keep related endpoints together in separate files, making your codebase easier to navigate and maintain.
2
Reusability
Reuse routers in different applications or include the same router multiple times with different configurations.
3
Team Collaboration
Different team members can work on different routers without conflicts.
4
Testing
Test routers independently before integrating them into the main application.