Python Friday #221: Refactor the FastAPI To-Do Application

Our minimalistic to-do application has collected some code smells. In this post we go through them and refactor our code to keep the application in a maintainable state for the upcoming changes.

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

 

Remove the duplication in our tests

When it comes to creating tasks, we only care in the test_create_task() function about all the necessary details that this operation involves. For all the other tests, we create tasks to have something with which we can work. Instead of repeating the details in every test, we can extract the code and put it in its own prepare_task() function:

This allows us to remove the duplication in our tests and replace it with a call to our new method:

This is much smaller than what we had before:

 

Refactor the API

The data store is only a mock that we replace in the future with a real database. But even with that in mind it is a bit unlucky that we have the logic for the data access copied throughout our endpoints.

If we encapsulate all the behaviour that interacts with our mock storage into its own class, we not only have smaller endpoints, but we can make sure that we do not reassign already used Ids for free. But before we can profit from the new possibilities, we must do the work.

To shorten this post, here are all the tests we need for our data store. You would write one test, write the implementation, and then repeat with the next test.

With our tests we can come up with a class like this DataStore inside the data folder:

Again, do not forget to create an empty __init__.py inside the data folder next to the datastore.py.

We can now rewrite our FastAPI application and then run the tests to check that everything still works as expected:

After extracting all the logic to store and retrieve data, our API is reduced to a thin layer over our data store. The more logic we can take out of our API, the better it is. Then it is much easier to reuse Python classes than API endpoints.

 

Next

The refactorings help us to keep our code in a better state. We will notice the improvement as soon as we need to add new features, and that usually happens sooner than later.

While checking if the Swagger documentation still works, I noticed two missing features that I like to add next week so that we can put our new structure to a test.

2 thoughts on “Python Friday #221: Refactor the FastAPI To-Do Application”

Leave a Comment

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