英文:
Is it possible to have a required query parameter with a default value on FastAPI?
问题
我正在尝试使FastAPI中的查询参数成为必需的,但给它一个默认值,但我在他们的用户指南中找不到任何信息。
在OpenAPI中,可以像这样做:
```python
parameters:
- name: "some_name"
in: "query"
description: "a description"
required: true
type: "string"
default: "First"
enum:
- "First"
- "Second"
- "Third"
如您所见,required 被分配为 true,我有一个默认值 ("first")。
使用 FastAPI,我有这个:
class ModelNames(str, Enum):
first = "first"
second = "second"
third = "third"
@app.post("/path")
async def this_function(
modelInstance = Query(
default=Required, # 我希望以某种方式将 "first" 和 Required 分配给 default
description="a description"
)
):
return None
这是您的代码部分的翻译。
<details>
<summary>英文:</summary>
I am trying to make a query parameter required but give it a default value on FastAPI, but i am not finding anything on their user guide.
On openapi, it would be something like this:
parameters:
- name: "some_name"
in: "query"
description: "a description"
required: true
type: "string"
default: "First"
enum:
- "First"
- "Second"
- "Third"
as you can see required is assigned to true and i have a default value ("first")
With fastapi i have this:
class ModelNames(str, Enum):
first = "first"
second = "second"
third = "third"
@app.post("/path")
async def this_function(
modelInstance = Query(
default=Required, # i would like to somehow assign "first" and Required to default
description="a description"
)
):
return None
I've tried directly assigning "first" but it makes it optional.
</details>
# 答案1
**得分**: 4
# Required parameter can't get default value by design
无法。
如果你想为自定义示例值的副作用定义默认值,请使用 example 参数。
https://fastapi.tiangolo.com/tutorial/schema-extra-example/#example-and-examples-in-openapi
<details>
<summary>英文:</summary>
# Required parameter can't get default value by design
You can't.
If you want to define a default value for the side effect of a custom example value, use the example parameter instead.
https://fastapi.tiangolo.com/tutorial/schema-extra-example/#example-and-examples-in-openapi
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论