1

I define the class I am assuming for the parameters. I want the parameters (eg param1 to potentially have a value of None):

    class A(BaseModel):
        param1: Union[int, None] = None #Optional[int] = None
        param2: Optional[int]
            
    @app.post("/A_endpoint/", response_model=A)
    def create_A(a: A):
        # do something with a 
        return a

When I call the endpoint:

curl -X 'POST' \
'http://0.0.0.0:7012/A_endpoint' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"param1": None,
"param2": 1,
}'

I get the error 422:

{
 "detail": [
   {
     "loc": [
     "body",
     65
    ],
     "msg": "Expecting value: line 4 column 14 (char 65)",
     "type": "value_error.jsondecode",
     "ctx": {
      "msg": "Expecting value",
      "doc": "{\n  "param1" = None, \n "param2" = 1}",
      "pos": 65,
      "lineno": 4,
      "colno": 14
     }
    }
 ]
}

I understand that the default value can be None when I omit this parameter (that works). But how can I allow None to be a possible value for param1 explicitly?

Thanks!

edgarbc
  • 366
  • 2
  • 15

1 Answers1

1

You're actually sending the literal value "None". This is not a valid integer or null.

The nullable type (which None represents in Python) is represented as null in JSON.

curl -X 'POST' \
'http://0.0.0.0:7012/A_endpoint' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"param1": null,
"param2": 1
}'

None is a pure python name that isn't part of the JSON standard.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84