Most Python web frameworks make you choose between testability and convenience. You either have clean code with complex test setup, or you use global state and hope your tests don’t interfere with each other.

FastAPI’s Depends() solves this elegantly.

Here is an example how you would use it in your API:

Article content
We gain a lot of flexibility by injecting the db dependency into our endpoints.

What’s happening here:

Type-safe – Your editor knows repo is a SnippetRepository. Full autocomplete, type checking works.

Automatic cleanup – The context manager ensures the database session closes, even if an exception occurs.

No global state – Every request gets its own session. No risk of one request interfering with another.

Testable – Here’s the magic:

Article content
We can now override the dev db for a test one: no side-effects, tests will run faster.

You override the dependency with an in-memory implementation. Your test doesn’t hit the database. It doesn’t need Docker. It doesn’t even need fixtures to clean up test data. And it runs in milliseconds. 🏃


This is how professional FastAPI applications are structured:

→ Dependencies are functions that provide resources → FastAPI calls them automatically for each request → Tests override dependencies with test doubles → Your endpoint code stays clean – it just declares what it needs

I see too many FastAPI tutorials that skip dependency injection or treat it as “advanced.” However, this is foundational knowledge. If you’re not leveraging Depends(), you’re making testing harder than it needs to be.

I think it’s a nice, practical application of clean architecture in the context of a beloved modern framework. This practice will go a long way towards any app you’ll design afterwards.


Thanks for reading. Let me know in our community how you have used dependency injection in FastAPI or beyond. I am also curious to hear where it didn’t work so well for you, and what you then did to work around it.


And check out our PDC Snipster program, where dependency injection is a first-class citizen. We build the repository pattern first, then wire it into FastAPI using Depends().

The Pybites Developer Cohort provided a motivating, structured environment that helped me bring a full Python project to life. Over six weeks, I shipped Snipster, a CLI + API app for managing code snippets, while sharpening my skills in FastAPI, SQLModel, testing, deployment, and architecture.

— Ben G, Data Engineer