Swagger Integration In Akka Http Services.

Reading Time: 3 minutes

This blog will help you that how Swagger UI can be generated with Akka HTTP.

Swagger allows developers to effectively interact and try out each and every route that your application exposes and it automatically generates UI from the Swagger specification. The visual documentation makes it easy for developers and clients to interact with the application.

You can read more about Swagger UI from here and Akka HTTP from here.

Now let’s look at the steps-

STEP-1

Add Dependency:

Firstly, we need to add swagger-akka–http dependency in our application’s build.sbt.

"com.github.swagger-akka-http" % "swagger-akka-http_2.11" % "0.14.0"

STEP-2

Add Swagger UI:

Adding Swagger UI to your site is quite easy, you just need to drop the static site files into the resources directory of your project. You can either download these UI files(HTML/CSS) from swagger website or you can use the existing files from the service in which already the swagger is implemented or you can also modify these files according to your requirement.

You can use the below method to read these files from the resource directory –

getFromResourceDirectory("swagger-ui")

STEP-3

Add Route Property  :

You need to add routes property in your application that can be added to other routes then you have to create a swagger package inside the controller package and inside that package you have to create Swagger.scala class.

This class basically contains the configuration properties of the swagger.
The Swagger.scala contains a routes property which can be concatenated along with existing akka-http routes.


case class Swagger(system: ActorSystem) extends SwaggerHttpService {
  val config = ConfigFactory.load()
  val API_URL = config.getString("swagger.api.url")
  val BASE_PATH = config.getString("swagger.api.base.path")
  val PROTOCOL = config.getString("swagger.api.scheme.protocol")

  override def apiClasses: Set[Class[_]] = Set(classOf[Base])

  override val host = API_URL

  override val basePath = BASE_PATH

  override def schemes: List[Scheme] = List(Scheme.forValue(PROTOCOL))

  override def apiDocsPath: String = "api-docs"

  val apiKey = new ApiKeyAuthDefinition("api_key", QUERY)

  override val securitySchemeDefinitions: Map[String, ApiKeyAuthDefinition] = Map("apiKey" -> apiKey)

  override def info: Info =
    new Info(
      "Swagger Akka http demo application....",
      "1.0",
      "Swagger API",
      "",
      None,
      None,
      Map.empty)
}

STEP-4

DOCUMENT THE ROUTES-

To document your routes , you have to create respective trait inside the swagger package of that class which you want to document. For example if you want to document your ping route which is inside the Base class, you have to create the respective trait like below-

This is the simple ping route of your project-

import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._

case class Base(system: ActorSystem) {
  val routes = path("ping") {
    get {
      complete(HttpResponse(OK, entity = "pong"))
    }
  }
}

This is the documentation of your ping route

 import javax.ws.rs.Path
import akka.http.scaladsl.server.Route
import io.swagger.annotations._

@Path("/ping")
@Api(value = "/ping")
@SwaggerDefinition(tags = Array(new Tag(name = "hello", description = "operations useful for debugging")))
trait Base {
  @ApiOperation(value = "ping", tags = Array("ping"), httpMethod = "GET", notes = "This route will return a output pong")
  @ApiResponses(Array(
    new ApiResponse(code = 200, message = "OK"),
    new ApiResponse(code = 500, message = "There was an internal server error.")
  ))
  def pingSwagger: Option[Route] = None
}

STEP-5

Add swagger routes with other routes and bind the routes to a port to start:

Below is the example how you can concate swagger route with your project routes.

object Boot {
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem("my-actor-system")
implicit val materializer = ActorMaterializer()

implicit val executionContext = system.dispatcher

val routes = Base(system).routes ~ Swagger(system).routes ~
getFromResourceDirectory("swagger-ui")

val bindingFuture = Http().bindAndHandle(routes, "0.0.0.0", 8080)

println("App has started....")

StdIn.readLine() // let it run until user presses return
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
}

STEP-6

Start your application then open the below url in your browser.

http://localhost:8080/swagger-ui/index.html

knoldus