I define a service as a class that provides DRY methods that can be called from anywhere in the code.
My FastAPI controller has an endpoint:
@router.get("/health")
async def health_check():
return {"status": "pass"}
I would like to update it to return MyHelper().get_health_status
, where MyHelper
is defined in ./services/my_helper.py
. What is the standard approach here?
Ideally, I would like to use dependency injection like in .NET core, where the process is roughly:
- Define the service in a namespace (.NET doesn't care about file pathing as long as it's the same root).
- Import the namespace into the
Startup.cs
file. - Register the service with the application in the aforementioned
Startup
file:ConfigureServices(IServiceCollection services)
->services.AddSingleton<IMyHelper, MyHelper>();
- Inject the helper interface into the constructor of any other files in the project.
What's the best way to approach this in a FastAPI project? Is there DI built in or what third party library should be used? If no DI is built in, how do I register my service so I can at least instantiate it inside router ("controller") files?
P.S. I am reading What is a Pythonic way for Dependency Injection?, but am still wondering if there is a preference when using FastAPI specifically. Again, given how REST APIs are basically built into .NET Core and there is a "standard" way (which is not just instantiating helper classes).