Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Global Dependencies doc example not working as-is #4978

@jerinpetergeorge

Description

@jerinpetergeorge

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

# code snippet copied from the official documentation

from fastapi import Depends, FastAPI, Header, HTTPException


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 = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])


@app.get("/items/")
async def read_items():
    return [{"item": "Portal Gun"}, {"item": "Plumbus"}]


@app.get("/users/")
async def read_users():
    return [{"username": "Rick"}, {"username": "Morty"}]

Description

TL;DR: maybe related to #4906

I was following the documentation of Global Dependencies and the example in the documentation is not working as expected.

I am getting the 422 status code with the following response

{
    "detail": [
        {
            "loc": [
                "header",
                "x-token"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        },
        {
            "loc": [
                "header",
                "x-key"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

Adding a default parameter to the Header(...) solved the issue

async def verify_token(x_token: str = Header(default=None)):
    ...


async def verify_key(x_key: str = Header(default=None)):
    ...

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.78.0

Python Version

3.8.10

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions