DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. Swagger UI With Akka HTTP

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.

Teena Vashist user avatar by
Teena Vashist
·
Jun. 14, 18 · Tutorial
Like (4)
Save
Tweet
Share
14.92K Views

Join the DZone community and get the full member experience.

Join For Free

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-akka–http 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 apiVersion, swaggerVersion 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!

Akka (toolkit)

Published at DZone with permission of Teena Vashist. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Demystifying Multi-Cloud Integration
  • Isolating Noisy Neighbors in Distributed Systems: The Power of Shuffle-Sharding
  • Data Stream Using Apache Kafka and Camel Application
  • Scaling Your Testing Efforts With Cloud-Based Testing Tools

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: