Current Main.py Structure
Initially, our main.py file includes endpoints such as:Splitting your endpoints into separate files makes your code more modular and maintainable.
Organizing Code with Routers
To streamline our application structure, we create a new directory namedrouters and add two files inside it: post.py and user.py. This allows us to move all post-related operations to post.py and user-related operations to user.py.
User Router Example
In theuser.py file, the code for handling user-related endpoints looks like this:
Post Router Example
Likewise, in thepost.py file, the post-related endpoints are refactored as follows:
app) with the router object (router) in each file. This makes the routes modular and easier to manage.
Integrating Routers in main.py
After splitting the routes into separate files, update your main.py to include the routers from therouters directory:
Testing the Application
Once refactored, test your application to confirm that all functionality operates as expected. Typical tests include:- Fetching all posts
- Creating a new post
- Retrieving a single post by ID
- Deleting or updating posts
- Creating a new user and retrieving the user by ID
Using routers helps keep your code clean and scalable. As your API grows, you can easily add new routers without cluttering the main application file.