FastAPI是否可以使用默认值的方式设置必需的查询参数?

huangapple go评论67阅读模式
英文:

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 (&quot;first&quot;)
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&#39;ve tried directly assigning &quot;first&quot; 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&#39;t get default value by design

You can&#39;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>



huangapple
  • 本文由 发表于 2023年2月14日 21:43:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定