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

OpenApi 如何在响应(response)中定义 Cookie?

OpenAPI 响应中Cookie的正确定义方法

OpenAPI 3.0及以上版本已经提供了原生的响应Cookie定义能力,无需使用你提到的两种受限方案,具体实现方式如下:

  • 在接口响应的headers配置段,以Set-Cookie:<目标Cookie名称>作为键名声明每个独立的Cookie,该命名规则为OpenAPI规范原生支持的带参数Header声明格式
  • 每个Cookie配置项可以完整声明description、schema(可指定type、格式、枚举等属性)、required、example等所有需要的元信息,完全覆盖自定义扩展缺少的属性定义能力

以下是完整的配置示例:

paths:
  /user/login:
    post:
      summary: 用户登录接口
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                username:
                  type: string
                password:
                  type: string
      responses:
        '200':
          description: 登录成功
          # 响应Cookie定义段
          headers:
            Set-Cookie:session_id:
              description: 用户会话唯一标识,HttpOnly、Secure属性开启,有效期24小时
              schema:
                type: string
              required: true
              example: session_id=2f9d1837eac; Expires=Fri, 14 Jun 2024 10:30:00 GMT; HttpOnly; Secure; SameSite=Lax
            Set-Cookie:theme_prefer:
              description: 用户主题偏好配置,有效期30天
              schema:
                type: string
                enum: [light, dark, system]
              example: theme_prefer=dark; Expires=Wed, 10 Jul 2024 10:30:00 GMT; SameSite=Lax
          content:
            application/json:
              schema:
                type: object
                properties:
                  code:
                    type: integer
                    example: 200
                  msg:
                    type: string
                    example: 登录成功

如果你仍在使用OpenAPI 2.0(Swagger)版本,无原生响应Cookie支持,可以自定义x-response-cookies扩展字段,结构与请求参数中的cookies定义保持一致即可,主流的OpenAPI文档生成、校验工具基本都支持该类自定义扩展的渲染和识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:36:02