0
0
FastAPIframework~5 mins

Shared dependencies in FastAPI

Choose your learning style9 modes available
Introduction

Shared dependencies let you reuse code easily in different parts of your FastAPI app. This helps keep your code clean and simple.

When you want to use the same database connection in multiple routes.
When you need to check user authentication in many places.
When you want to apply the same logic or data validation across several endpoints.
When you want to share common settings or configurations in your app.
When you want to avoid repeating code for things like logging or error handling.
Syntax
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def common_dependency():
    # code to run
    return "value"

@app.get("/items/")
async def read_items(dep=Depends(common_dependency)):
    return dep

Use Depends() to declare a dependency in your path operation function.

FastAPI will run the dependency function and pass its result to your endpoint.

Examples
This example shares a token header dependency for the /users/ endpoint.
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_token_header():
    return "token123"

@app.get("/users/")
async def read_users(token: str = Depends(get_token_header)):
    return {"token": token}
This example shares query parameters as a dependency.
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def common_parameters(q: str = None):
    return {"q": q}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons
Sample Program

This program shows a shared database connection dependency used in two routes. Both routes get the same 'db' value from get_db.

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_db():
    db = "database connection"
    try:
        yield db
    finally:
        pass  # close connection here

@app.get("/users/")
async def read_users(db=Depends(get_db)):
    return {"db": db, "message": "Users fetched"}

@app.get("/items/")
async def read_items(db=Depends(get_db)):
    return {"db": db, "message": "Items fetched"}
OutputSuccess
Important Notes

Dependencies can be functions or classes.

Use yield in dependencies to handle setup and cleanup (like opening and closing a database connection).

Shared dependencies help keep your code DRY (Don't Repeat Yourself).

Summary

Shared dependencies let you reuse code across multiple routes.

Use Depends() to declare dependencies in FastAPI.

They help keep your app clean and easy to maintain.