Search code examples
fastapipydantic

pydantic Optional Form returns 422 on post when form is missing


How can I get an optional Form,

@app.post("/config", include_in_schema=False)
async def postconfig(request: Request,
    gitlabtoken:str = Form(...),
    gitlaburl:str = Form(...),
    projectids:str = Form(...),
    jobscopes:str = Form(...),
    filter:str = Form(...),
    blacklist:str = Form(...),
    historyurls:Optional[str] = Form(...)
):
    """ update config fields in mem """

When I post updates with historyurls="", it fails passing pydantic returning 422:

{"detail":[{"type":"missing","loc":["body","historyurls"],"msg":"Field required","input":null,"url":"https://errors.pydantic.dev/2.5/v/missing"}]}

I can add something to historyurls, or I can also use pydantic.ValidationError, but should not the Optional take care of this?


Solution

  • Make historyurls accept None by explicitly setting None as the default value:

    historyurls: str = Form(None)
    

    or,

    historyurls: Optional[str] = Form(None)