Fastapi

Page content

FastAPI - Dependencies and Custom Headers

Source

Code

from fastapi import Depends, FastAPI, Header, HTTPException

app = FastAPI()


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


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


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

Test’s

Failed

no Custom Header

curl -s http://localhost/api/items/ |jq
{
  "detail": [
    {
      "loc": [
        "header",
        "x-token"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": [
        "header",
        "x-key"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

adding “x-token”

curl -s -H "x-token: fake-super-secret-token" http://localhost/api/items/ |jq
{
  "detail": [
    {
      "loc": [
        "header",
        "x-key"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

Success

adding “x-token” and “x-key”

curl -s -H "x-key: fake-super-secret-key" -H "x-token: fake-super-secret-token" http://localhost/api/items/ |jq '.'
[
  {
    "item": "Foo"
  },
  {
    "item": "Bar"
  }
]

Middleware

some further middleware and examples

x-robots-tag Header

@app.middleware("http")
async def add_noindex(request: Request, call_next):
    response = await call_next(request)
    response.headers["x-robots-tag"] = 'noindex, nofollow'
    return response

Check for Mobile Header

from fastapi import FastAPI, Request
from starlette.responses import JSONResponse, Response

app = FastAPI()

@app.middleware("http")
async def verify_user_agent(request: Request, call_next):
    if request.headers['User-Agent'].find("Mobile") == -1:
        response = await call_next(request)
        return response
    else:
        return JSONResponse(content={
            "message": "we do not allow mobiles"
        }, status_code=401)


@app.get('/')
def index(request: Request, response: Response):
    return {'message': 'ok'}

CORS

from fastapi import FastAPI, Request
from starlette.responses import Response
from fastapi.middleware.wsgi import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
@app.get('/')
def index(request: Request, response: Response):
    return {'message': 'ok'}

Any Comments ?

sha256: 5978695a71efb9002e65888059a4c217cfe995de6c4edf602073b5eea11cef8a