从 Scala 源代码 (http4s) 生成 Swagger/OpenAPI 规范

Tom*_*ous 6 swagger swagger-2.0 openapi http4s

所以我不是 swagger 专家,但所有使用 swagger 的系统都要求您拥有 JSON 或 YAML 中的 swagger 规范来定义 API 的所有端点(等)。

我的问题是:有没有办法根据实际的源代码生成这些规范文件?我在问,因为当您开始添加属性或返回略有不同的结果时,似乎很难保持端点代码和文档同步。

所以当我有这个代码时(使用 http4s 和 RhoService):

object HelloWorld {
  val service = new RhoService {
    GET / "hello" / 'name |>> { name: String =>
      Ok(Json.obj("message" -> Json.fromString(s"Hello, ${name}")))
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果它可以产生(以某种方式:)

/hello/{name}:
    get:
      tags:
      - "HelloWorld"
      summary: ""
      description: ""
      operationId: "getHellobyName"
      produces:         
      - "application/json"
      parameters:
      - name: "name"
        in: "path"
        description: ""
        required: true
        type: "string"
      responses:
        200:
          description: "successful operation"
          schema:
            $ref: "#/definitions/Hello"           
      security:
      - api_key: []
Run Code Online (Sandbox Code Playgroud)

ada*_*amw 7

免责声明:我是tapir的作者。

rho是一种可能性。另一种方法是将 API 端点的描述与业务逻辑完全分离。

有了端点的描述(这是一个常规的 Scala 值),它就可以被解释为服务器(给定“业务逻辑”功能)或文档。

可以提供 http4s 和 OpenAPI 解释器的两个 Scala 库是tapirtypeapi


Tom*_*ous 5

它没有很好的记录,但显然 http4sRhoService添加了中间件来swagger.json根据您的路由生成:

通过调用“ http://localhost:8080/swagger.json ”来获取它

Git来源:https://github.com/http4s/rho/blob/0c5aed48aeeea18b1d66d88b58cd3deea733f070/swagger/src/main/scala/org/http4s/rho/swagger/SwaggerSupport.scala#L30

  • 如此重要的组件,奇怪的是没有关于它的文档。 (2认同)
  • Http4s/Rho 的 Swagger 输出示例代码可以在 https://github.com/http4s/rho/tree/master/examples/src/main/scala/com/http4s/rho 找到 (2认同)