首页 > 解决方案 > Swagger Editor 为 Rest 端点创建错误的路径

问题描述

所以,我需要使用 Swagger 重新创建我的休息端点。为此,我在 editor.swagger.io 使用 Swagger 编辑器

要调用我的实际休息端点,我需要这条路径:http://localhost:8080/phonenumbersmanagement/api/v1/areacodes/1

可悲的是,Swagger Editor 创建了一个类似的路径,我不能使用它:http://localhost:8080/phonenumbersmanagement/api/v1/areacodes?id=1

这是一个 GET 请求。我得到一个405 - Method not allowed

我在 Swagger 编辑器中的代码如下所示:

/areacodes:
    post:
      tags:
      - "areacode"
      summary: "Add AreaCode"
      description: ""
      operationId: "addAreaCode"
      consumes:
      - "application/json"
      produces:
      - "application/json"
      parameters:
      - in: "body"
        name: "body"
        description: "add areacode"
        required: true
        schema:
          $ref: "#/definitions/AreaCode"
      responses:
        "405":
          description: "Invalid input"
    get:
      tags:
      - "areacode"
      summary: "Get Areacode"
      description: ""
      operationId: "getAreaCodeById"
      produces:
      - "application/json"
      parameters:
      - name: "id"
        in: "query"
        description: "Status values that need to be considered for filter"
        required: true
        type: "integer"
        format: "int32"
      responses:
        "200":
          description: "successful operation"
          schema:
            type: "array"
            items:
              $ref: "#/definitions/AreaCode"
        "400":
          description: "Invalid status value"

有没有人知道如何解决这个问题?

标签: javarestswaggerswagger-editor

解决方案


其中.../areacodes/1,1是一个路径参数,所以该参数必须定义为in: path而不是in: query。此外,必须使用路径模板定义具有路径参数的端点 - .../areacodes/{id},其中{id}表示名为 的路径参数id

考虑到这一点,您的 GET 操作需要定义如下:

paths:
  /areacodes/{id}:  # <------
    get:
      ...
      parameters:
      - name: "id"
        in: path    # <------
        description: "Status values that need to be considered for filter"
        required: true
        type: "integer"
        format: "int32"

推荐阅读