【问题标题】:How to add image to Swagger UI autodocs using FastAPI?如何使用 FastAPI 将图像添加到 Swagger UI autodocs?
【发布时间】:2022-08-21 01:29:05
【问题描述】:

我想将图像添加到 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 的屏幕截图:

我怎样才能做到这一点?

提前致谢。

    标签: python swagger swagger-ui fastapi openapi


    【解决方案1】:

    Swagger UI and 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'},
        },
        ...
    

    【讨论】:

    • 如果我想在示例字段中添加图像怎么办?
    • 详尽而全面的答案。太感谢了!
    猜你喜欢
    • 2020-09-13
    • 2022-08-13
    • 2022-11-08
    • 1970-01-01
    • 2022-08-15
    • 2017-06-12
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    相关资源
    最近更新 更多