Python Friday #231: Split a FastAPI Application Into Manageable Parts

As we saw with the OAuth2 and JWT example, our main.py file can grow quickly. If we keep adding features, the file will be unmaintainable in no time. For Flask we used Blueprint to split up the application , for FastAPI we can use APIRouter to do the same.

This post is part of my journey to learn Python. You find the code for this post in my PythonFriday repository on GitHub.

 

Our starting point

To explain the concept of routers, we best start with something smaller. We return to our minimalistic to-do application and continue where we left it . Our main.py currently looks like this:

 

Create the router

To move our existing endpoints into a new router, we can follow this checklist:

  1. Create a new folder routers.
  2. Create the empty __init__.py inside routers.
  3. Create a todo.py inside routers.
  4. Copy your existing endpoints (all except main()) to routers/todo.py.
  5. Create a router object with router = APIRouter()
  6. Replace @app with @router

Our extracted endpoints file now looks like this:

 

Include the router in main.py

In the main.py file, we can remove the extracted endpoints, get rid of all no longer needed imports and tell FastAPI that we want to include our todo router:

 

Run the tests

We only moved code around inside our application. Therefore, all our tests should still work, and we better check if this is indeed the case:

…………………….. [100%]
26 passed in 0.67s

 

Optimise the Router

We currently have /api/todo in the route of all our endpoints. We can add this part as a prefix to the include_router() method in main.py and remove it from the endpoints in our router:

We can run our tests to check that everything still works.

This allows us to change the route for our endpoints at a single place, should that be something we want to do in the future.

Attention: If you set the prefix in include_router() and in APIRouter(), the two prefixes get combined.

 

Next

With APIRouter we not only can separate endpoints by topic, but we can also add endpoints from other packages. That can be helpful for large applications or when we want to use a library to handle all the authentication for us. Next week we extend the to-do application and add a database.

2 thoughts on “Python Friday #231: Split a FastAPI Application Into Manageable Parts”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.