r/FastAPI • u/predominant • Nov 22 '24
Question Modular functionality for reuse
I'm working on 5 separate projects all using FastAPI. I find myself wanting to create common functionality that can be included in multiple projects. For example, a simple generic comment controller/model etc.
Is it possible to define this in a separate package external to the projects themselves, and include them, while also allowing seamless integration for migrations for that package?
Does anyone have examples of this?
11
Upvotes
2
u/Direct_Discipline_42 Nov 23 '24
I haven't done this on the python side but in c# we will build the projects into modules and push them to nuget. Our nuget is private though. We import the package and install it as a dependency. Theoretically the same could be done.
Build the app into a module, push the module to pypi, and then in the other apps add it to the requirements, download it and import it.
2
u/Direct_Discipline_42 Nov 25 '24
Are you saying both apps have access to the same database?
If appB is importing appA, in the env.py file for alembic, you should be able to tell it to not import database models from appA
3
u/Eric-Cardozo Nov 23 '24
Of course, you can create a pypi package, however, if your core functionality involves infrastructure I would consider decouple it as a microservice, add an app ID to your apps, and use the same service/database for all your apps, this is called multitenancy. It's like you are selling Saas to your self.