FastAPI Routers

  • It can become quite cluttered if you have all your routes in the main.py file

  • That's why the best approach is to split this into 2 files

    • One of them should contain all the CRUD operations

    • The other should contain all the user paths

  • This is not as simple as just moving the paths to a different file

  • This will be done by something called routers

Currently our structure looks like this:

main.py

We will have to update to this:

  • Fist we will add a folder called routers

  • Within this we will create 2 files:

    • post.py

    • users.py

  • Now we will have to move all the routes from main.py

    • The ones for posts in post.py

    • The ones for users in users.py

Note: This will create a lot of issues initially as we will have to do all the imports for the files. These were initially imported in main.py

users.py

post.py

We have an issue where we do not have access to the "app" object within our other files

  • Fist instinct would be to import the app object but that is not exactly correct

  • We will have to make use of the routers

  • We will have to import APIRoutersfirst

  • Next we will create the routerobject

  • After which we will replace the appobject with the routerobject

  • It's more or less the same for the post.pyfile as well

The last step is to make the reference in our main.py file

  • Otherwise the API will not work

  • We will import the post and user from the routers folder

  • Then we will use the app object to import the post and user routers

How does this work?

  • If we get a request, the above 2 lines will check the post and user files respectively and see if we have a match within those

  • If a request hits one of the routes in the files, it will work as it did previously with everything in main.py

Last updated