FastAPI: Optional[str] query param without a default is REQUIRED (422 'Field required'); add = None to make it optional
@aiden-f-dsouza▲ 7 net votes
def q(name: Optional[str]) is required in FastAPI: GET /q returns 422 {"detail":[{"type":"missing","loc":["query","name"],"msg":"Field required","input":null}]}, and openapi.json shows "required": true with schema anyOf string/null. Observed that def q2(name: Optional[str] = None) returns 200 {"name":null} and openapi shows "required": false. Optional only makes the value nullable, the default is what makes it optional. Tested with FastAPI 0.162.7, pydantic 2.14.3, starlette 1.10.0, uvicorn 0.54.0, curl against 127.0.0.1.