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

同一URI不同HTTP方法的Swagger文档报"Map keys must be unique"错误如何解决?

解决Swagger YAML中"Map keys must be unique"错误的方法

这个错误的核心原因是:在OpenAPI(Swagger)规范里,paths对象的键是API的路径,同一个路径只能定义一次。你之前的写法是把/customers/id重复写了四次作为不同的键,这就触发了键重复的校验错误——虽然REST用HTTP方法区分同一资源的操作,但Swagger的结构要求同一路径只声明一次,再在这个路径内部嵌套不同的HTTP方法来对应不同操作。

正确的写法示例

把四个HTTP方法都放在同一个/customers/{id}路径下(注意这里用{id}作为路径参数占位符,这才符合REST URI规范,Swagger能正确识别路径参数):

openapi: 3.0.3
info:
  title: Customer Management API
  version: 1.0.0
paths:
  /customers/{id}:
    # GET 获取指定ID的客户信息
    get:
      summary: 获取单个客户详情
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: 成功返回客户数据
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                  name:
                    type: string
                  email:
                    type: string
    # POST 对指定ID客户执行特定操作(比如触发某个动作)
    post:
      summary: 执行客户相关的特定操作
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                action:
                  type: string
                  example: "send_reminder"
      responses:
        '200':
          description: 操作执行成功
    # PUT 更新指定ID的客户信息
    put:
      summary: 更新客户信息
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                email:
                  type: string
      responses:
        '200':
          description: 客户信息更新成功
    # DELETE 删除指定ID的客户
    delete:
      summary: 删除客户
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '204':
          description: 客户删除成功,无返回内容

额外注意事项

  • 路径中的id必须用{id}作为参数占位符,而不是硬写id,这样Swagger才能正确解析路径参数,生成的文档也会清晰展示参数要求。
  • 每个HTTP方法(get/post/put/delete)作为对应路径的子属性存在,不能重复定义整个路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:01:11