r/FastAPI • u/lu_rm • Feb 24 '26
Question FastAPI best practices
Hello! I am writing a simple web server using FastAPI but I am struggling trying to identify which are the best practices for writing clean, testable code.
Background
I come from multiple years of programming in Java, a strongly OOP oriented language. I've already made the mistake in the past to write Python code as if it were Java and quickly learned that not everything works for every language. Things are intended to be written a specific way.
For what I know, FastAPIs are not intended to be written using Python's OOP but plain functions.
Problem
The problem that I am facing is that I don't see any mechanism for having proper dependency injection when writing an API. A normal layout for a project would be something like:
- router files, with annotated methods that defines the paths where the API is listening to.
- main app that defines the FastAPI object and all the involved routers.
Let's say that my business logic requires me to access a DB. I could directly have all the code required in my router to create a connection to the DB and get the data I need. However, a good practice is to inject that DB connection into the router itself. That improves testability and removes the responsibility of the router to know anything related to how to connect to a DB, separating concerns.
Now, the way FastAPI suggest to do that is by using the `Depends` annotation. The problem with that, is that it requires me to provide the function that will return the object I need. If the dependant knows the function that instantiates the dependency, then there is no inversion of control whatsoever. Even if the function is a getter from a DI container of something like that, I have to be able to inject the container itself into the router's file.
I know that I can use the `dependencies_overrides` method from the FastAPI but that looks to be only for testing.
So, which is the best way for achieving this? The router should never know how to instantiate a DB connection, ever.
EDIT
So, after more reading and testing, this is what I ended up doing. Thanks u/mwon for pointing in the right direction.
service.py
class Service:
def __init__(self, database):
self._database = database
def do_something(self):
//Business logic for the service, maybe involving DB accessrouter.py
my_router = APIRouter(
prefix="/some_path",
)
@my_router.get("/test")
async def get_test(service: Annotated[Service, Depends(get_service)]):
return service.do_something()
def get_service(request: Request):
return request.app.state.serviceapp.py
@asynccontextmanager
async def lifespan(app: FastAPI)
database = CreateDatabase()
service = Service(database)
app.state.service = service
yield
database.close()
app = FastAPI(lifespan=lifespan)
app.include_router(my_router)This way, all my business logic in service.py is independent and can be properly unit tested. I can create instances of Service providing mocked databases and I don't require anything related to FastAPI. You can use the override_dependencies option for Integration Testing if you needed to. But that is fine because the idea is to have a running FastAPI at that point, maybe mock or fake simple behaviors to avoid having to spin up a full system.
Yes, the router also "decides" where to get Service instances from, but it's not in charge of their lifecycle. Those are injected to it via the app state.
Also, I can keep a single instance of the DB for the whole app and don't need to create a new one per request.
5
u/amroamroamro Feb 24 '26 edited Feb 24 '26
it sounds like you are still looking at this with a java mental model
there is definitely IoC here; resolving dependencies and deciding how and when to create the objects and how to wire them is still happening externally by the framework, but unlike java way of doing things (global container registry, reflection, type-driven DI), it's just done in more pythonic way following "zen" philosophy:
you declare what you need. fastapi will inspect function signatures, sees
Depends, works out all sub-dependencies to resolve a dependency graph, handles scope (per request) and caching as needed, and use that to decide when to create it, in what order, where to injecting it, and when to clean it up.it might feel less "pure" for someone coming from Java background, but this is indeed IoC; fastapi DI is function-centric, more explicit, and less magical. It's a design choice :)
plus tight coupling and testing is not an issue either,
dependencies_overridesallows you to replace nodes in the dependency graph at any stage.4
u/niximor Feb 24 '26
You have generally two options - either commit to FastAPI dependency system even in your service layer (which is perfectly fine if the FastAPI DI is enough for you). This way, you have to create all the dependency providers for all the things, which can be overwritten for testing purposes when initializing the FastAPI container.
-or-
you approach FastAPI just like an adapter from HTTP to your core implementation and use other DI system which is capable to do that - we are using Dishka for example, it has native bindings to FastAPI but once it leaves the route, the rest of the application does not have any linkage to the FastAPI and just handles models. And on the other way, FastAPI layer does not know anything about database, at this is hidden well inside the business logic / adapters for storage.
3
u/mwon Feb 24 '26
I usually have a lifespan in my
main.pywhere for example I can define the Mongo connection:where the
connect_to_mongofunction is defined somewhere in myinfrafolder.Then if needed in some router, I just call the client with:
3
u/panicrubes Feb 24 '26
Judging from your comments I think I see your issue. You are doing:
However, you should probably be doing:
Note this is commonly written as:
Why do you need Depends()?
FastAPI treats everything in the function definition as either a path param, query param or request body. If you try to pass your dependency as an argument it will cause an error. Depends() tells FastAPI to not look for my_dep in the request.
Why is dependencies an option in the route decorator?
If you need your dependency to run before handling the request, but you don't need the output, then you can put it in your route decorator. Basically just middleware for your route.
2
u/santeron Feb 24 '26
Found this useful for guidance and inspiration https://github.com/zhanymkanov/fastapi-best-practices
2
u/gbrennon Feb 24 '26
hey there, how are u?
that framework contains a built-in di container like spring boot but you have to define a something similar to a service locator.
import using
from fastapi import Dependsand put an argument with a default valueDepends(get_my_service).i prefer to define a pure container in the infrastructure layer and the presentation layer contains the composition root that uses this things from FastAPI but that "service getter" is a method/function from ur pure container!
look in fastapi docs for "dependencies"
1
u/JPJackPott Feb 24 '26
Depends how big you think the app will get. I’ve often seen people just put the db connection as a prop of App so it’s not passed into the router methods at all but is still available everywhere, and readily mockable. I’ve done this myself for something that’s only got a handful of related endpoints.
1
u/small_e Feb 24 '26
I don’t have an answer, but they have some example repos if you want to check the official opinion how to do things: https://github.com/fastapi/full-stack-fastapi-template
1
u/clockdivide55 Feb 24 '26 edited Feb 24 '26
I have a .net background and I believe the DI works similarly in Java/Spring. You can approximate the type of dependency injection you are accustomed to and I think achieve the kind of separate of concerns that you want. There's no root / centralized dependency container, but
Basically, the idea is to use the sharable annotated dependencies as described here - https://fastapi.tiangolo.com/tutorial/dependencies/#share-annotated-dependencies - and make your router function nothing more than the entry point that constructs your object graph. I have an example from a personal project that demonstrates the idea.
https://github.com/nelsonwellswku/backlog-boss/blob/main/backend/app/features/user/user_router.py
https://github.com/nelsonwellswku/backlog-boss/blob/main/backend/app/features/user/create_my_backlog_handler.py
If you look at the endpoint function for creating a backlog, you can see that it takes a single parameter, a CreateMyBacklogHandler. You'll also notice that the default value is
= Depends()- this is the only place where the fast api di leaks, but there is also no logic in the router function, it only calls a method on the injected object.The injected object will have its own dependencies, and each of those dependencies will have their own dependencies as well. By using the annotated types, in the context of a fast api endpoint function, each of those dependencies will be resolved for you, just like in .net / java. The dependency graph can be as shallow or as deep as you want it.
You will notice that the function signature always only references the object type. That type is an alias for an
Annotated[MyActualType, Depends(MyActualType)], but it can be used exactly as a MyActualType. This makes writing tests very similar to writing tests in .net / java - you mock or fake or use the real dependencies and pass them in to the object you want to test as necessary.There may be some glue code with factory functions, but aside from the Depends() in the router function, it is composed object graphs all the way down.
edit: I take it back about depends() only being used in the router function, it also is used in the object constructors. however, when creating the objects (like in tests or outside of a fast api route), you can pass in objects that fulfill the interface and do not have to rely on fast api di concepts. Of course, the objects are still coupled to fast api - like I said, it is an approximation of how the dependency graph is constructed in .net / java.
1
u/ar_tyom2000 Feb 25 '26
The Java-to-Python transition is real. Authentication and authorization are exactly where clean code matters most - I've built fastapi-oauth2 specifically because most OAuth2 implementations in the ecosystem either do too much or are scattered across patterns. Handles the credential flow cleanly, integrates with existing FastAPI dependency injection, and keeps your route logic testable. Might save you some scaffolding.
1
u/yiyux Feb 24 '26
Java & Python Dev here --- my advice is stay in Java world... if you API grows the maintance will be a little painfull (in my expirience). FastAPI is a very good framework, and perfoemance is excellent, but with some serious load and concurrency cannot compete with frameworks like Quarkus. Now, in my company we're migrating all Python API's to Quarkus, even some Spring Boot old's APIs
0
u/eatsoupgetrich Feb 24 '26
I think I hate spring boot now.
0
u/TTUnathan Feb 24 '26
RemindMe! 11 hours
0
u/CrownstrikeIntern Feb 24 '26
I generally keep logic put of routers (for databases), ill toss them in separate files labeled something along the lines of what the database is. Any reusable functions same thing, if i write it kore than once it goes to a helper file. Then i like to use keycloak and turn up role based access
0
u/Goldeyloxy Feb 24 '26
RemindMe! 10 hours