简体   繁体   English

如何在 FastAPI 中生成响应描述

[英]How to generate response decriptions in FastAPI

I want to generate a description of all available responses (along with code 200 example), which are represented in the code, like here.我想生成所有可用响应的描述(以及代码 200 示例),这些响应在代码中表示,如下所示。

from typing import Any

import uvicorn
from fastapi import FastAPI, HTTPException

router = FastAPI()
from pydantic import BaseModel

class FileItemBase(BaseModel):
    current_project: str = "Test project"

class FileItemInDBBase(FileItemBase):
    id: int
    folder_path: str

    class Config:
        orm_mode = True

class FileResponse(FileItemInDBBase):
    pass

@router.get("/", response_model=FileResponse)
def example_code() -> Any:
    """
    # beautiful description
    to demonstrate functionality
    """
    demo=True
    if demo:
        raise HTTPException(418, "That is a teapot.")
if __name__ =="__main__":
    uvicorn.run(router)

What I got with this is such a description.我得到的就是这样的描述。

描述示例

When I try this out - I got an error response (as expected).当我尝试这个时 - 我得到了一个错误响应(正如预期的那样)。

回复

What I want - is the description of an error included in the example responses, like here.我想要的 - 是示例响应中包含的错误的描述,例如此处。 A Frontend-developer can look at this description and process such cases in the right way without testing the API.前端开发人员可以查看此描述并以正确的方式处理此类情况,而无需测试 API。

我想成功

I know how it can be made within OpenAPIspecs .我知道如何在 OpenAPI规范中制作它。

Is there a way to generate this description with FastAPI?有没有办法用 FastAPI 生成这个描述?

You can add a responses parameter to your path operation.您可以向路径操作添加响应参数。

Then you can pass your model there.然后你可以在那里传递你的模型。 It will create a schema for that model.它将为该模型创建一个模式。

class FileItemBase(BaseModel):
    current_project: str = "Test project"


@app.get("/", response_model=FileItemBase, responses={418: {"model": FileItemBase}})
def example_code():
    """
    # beautiful description
    to demonstrate functionality
    """
    demo = True
    if demo:
        raise HTTPException(418, "That is a teapot.")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM