如何使用FastAPI将图像添加到Swagger UI自动文档?

4sup72z8  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(222)

我想在FastAPI自动文档中添加一个图像(由Swagger UI提供),但是我不知道如何操作。代码如下:

@api.get(path='/carbon-credit/',
    responses={
        200: {'description': 'Ok',
            "content": {
            "image/jpeg": {
                "example": 'https://picsum.photos/seed/picsum/200/300'
                    }
                }},
        404: {"description": "not found"},
        422: {'description': 'not found 2'},
    },
    name='API for Carbon Credit',
    description="get carbon credit",
    tags=['Images'],
    response_class=Response)

从代码中可以看出,我尝试使用URL来实现这一点,而我在ReDoc和Swagger UI中得到的只是文本形式的URL,而不是实际的图像。另外,我希望使用存储在本地驱动器中的图像。
来自Swagger UI和ReDoc的屏幕截图:

我怎么才能做到呢?
先谢谢你。

0yg35tkg

0yg35tkg1#

Swagger UI和ReDoc都使用description参数的标准HTML标签。因此,您可以使用description添加图像。

@app.get(path='/',
    responses={
        200: {'description': '<img src="https://placebear.com/cache/395-205.jpg" alt="bear">',
    ...

OpenAPI还支持markdown元素(参见here),并将在Swagger UI/ReDoc中为您呈现图像。因此,您可以选择用途:

@app.get(path='/',
    responses={
        200: {'description': '![bear](https://placebear.com/cache/395-205.jpg)',
    ...

要使用存储在本地驱动器中的映像,您可以将一个StaticFiles示例挂载到一个特定的路径(比如/static),以便从驱动器中的一个目录提供静态文件/映像。

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get(path='/',
    responses={
        200: {'description': '![bear](static/bear.jpg)',
    ...

将图像添加到示例字段

要将图像添加到examples域,您可以再次使用description参数,如下所示。请确保通过examples参数而不是example来执行此操作。

@app.get(path='/',
    responses={
        200: {"description": "OK",
               "content": {
                  "image/jpeg": {
                     "schema": {
                        "type": "string",
                        "format": "binary"
                     },
                     "examples": {
                        "sampleImage": {
                           "summary": "A sample image",
                           "description": "![bear](https://placebear.com/cache/395-205.jpg)",
                           "value": ""
                        }
                     }
                  }
               }
            },
        404: {"description": "not found"},
        422: {'description': 'not found 2'},
    },
    ...

相关问题