0
0
FastAPIframework~5 mins

Global dependencies in FastAPI

Choose your learning style9 modes available
Introduction

Global dependencies let you run shared code for many parts of your app automatically. This helps keep your code clean and avoid repeating yourself.

You want to check user authentication for many routes.
You need to connect to a database for multiple endpoints.
You want to add common headers or logging for all requests.
You want to share a configuration or resource across your app.
You want to handle errors or validation globally.
Syntax
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI(dependencies=[Depends(your_dependency_function)])
The dependencies list in FastAPI() applies to all routes automatically.
Each dependency function can return values or perform actions before the route runs.
Examples
This example adds a global dependency that provides default query parameters to all routes.
FastAPI
from fastapi import FastAPI, Depends

async def common_parameters():
    return {"q": "default"}

app = FastAPI(dependencies=[Depends(common_parameters)])
This example globally checks a header token for all requests and blocks unauthorized access.
FastAPI
from fastapi import FastAPI, Depends, Header, HTTPException

async def verify_token(x_token: str = Header(...)):
    if x_token != "secret-token":
        raise HTTPException(status_code=400, detail="Invalid Token")

app = FastAPI(dependencies=[Depends(verify_token)])
Sample Program

This FastAPI app uses a global dependency to check a header token on every request. If the token is wrong, it returns an error. Otherwise, it returns a list of items.

FastAPI
from fastapi import FastAPI, Depends, Header, HTTPException

async def verify_token(x_token: str = Header(...)):
    if x_token != "secret-token":
        raise HTTPException(status_code=400, detail="Invalid Token")

app = FastAPI(dependencies=[Depends(verify_token)])

@app.get("/items/")
async def read_items():
    return {"items": ["apple", "banana"]}
OutputSuccess
Important Notes

Global dependencies run before each request handler automatically.

You can combine global dependencies with route-specific dependencies.

Use global dependencies to keep your code DRY (Don't Repeat Yourself).

Summary

Global dependencies apply shared logic to all routes in your FastAPI app.

They help with authentication, database connections, and common validations.

Defined once, they run automatically for every request.