swagger-ui
Let’s see how to integrate the most popular API documentation in Play Framework. I’m talking about Swagger. It’s very powerful tool for REST API description and Play Framework supports it with help of separate module. In this post I’m going to show step by step instruction how to setup Play Framework with Swagger UI.

Pre-requirements for this tutorial are basic knowledge of how Play Framework works (build.sbt, routes, Controllers, application.conf) and ability to read very attentive. When you met the pre-requirements and you have some Play-project you can go ahead and finish the tutorial.

Step #1

Add Swagger dependency in build.sbt

...
libraryDependencies ++= Seq(
  jdbc,
  anorm,
  cache,
  ws,
  filters,
  "com.wordnik" %% "swagger-play2" % "1.3.11"
)
...

Now we can use generation of API documentation in a project.

Step #2

In routes file we need to put URI in order to list all REST endpoints in a project:

GET         /api-docs.json                      controllers.ApiHelpController.getResources

Step #3

It’s time to decorate REST endpoints with appropriate annotations:

@Api(value = "/lawyers", description = "Operations with account")
object LawyerController extends Controller with UserAccountForms {

  @ApiOperation(
    nickname = "createAccount",
    value = "Create user account",
    notes = "User Sign Up endpoint",
    httpMethod = "POST",
    response = classOf[models.swagger.BearerToken])
  @ApiResponses(Array(
    new ApiResponse(code = 201, message = "Account successfully created"),
    new ApiResponse(code = 400, message = "Email already exist"),
    new ApiResponse(code = 500, message = "DB connection error")))
  @ApiImplicitParams(Array(
    new ApiImplicitParam(value = "Account object that need to be created", required = true, dataType = "models.swagger.UserAccountInfo", paramType = "body")))
  def createAccount = Action.async {
    implicit request => {
      //Some code here. It's not important
    }
  }

}

Step #4

Modify routes file again but now for a particular endpoint:

GET         /api-docs.json/lawyers              controllers.ApiHelpController.getResource(path = "/lawyers")
POST        /lawyers                            controllers.LawyerController.createAccount

This is minimal set of actions which can provide you with information about your REST API. But if you want more – UI representation of JSON, you need to perform several extra steps. Let’s continue with Swagger UI.

Step #5

Download Swagger UI and put all these files in [project_root_dir]/public/swagger

Step #6

Copy index.html in [project_root_dir]/app/views and rename it in swagger.scala.html

Step #7

Add default application URL in application.config

swagger.api.basepath="http://localhost:9000"

Step #8

Modify swagger.scala.html

8.1
Add line on the top of the file:

@import play.api.Play.current

8.2
Update all locations to static resources. After the update all of them will be like this:

<script src='/assets/swagger/lib/backbone-min.js' type='text/javascript'></script>

8.3
Update JavaScript code snippet by injecting there some Play Template code:

   $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = url[1];
      } else {
        url = "@{s"${current.configuration.getString("swagger.api.basepath")
            .getOrElse("http://localhost:9000")}/api-docs.json"}"
      }
...

Step #9

Add action which will be responsible for Swagger UI display:

object Application extends Controller {

  def swagger = Action {
    request =>
      Ok(views.html.swagger())
  }

}

Step #10

And finally add line of code in routes

GET         /swagger                            controllers.Application.swagger

That’s it. Now you can Use Swagger API documentation in your own Swagger UI. I tried to do this tutorial as concise as I can in order to reduce the number of points where you can be confused. Thanks

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog

Close