简体   繁体   中英

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.

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.

我想成功

I know how it can be made within OpenAPIspecs .

Is there a way to generate this description with 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.")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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