英文:
How to allow None type as a parameter in a fastAPI endpoint?
问题
我定义了我假定的参数的类。我希望这些参数(例如 param1)可以有一个值为 None:
```python
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):
# 对 a 进行操作
return a
当我调用该端点时:
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
}'
我得到了错误 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
}
}
]
}
我理解默认值可以是 None,当我省略该参数时(这是有效的)。但我如何明确地允许 param1 的值为 None?
谢谢!
<details>
<summary>英文:</summary>
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!
</details>
# 答案1
**得分**: 1
你实际上正在发送字面值 "None"。这不是一个有效的整数或空值。
可为空类型(在Python中由None表示)在JSON中表示为 `null`。
```sh
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
是纯粹的Python名称,不是JSON标准的一部分。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论