0
0
FastapiHow-ToBeginner · 3 min read

How to Use Global Dependency in FastAPI: Simple Guide

In FastAPI, you can use dependencies parameter in the FastAPI app instance to declare a global dependency that runs for every request. This lets you share common logic like authentication or database sessions across all routes without repeating code.
📐

Syntax

Use the dependencies parameter when creating the FastAPI app to add global dependencies. Each dependency is a function wrapped with Depends. These run before every request handler.

  • FastAPI(dependencies=[Depends(your_dependency)]): Adds global dependencies.
  • Depends(your_dependency): Declares a dependency function.
  • Dependency functions can return values or perform actions like authentication.
python
from fastapi import FastAPI, Depends

def global_dependency():
    print("Global dependency called")

app = FastAPI(dependencies=[Depends(global_dependency)])
💻

Example

This example shows a global dependency that prints a message for every request. It runs before any route handler, demonstrating how to share logic globally.

python
from fastapi import FastAPI, Depends
from fastapi.responses import JSONResponse

# Global dependency function
async def global_dependency():
    print("Global dependency executed")

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

@app.get("/")
async def read_root():
    return JSONResponse({"message": "Hello World"})

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return JSONResponse({"item_id": item_id})
Output
When accessing any route, the console prints: Global dependency executed The HTTP response for GET / is: {"message": "Hello World"} The HTTP response for GET /items/5 is: {"item_id": 5}
⚠️

Common Pitfalls

Common mistakes when using global dependencies include:

  • Defining dependencies that return values but not using them in routes, which wastes resources.
  • Using blocking code inside async dependencies, causing slow responses.
  • Forgetting to use Depends wrapper, so the function is not treated as a dependency.
  • Adding global dependencies that raise exceptions without proper handling, which can block all routes.
python
from fastapi import FastAPI

# Wrong: missing Depends wrapper, so this won't run as a dependency
async def wrong_dependency():
    print("This won't be called globally")

app = FastAPI(dependencies=[wrong_dependency])  # This is incorrect

# Right way:
from fastapi import Depends
app = FastAPI(dependencies=[Depends(wrong_dependency)])
📊

Quick Reference

Summary tips for using global dependencies in FastAPI:

  • Use dependencies=[Depends(your_dependency)] in FastAPI() to apply globally.
  • Global dependencies run before every route handler.
  • Keep global dependencies fast and non-blocking.
  • Use them for shared logic like authentication, logging, or database sessions.
  • Handle exceptions inside dependencies to avoid blocking all routes.

Key Takeaways

Declare global dependencies in FastAPI using the dependencies parameter in the FastAPI app instance.
Wrap dependency functions with Depends to ensure they run before every request.
Use global dependencies for shared logic like authentication or resource setup.
Avoid blocking code and handle exceptions inside global dependencies.
Test that global dependencies run by checking side effects like logs or prints.