swagger 为什么在FastAPI中为path参数提供描述会导致422错误?

eufgjt7s  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(142)

我正在学习FastAPI(版本0.104.1)。我喜欢它可以为你的API自动生成文档和测试页面。但是,我现在被一件事卡住了。
以下是API端点的定义:

@app.get('/api/v1/book/<id>', 
            responses={
               200: {"model":Book,"description":"Details for the requested book"},
               404: {"model":None,"description":"The book could not be found"}
            })
   def get_book(id: str):
      """Gets the details for one specific book."""
      pass # implementation goes here

字符串
这个API端点完全按照预期工作。但是,我希望能够以在API文档页面中显示参数的方式记录参数的含义。一个Stack Overflow post建议这样做可能会工作:

@app.get('/api/v1/book/<id>', 
            responses={
               200: {"model":Book,"description":"Details for the requested book"},
               404: {"model":None,"description":"The book could not be found"}
            })
   def get_book(id: str = Path(..., description="The book ID to retrieve")):
      """Gets the details for one specific book.""" 
      pass # implementation here


这在API文档中起作用-参数的描述正确显示。
x1c 0d1x的数据
但是,API不再工作。调用API会导致以下结果:

Error: Unprocessable Entity

    Response body
    Download
    {
      "detail": [
        {
          "type": "missing",
          "loc": [
            "path",
            "id"
          ],
          "msg": "Field required",
          "input": null,
          "url": "https://errors.pydantic.dev/2.4/v/missing"
        }
      ]


所以,我在FastAPI文档中找到了this page,并尝试使用它的策略:

@app.get('/api/v1/book/<id>', 
            responses={
               200: {"model":Book,"description":"Details for the requested book"},
               404: {"model":None,"description":"The book could not be found"}
            })
   def get_book(id = Annotated[str, Path(description="The book ID to retrieve")]):
      """Gets the details for one specific book.""" 
      pass # implementation here


现在,API又可以工作了,但是文档页面中的描述已经消失了。
我不明白文档生成器如何从代码中提取元数据,以及如何在文档中描述参数并使参数正常工作。

ygya80vv

ygya80vv1#

我要么看到了不正确的文档,要么它只是从我的意识中溜走了,我从Flask中获得的肌肉记忆开始发挥作用,但是FastAPI使用{}作为基于路径的参数,而不是<>
更改为:

@app.get('/api/v1/book/{id}', 
            responses={
               200: {"model":Book,"description":"Details for the requested book"},
               404: {"model":None,"description":"The book could not be found"}
            })
   def get_book(id: str = Path(description="The book ID to retrieve")):
      """Gets the details for one specific book.""" 
      pass # implementation here

字符串
工作完美.

相关问题