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

Trending

  • System Testing and Best Practices
  • Hibernate Get vs. Load
  • Measuring Service Performance: The Whys and Hows
  • How To Use the Node Docker Official Image
  1. DZone
  2. Coding
  3. Frameworks
  4. Play Framework: Swagger UI

Play Framework: Swagger UI

Alexey Zvolinskiy user avatar by
Alexey Zvolinskiy
·
Dec. 22, 14 · Interview
Like (2)
Save
Tweet
Share
18.66K Views

Join the DZone community and get the full member experience.

Join For Free

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

Play Framework Framework

Published at DZone with permission of Alexey Zvolinskiy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • System Testing and Best Practices
  • Hibernate Get vs. Load
  • Measuring Service Performance: The Whys and Hows
  • How To Use the Node Docker Official Image

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

Let's be friends: