Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Swagger UI With Akka HTTP

DZone's Guide to

Swagger UI With Akka HTTP

Would you like to see how Swagger UI can be generated with Akka HTTP? Read this article to find out how.

· Integration Zone ·
Free Resource
CRM integration has become the cornerstone to meeting initiatives across organizations. Explore the top 6 value-driven Salesforce CRM integrations ebook.  

In this article, we will see how Swagger UI can be generated with Akka HTTP.

Before digging into it further, you can read more about Swagger UI from here and Akka HTTP from here.

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.

Let’s look at what the setup will look like.

Add Dependency:

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

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

Add Route Property:

You need to add routes property in your application that can be added to other routes: Swagger.scala.
The Swagger.scala contains a routes property that can be concatenated along with existing akka-http routes.
This will expose an endpoint at <baseUrl>/<specPath>/<resourcePath> with the specified apiVersionswaggerVersion and resource listing.

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" -&amp;amp;amp;amp;amp;gt; apiKey)

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

Add Akka HTTP route using the Route DSL:

Akka-Http routing provides a way to concatenate various HTTP routes, which are composed of one or more level of directives that narrows down to handle each specific request.

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

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

Add Swagger Annotations:

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
}

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.

Image title

The following trait will expose a swagger route hosting file from the resources/swagger directory.

getFromResourceDirectory("swagger-ui")

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

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 = Example(system).routes ~ Swagger(system).routes ~
      getFromResourceDirectory("swagger-ui")

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

    println("Application has started on port 8080")

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

}

Start your application, then you can see the swagger UI on the browser:

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

Image title

You can find the source code here.

Hope you find this blog helpful, Happy Blogging!

Sync, automate, and notify lead to customer changes across marketing, CRM, and messaging apps in real-time with the Cloud Elements eventing framework. Learn more.

Topics:
scala ,akka http ,swagger ui ,integration ,akka ,http

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}