0
0
FastapiHow-ToBeginner · 3 min read

How to Create Dependency in FastAPI: Simple Guide

In FastAPI, you create a dependency by defining a function and using the Depends class to declare it in your path operation function parameters. FastAPI will automatically run the dependency function and pass its result to your endpoint.
📐

Syntax

To create a dependency in FastAPI, define a function that returns the value or object you want to inject. Then, use Depends in your endpoint function parameters to declare the dependency.

Parts explained:

  • def dependency_function(): - Your dependency provider function.
  • Depends(dependency_function) - Tells FastAPI to run this function and provide its result.
  • Parameter in endpoint function - Receives the value returned by the dependency.
python
from fastapi import FastAPI, Depends

app = FastAPI()

def dependency_function():
    return "Hello from dependency"

@app.get("/")
async def read_root(dep_value: str = Depends(dependency_function)):
    return {"message": dep_value}
💻

Example

This example shows a simple dependency that returns a greeting string. The endpoint uses Depends to get the greeting and returns it in the response.

python
from fastapi import FastAPI, Depends

app = FastAPI()

def get_greeting():
    return "Hello, FastAPI Dependency!"

@app.get("/greet")
async def greet(greeting: str = Depends(get_greeting)):
    return {"greeting": greeting}
Output
{"greeting":"Hello, FastAPI Dependency!"}
⚠️

Common Pitfalls

Common mistakes when creating dependencies in FastAPI:

  • Not using Depends in the endpoint parameter, so the function is not treated as a dependency.
  • Forgetting to return a value from the dependency function.
  • Using synchronous dependencies in async endpoints without async def, which can block the event loop.
  • Trying to pass parameters directly to the dependency function instead of using other dependencies or request data.
python
from fastapi import FastAPI

app = FastAPI()

def wrong_dependency():
    print("This does not return anything")

@app.get("/wrong")
async def wrong(dep: str = wrong_dependency()):  # Wrong: missing Depends and calling function
    return {"dep": dep}

# Correct way:
from fastapi import Depends

def correct_dependency():
    return "Correct value"

@app.get("/correct")
async def correct(dep: str = Depends(correct_dependency)):
    return {"dep": dep}
📊

Quick Reference

FastAPI Dependency Injection Cheat Sheet:

ConceptUsage
Define dependencydef dep_func(): return value
Use dependencyparam: Type = Depends(dep_func)
Async dependencyasync def dep_func(): return value
Multiple dependenciesUse multiple Depends parameters in endpoint
Dependency with parametersUse other dependencies or request data inside dependency function
ConceptUsage
Define dependencydef dep_func(): return value
Use dependencyparam: Type = Depends(dep_func)
Async dependencyasync def dep_func(): return value
Multiple dependenciesUse multiple Depends parameters in endpoint
Dependency with parametersUse other dependencies or request data inside dependency function

Key Takeaways

Use the Depends class to declare dependencies in FastAPI endpoint parameters.
Define dependency functions that return the needed value or object.
FastAPI automatically runs dependencies and injects their results.
Always return a value from your dependency functions.
Use async def for dependencies if your endpoint is async to avoid blocking.