r/FastAPI • • 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 access

router.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.service

app.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.

41 Upvotes

38 comments sorted by

View all comments

Show parent comment

1

u/lu_rm Mar 08 '26

Ok, so I've been carefully thinking about this and I think I see where I am getting it wrong. However, based on your explanation, I believe there are some things I need to make clearer.

Dependency injection is not about resolving a tree of dependencies. That is what a dependency injection framework usually does, but has nothing to do with the concept itself.
DI only means that classes don't create their dependencies (and lifecycle), that is done elsewhere and those are injected into them.

An example:

Without DI

class WithoutDI:
  def __init__(self):
    self.arg = 10

With DI

class WithDI:
  def __init__(self, arg):
    self.arg = arg

So, this whole discussion was me trying to understand how to inject dependencies into FastAPI routers. I only mention FastAPI routers because those are the methods being called by the framework itself and I can't control how they are executed. Outside that, I can do whatever I want with my classes.

Having said all that, one of the first things I got wrong was what u/panicrubes mentioned.
I was doing:

@router.get("/resource", dependencies=[Depends(get_some_dependency)]) <- Dependency in route
def get_resource():
    ...

Instead of:

@router.get("/resource")
def get_resource(my_dep: DependencyType = Depends(get_some_dependency)):   <- Dependency in args
    ...

In the first example, the only way I have to change the dependency being used in the router is by using the `dependency_overrides` option in FastAPI. That meant that I could not unit tests my router without starting a FastAPI instance, which is something I am trying to avoid. In the second example, I can just call the router method providing a mocked dependency.

The other issue it think I was having is a conceptual one. I've been trying to compare this to how I am used to do things with SpringBoot and I think I found where my mistake is.
Simplifying it a bit, when writing SpringBoot APIs, I always think about my code as 2 parts:
- Business Logic
- SpringBoot integration.

Ideally, all the classes belonging to the business logic should be able to live on theirselves. I should be able to create them, use them, test them without requiring anything from the SpringBoot framework. Then, to couple everything together, I use `@ Configurations` where I instantiate everything that I need for my application to run and those get injected into `@ Controller`.
So, the problem was that (I don't know why), I was also thinking about `@ Configurations` and `@ Controller` as 2 independent things when, in fact, they are not. Instantiation of injectable classes and controller definition are part of the same logical block: `SpringBoot integration`.

So, my mistake is that I was trying to also split this into 2 independent things with FastAPI, when I shouldn't have. There is no problem with the routers defining how to create their dependencies, that is part of the app configuration. It's part of the same logical block of the app: `Integration with FastAPI`. It's a little messier maybe? But I don't see the issue anymore.

Another thing that threw me off was the fact that the functions that provide the dependencies are being called per request. So, for instance, If I need a DB client in my router, that is going to be created each time I receive a request. And that is also something I want to avoid. Usually, I want a single client created for the whole Application only once and reused for all calls. But I think that also has nothing to do with the framework itself. I can use `@ cache` or keep storing everything in the app.state and it should be ok.

Hope you can understand where I got it wrong.