0
0
FastAPIframework~5 mins

Why dependency injection matters in FastAPI

Choose your learning style9 modes available
Introduction

Dependency injection helps your code stay clean and easy to change. It lets you give parts of your app what they need without hard coding them inside.

When you want to share a database connection across many parts of your app.
When you need to swap one service for another without changing your main code.
When writing tests and you want to replace real parts with fake ones easily.
When you want to keep your code organized and avoid repeating setup steps.
Syntax
FastAPI
from fastapi import Depends

app = FastAPI()

def get_db():
    db = create_db_session()
    try:
        yield db
    finally:
        db.close()

@app.get("/items/")
async def read_items(db = Depends(get_db)):
    return db.query_items()

Depends() tells FastAPI to run the function and give its result to your endpoint.

You can use yield in dependency functions to handle setup and cleanup.

Examples
This example shows using a dependency to check a token before running the endpoint.
FastAPI
from fastapi import Depends, HTTPException

app = FastAPI()

def get_token_header():
    token = "expected-token"
    if token != "expected-token":
        raise HTTPException(status_code=400, detail="Invalid token")
    return token

@app.get("/secure-data")
async def secure_data(token: str = Depends(get_token_header)):
    return {"data": "This is secure"}
Here, a class instance is injected as a dependency to keep code clean and testable.
FastAPI
from fastapi import Depends

app = FastAPI()

class Service:
    def do_work(self):
        return "work done"

def get_service():
    return Service()

@app.get("/work")
async def work(service: Service = Depends(get_service)):
    return {"result": service.do_work()}
Sample Program

This simple FastAPI app shows how dependency injection passes a message to the endpoint without hard coding it inside.

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

# Dependency function
async def get_message():
    return "Hello from dependency!"

# Endpoint using dependency injection
@app.get("/greet")
async def greet(message: str = Depends(get_message)):
    return {"message": message}
OutputSuccess
Important Notes

Dependencies can be reused in many endpoints to avoid repeating code.

Using dependency injection makes testing easier by allowing you to swap real parts with mocks.

FastAPI handles calling and cleaning up dependencies automatically.

Summary

Dependency injection helps keep your code clean and flexible.

It allows easy sharing and swapping of parts like services or database connections.

FastAPI makes using dependency injection simple with the Depends function.