Is it possible to create a chain of dependencies in fastapi?

Viewed 30

I want to get json and validate it. I can't just use pedantic @validator because additional validation requires a database connection or other I/O. How should I use all these checks correctly?

This is something that I want (just enumerate all dependencies for Body param)

from __future__ import annotations
from fastapi import FastAPI, Body, Depends
from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel

app = FastAPI()

class ImportModel(BaseModel):
    id: int
    text: str | None

def f1(req: ImportModel = Body()):
    if extra_check1(req):
        return req
    raise RequestValidationError("f1")

def f2(req: ImportModel = Body()):
    if extra_check2(req):
        return req
    raise RequestValidationError("f2")

def f3(req: ImportModel = Body()):
    if extra_check3(req):
        return req
    raise RequestValidationError("f3")

#etc...

@app.post('/import')
def import_smth(req: ImportModel = Depends(f1, f2, f3)):
    return req
1 Answers

If all you need to do is perform checks without returning anything (new), you can just use the dependencies parameter of your path operation decorator:

@app.post("/import", dependencies=[Depends(f1), Depends(f2), Depends(f3)])
def import_smth(req: ImportModel):
    return req
Related