0
0
FastAPIframework~5 mins

Dependencies with parameters in FastAPI

Choose your learning style9 modes available
Introduction

Dependencies with parameters let you reuse code that needs extra information to work. This helps keep your app clean and organized.

When you want to check user permissions based on a role passed as a parameter.
When you need to connect to different databases depending on a parameter.
When you want to customize behavior of a dependency based on input values.
When you want to share common logic but with small variations.
When you want to inject configuration values into your dependencies.
Syntax
FastAPI
from fastapi import Depends
from fastapi import FastAPI

app = FastAPI()

def common_dependency(param: str):
    # use param inside
    return f"Value is {param}"

@app.get("/")
async def read_root(value: str = Depends(lambda: common_dependency('example'))):
    return {"message": value}

You define a function that takes parameters and use it inside Depends().

You can pass parameters by wrapping the dependency call in a lambda or another function.

Examples
This example passes a fixed string 'hello' to the dependency and returns it uppercased.
FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

def get_query_param(q: str):
    return q.upper()

@app.get("/items/")
async def read_items(q: str = Depends(lambda: get_query_param('hello'))):
    return {"query": q}
This example checks if the role is 'admin' and raises an error if not.
FastAPI
from fastapi import Depends, FastAPI, HTTPException

app = FastAPI()

def verify_role(role: str):
    if role != "admin":
        raise HTTPException(status_code=403, detail="Not authorized")
    return True

@app.get("/admin/")
async def admin_access(authorized: bool = Depends(lambda: verify_role('admin'))):
    return {"status": "Welcome admin"}
Sample Program

This program defines a dependency that checks if the role is 'user'. The endpoint uses this dependency with the parameter 'user'. If the role is correct, it returns a success message.

FastAPI
from fastapi import FastAPI, Depends, HTTPException

app = FastAPI()

def check_permission(role: str):
    if role != "user":
        raise HTTPException(status_code=403, detail="Access denied")
    return f"Permission granted for {role}"

@app.get("/dashboard")
async def dashboard(permission: str = Depends(lambda: check_permission('user'))):
    return {"message": permission}
OutputSuccess
Important Notes

Use lambda or small wrapper functions to pass parameters to dependencies.

Dependencies with parameters help avoid repeating similar code with small changes.

Remember to handle errors inside dependencies to keep your app safe.

Summary

Dependencies with parameters let you customize shared code.

You pass parameters by wrapping the dependency call.

This keeps your code clean and easy to maintain.