Skip to content

Required Body argument with None is not supported #5841

@roynico

Description

@roynico

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

from fastapi import FastAPI, Body
from typing import Optional

app = FastAPI()

@app.post("/")
def post_data(data: Union[str, None] = Body(...)):
      pass

Description

According to the documentation, it is possible to handle a None value for required argument provided by the user. First of all, the example in the documentation doesn't really make sense, since a Python None (i.e. a JSON null) can not be provided in the query a GET request, but has to be sent through the body of a POST/PUT request.
Nevertheless, this is my use case: I have a POST endpoint, with a required (without default) argument, but I want the user to be able to send a null value.
There has been a issue (#1661) for 2 years exactly about this point. It has been claimed, that this is solved in 0.85.1, but I claim that this is not. I report here below more or less the same MWE:

  • store the above code in a file example.py
  • start the fastapi server with uvicorn example:app
  • send a POST request with:
$ curl -X POST "http://localhost:8000/" -d 'null' -H "Content-Type: application/json"
{"detail":[{"loc":["body"],"msg":"field required","type":"value_error.missing"}]}

Expected would be:

$ curl -X POST "http://localhost:8000/" -d 'null' -H "Content-Type: application/json"
null

I tried with other (more recent) versions of fastapi without more success.

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.85.1

Python Version

Python 3.9.2

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions