You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在FastAPI的Swagger UI中移除二进制文件的示例值区域?

问题

我有一个返回文件的API路由,该响应没有请求体,但Swagger UI里默认显示了标注为“string”的“Example value”区域,想完全移除这个区域。请问在FastAPI里有没有办法做到?或者说,即使响应是无请求体的文件,这个区域有必须保留的理由吗?

我已经尝试过两种方法,但都没达到完全移除的效果:

  • 将example设为None,结果和没声明时一样,还是显示默认的“string”示例
  • 将example设为空字符串,只能清空区域内容,但区域本身还在

我的代码示例:

from fastapi import APIRouter
from starlette.responses import FileResponse

router = APIRouter()


@router.get("/",
            response_class=FileResponse,
            responses={
                200: {
                    "content": {"application/octet-stream": {}}
                }
            },
            )
async def get_file():
    ...
    return FileResponse(file_path, media_type='application/octet-stream', filename=filename)

尝试设置空字符串的代码:

responses={200: {
    "content": {"application/octet-stream": {
        "example": ""
    }}
}
解决方案

要完全移除Swagger UI里的这个“Example value”区域,你可以在响应的content定义中添加"schema": {"type": "string", "format": "binary"},明确告诉OpenAPI这是二进制文件类型,这样Swagger UI就不会显示默认的字符串示例区域了。

修改后的代码如下:

from fastapi import APIRouter
from starlette.responses import FileResponse

router = APIRouter()


@router.get("/",
            response_class=FileResponse,
            responses={
                200: {
                    "content": {"application/octet-stream": {
                        "schema": {"type": "string", "format": "binary"}
                    }}
                }
            },
            )
async def get_file():
    ...
    return FileResponse(file_path, media_type='application/octet-stream', filename=filename)

是否需要保留该区域的说明

对于返回二进制文件的接口,这个默认的字符串示例区域完全没有意义——实际响应是二进制流而非字符串,移除它能让Swagger UI的展示更贴合接口实际行为,避免误导使用者。

内容的提问来源于stack exchange,提问作者Eric Ramírez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 15:42:15