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

openapi-generator-cli中如何正确描述application/pdf类型的响应

解决方案

方法1:标记二进制响应避免JSON解析

绝大多数openapi-generator的客户端生成器(包括javascript、typescript-fetch等常用模板)都会识别x-is-binary自定义扩展字段,明确告知生成器该接口返回二进制内容,不需要执行JSON序列化。
修改后的OpenAPI定义如下:

/SupportingDocument/document/{documentId}:
  get:
    tags: [Company, Document]
    operationId: getDocument
    summary: Get document by id
    security:
      - JWTAuth: []
    parameters:
      - in: path
        name: documentId
        required: true
        schema: { type: string }
    responses:
      200:
        description: A PDF file
        content:
          application/pdf:
            schema:
              type: string
              format: binary
            x-is-binary: true # 新增该行标记当前响应为二进制内容
      404: { $ref: '#/components/responses/NotFound' } # 原定义此处错误引用了500响应,可按需修正
      500: { $ref: '#/components/responses/InternalServerError' }

配置后重新生成代码,生成器会自动将响应处理逻辑改为返回blob或者arrayBuffer,不会再调用response.json()。

方法2:强制返回原始Response对象

如果你需要完全自定义响应处理逻辑,直接拿到原生fetch的Response对象,可以在操作级别添加x-raw-response: true扩展:

/SupportingDocument/document/{documentId}:
  get:
    tags: [Company, Document]
    operationId: getDocument
    x-raw-response: true # 新增该行强制返回原始响应
    summary: Get document by id
    security:
      - JWTAuth: []
    parameters:
      - in: path
        name: documentId
        required: true
        schema: { type: string }
    responses:
      200:
        description: A PDF file
        content:
          application/pdf:
            schema:
              type: string
              format: binary
      404: { $ref: '#/components/responses/NotFound' }
      500: { $ref: '#/components/responses/InternalServerError' }

该配置下生成的代码会直接返回Response对象,和你预期的效果完全一致。

注意事项

  • 建议将openapi-generator-cli版本升级到6.0及以上,旧版本对format: binary的识别存在已知兼容问题
  • 如果使用typescript-fetch模板生成代码,可以在生成命令中添加额外参数--additional-properties=supportsES6=true,useFetchApi=true保证二进制处理逻辑正常生效

内容的提问来源于stack exchange,提问作者user11499587

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:24:02