1. 路径装饰器
from fastapi import FastAPI, Header, HTTPException, Depends,status
app = FastAPI()
def verify_token(x_token: str = Header()):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="X-Token header invalid")
# return x_token
@app.get("/items/", dependencies=[Depends(verify_token)])
def get_items():
return [{"item": "Foo"}, {"item": "Bar"}]
2. 全局
from fastapi import Depends, FastAPI, Header, HTTPException
def verify_token(x_token: str = Header()):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
app = FastAPI(dependencies=[Depends(verify_token)])
@app.get("/items/")
def get_items():
return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
@app.get("/users/")
def get_users():
return [{"username": "Rick"}, {"username": "Morty"}]