Using Swagger API Docs with Play 2 (Scala): Examples & Reference

Last updated:

This project uses Swagger version 1.3.8

Here are some examples of how to annotate your Play 2.x web app (Scala) using Swagger directives so you can, for instance, plug a Swagger-UI project into your API in order to have a GUI for humans to learn and test your API.

Installing swagger-play2 plugin

Just add this to your project's dependencies (most likely in build.sbt)

libraryDependencies ++= Seq(
  //other dependencies
  "com.wordnik" %% "swagger-play2" % "1.3.8",
  //other dependencies

Annotating domain models

case class Query(
  @(ApiModelProperty @field)(position = 1, value = "id", required = true) id: Long,
  @(ApiModelProperty @field)(position = 2, value = "body", required = true) body: String,
  @(ApiModelProperty @field)(position = 3, value = "favorite", required = true) favorite: Boolean,
  @(ApiModelProperty @field)(position = 4, value = "name", required = false) name: Option[String])

Annotating controller actions

Here you can define the operation name, its parameters, return types and so on.

@ApiOperation(nickname = "searchAll", value = "Perform a full search in the database", notes = "Returns records", httpMethod = "GET")
    new ApiResponse(code = 200, message = "Success"),
    new ApiResponse(code = 400, message = "Bad Request")))
    new ApiImplicitParam(name = "q", value = "Query string", required = true, dataType = "String", paramType = "query")))
  def searchAll() = Action { implicit request =>

HEADS-UP ApiImplicitParam and ApiParamare two ways of defining parameters for a controller action, but ApiImplicitParam is more versatile and doesn't require you to declare parameters to the actual action methods


Dialogue & Discussion