FastAPI multiple dependencies

Sarit Ritwirune
May 21, 2024

--

from fastapi import Header, HTTPException

async def verify_token(x_token: str = Header(...)):
if x_token != "fake-token":
raise HTTPException(status_code=400, detail="X-Token header is invalid")

async def verify_key(x_key: str = Header(...)):
if x_key != "fake-key":
raise HTTPException(status_code=400, detail="X-Key header is invalid")
return x_key

@app.get("/items", dependencies=[Depends(verify_token), Depends(verify_key)])
async def read_items():
return [{"item": "Foo"}, {"item": "bar"}]

To do global dependencies

app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])

--

--

Sarit Ritwirune

On the way to full stack cross-platform. Currently make living by data science.