Skip to main content
In this article, we refactor our FastAPI application by separating user and post path operations (CRUD operations) into distinct files. Initially, our main.py file contains all endpoints, which can lead to clutter as the application grows.

Current Main.py Structure

Initially, our main.py file includes endpoints such as:
During execution, you might observe logs like these:
In addition to posts, main.py also handles user operations, such as creating a new user or retrieving a user by ID:
Managing all endpoints in one file can become unwieldy as your application grows.
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 named routers 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 the user.py file, the code for handling user-related endpoints looks like this:
Later, once this code is moved from main.py, you can safely remove the user-related endpoints from it.

Post Router Example

Likewise, in the post.py file, the post-related endpoints are refactored as follows:
Replace the usage of the FastAPI instance (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 the routers directory:
With these changes, FastAPI delegates request handling to the appropriate router based on the URL endpoints, keeping the code modular and manageable as the application grows.

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
For instance, a successful post creation might respond with:
And the server logs may display:
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.
Happy coding!

Watch Video