0
0
FastAPIframework~5 mins

Depends function basics in FastAPI

Choose your learning style9 modes available
Introduction

The Depends function helps you share and reuse code in FastAPI by letting you declare dependencies easily.

When you want to reuse common logic like getting a database connection in many places.
When you need to check user authentication before running an endpoint.
When you want to separate concerns by moving code out of your main route functions.
When you want FastAPI to automatically handle calling helper functions and passing their results.
When you want cleaner and more organized code by using dependency injection.
Syntax
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def common_logic():
    # some reusable code
    return 'result'

@app.get("/items/")
async def read_items(data=Depends(common_logic)):
    return {"data": data}

Depends wraps a function that FastAPI will call automatically.

The result of the dependency function is passed as an argument to your route function.

Examples
This example shows a simple dependency that returns a token string.
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_token():
    return "token123"

@app.get("/secure-data")
async def secure_data(token: str = Depends(get_token)):
    return {"token": token}
This example uses a dependency with a parameter and returns it to the route.
FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

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

@app.get("/search")
async def search(params: dict = Depends(common_parameters)):
    return params
Sample Program

This program defines a dependency function get_message that returns a greeting string. The route /greet uses Depends to call this function automatically and returns its result in JSON.

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

def get_message():
    return "Hello from dependency!"

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

Dependencies can be functions or classes.

FastAPI handles calling dependencies and passing their results automatically.

Use dependencies to keep your code clean and reusable.

Summary

Depends helps reuse code by injecting dependencies into routes.

It makes your code cleaner and easier to maintain.

FastAPI calls dependency functions automatically and passes their results.