Generating OpenAPI documentation

To use, add the following dependencies:

"com.softwaremill.tapir" %% "tapir-openapi-docs" % "0.8.6"
"com.softwaremill.tapir" %% "tapir-openapi-circe-yaml" % "0.8.6"

Tapir contains a case class-based model of the openapi data structures in the openapi/openapi-model subproject (the model is independent from all other tapir modules and can be used stand-alone).

An endpoint can be converted to an instance of the model by importing the package and calling the provided extension method:

import tapir.openapi.OpenAPI

val docs: OpenAPI = booksListing.toOpenAPI("My Bookshop", "1.0")

Such a model can then be refined, by adding details which are not auto-generated. Working with a deeply nested case class structure such as the OpenAPI one can be made easier by using a lens library, e.g. Quicklens.

Multiple endpoints can be converted to an OpenAPI instance by calling the extension method on a list of endpoints:

List(addBook, booksListing, booksListingByGenre).toOpenAPI("My Bookshop", "1.0")

The openapi case classes can then be serialised, either to JSON or YAML using Circe:

import tapir.openapi.circe.yaml._


Exposing OpenAPI documentation

Exposing the OpenAPI documentation can be very application-specific. For example, to expose the docs using the Swagger UI and akka-http:

  • add libraryDependencies += "org.webjars" % "swagger-ui" % "3.22.2" to build.sbt (or newer)
  • generate the yaml content to serve as a String using tapir:
import tapir.openapi.circe.yaml._

val docsAsYaml: String = myEndpoints.toOpenAPI("My App", "1.0").toYaml
  • add the following routes to your server:
val SwaggerYml = "swagger.yml"

private val redirectToIndex: Route =
  redirect(s"/swagger/index.html?url=/swagger/$SwaggerYml", StatusCodes.PermanentRedirect) 

// needed only if you use oauth2 authorization
private def redirectToOath2(query: String): Route =
    redirect(s"/swagger/oauth2-redirect.html$query", StatusCodes.PermanentRedirect)

private val swaggerVersion = {
  val p = new Properties()
  val pomProperties = getClass.getResourceAsStream("/META-INF/maven/org.webjars/swagger-ui/")
  try p.load(pomProperties)
  finally pomProperties.close()

val routes: Route =   
  pathPrefix("swagger") {
    pathEndOrSingleSlash {
    } ~ path(SwaggerYml) {
    } ~ getFromResourceDirectory(s"META-INF/resources/webjars/swagger-ui/$swaggerVersion/")
  } ~
  // needed only if you use oauth2 authorization
  path("oauth2-redirect.html") { request => 
    redirectToOath2( => '?' + s).getOrElse(""))(request)