#219: Structure your FastAPI Application
With our API, the tests, and the models we get deeper and deeper into FastAPI. It is now a good moment to check what FastAPI suggests on how to structure our application before we start a more complex example.
A structure for bigger FastAPI applications
In the FastAPI documentation we can find this suggested structure for bigger applications:
While that looks good, it misses a place for our tests, models, and the code to access the database. That means we can start with it but quickly run into the problem of finding a space for those not covered parts.
Alternatives
If we search for alternatives on how to structure our FastAPI project, we can find a few good candidates.
- Eric Sales De Andrade created a comprehensive solution in his article "Building and Testing FastAPI CRUD APIs with Pytest - A Step-By-Step Guide" that you can follow along with code samples.
- On FastAPITutorial we can find another way to structure our FastAPI project, even when the article is more focused on testing the application.
While those two approaches work, I am not fully happy with either structure. I would like something like the structure for Flask, that I got from Talk Python Training. Unfortunately, there is not a complete structure in the 3 courses about FastAPI that covers everything at once. That said, nobody is stopping us from condensing the templates used there into a single one:
That looks a bit more like what I had in mind. Let us see how this will work out with a larger application.
Next
There are multiple ways to structure our FastAPI applications. While there is an official guideline on how to do that, it does not cover all the parts that we are going to need. For my next step I am using the combined structure and see how that works out. Next week we put that to a test by building a To-do application that can manage our tasks.