Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Swagger / OpenAPI specification from scala source code (http4s)

So I'm no swagger expert, but all systems using swagger require you to have the swagger specification in JSON or YAML defining all endpoints (and such) of your API.

My question is: Are there know ways to generate these specification files based on the actual source code? I'm asking, because it seems very hard to keep endpoint code & documentation in sync when you start adding properties or returning slightly different results.

So when I have this code (using http4s & RhoService):

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

It would be great if it could produce (in some way:)

/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: []
like image 582
Tom Lous Avatar asked Sep 21 '17 11:09

Tom Lous


2 Answers

Disclaimer: I'm the author of tapir.

rho is one possibility. Another approach is to completely separate the description of the API endpoint from the business logic.

Having a description of an endpoint, which is a regular Scala value, it can be then interpreted as either a server (given the "business logic" function), or documentation.

Two Scala libraries that can provide both http4s and OpenAPI interpreters are tapir and typeapi.

like image 137
adamw Avatar answered Sep 22 '22 22:09

adamw


It is not documented well, but apparently http4s' RhoService adds middleware to generate a swagger.json based on your routes:

Fetch it by calling 'http://localhost:8080/swagger.json'

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

like image 34
Tom Lous Avatar answered Sep 25 '22 22:09

Tom Lous