fastapi-decorators

raw JSON →
1.0.20 verified Fri May 01 auth: no python

A utility library for FastAPI that lets you create decorators for endpoints using FastAPI's dependency injection. It provides a @depends decorator that wraps dependencies and preserves type hints, making it easy to reuse common preprocessing logic. Current version: 1.0.20. Released intermittently, with bugfix and compatibility improvements.

pip install fastapi-decorators
error ImportError: cannot import name 'depends' from 'fastapi_decorators'
cause Older versions of the library had different export names; also possible typo in import path.
fix
Ensure you have fastapi-decorators >=1.0.0 installed. Use from fastapi_decorators import depends.
error TypeError: 'Depends' object is not callable
cause Attempting to use `Depends` (uppercase) from fastapi_decorators instead of the correct lowercase `depends`.
fix
Use from fastapi_decorators import depends and apply it as a decorator: @depends(some_dependency).
error fastapi.exceptions.FastAPIError: Invalid args for response field...
cause ForwardRef (string annotation) in the dependency function that was not resolved due to version <1.0.16.
fix
Upgrade to fastapi-decorators >=1.0.16. If that's not possible, replace string annotations with actual type references.
gotcha The @depends decorator modifies the function signature. If your endpoint has additional dependencies, ensure they are ordered correctly. The wrapped dependency becomes a parameter in the endpoint's signature.
fix Always include the dependency as a parameter in the endpoint function with Depends() if you need to access its return value; otherwise, the return value is lost.
gotcha In versions before 1.0.20, explicit `-> None` return annotations on the dependency function were not preserved in the wrapped endpoint's signature. This could break type checkers expecting `None` returns.
fix Upgrade to 1.0.20 or later, or omit explicit `-> None` from dependency functions.
gotcha ForwardRef (string-based) annotations in dependency functions may fail to resolve in versions <1.0.16. This causes a runtime error when FastAPI tries to build the endpoint's OpenAPI schema.
fix Upgrade to 1.0.16 or later, or avoid forward reference annotations in dependency functions.

Create a reusable dependency decorator that extracts a token, then apply it to an endpoint. The dependency is injected as a parameter.

from fastapi import FastAPI, Depends, HTTPException
from fastapi_decorators import depends

app = FastAPI()

def verify_token(authorization: str = Depends(oauth2_scheme)):
    if authorization != "valid_token":
        raise HTTPException(status_code=401)
    return authorization

@app.get("/secure")
@depends(verify_token)
async def secure_endpoint(token: str = Depends(verify_token)):
    return {"token": token}