Playframework and Swagger

Playframework and Swagger

1. Prepare the RESTful Project(Upgrade)
Download the latest activator version and place in the working directory.
https://www.playframework.com/documentation/2.4.3/ScalaTestingWithScalaTest

Some Changes to Upgrade the Version
activator
declare -r app_version=“1.3.6"

activator.bat
set APP_VERSION=1.3.6

build.sbt
import play.sb.PlayScala
…snip...
scalaVersion := "2.10.4"

ivyScala := ivyScala.value map { _.copy(overrideScalaVersion = true) }

libraryDependencies ++= Seq(
  "org.scalatest" %% "scalatest" % "2.2.5" % "test",
  "org.scalatestplus" %% "play" % "1.4.0-M4" % "test"
)
…snip...

project/build.properties
sbt.version=0.13.8

project/plugins.sbt
logLevel := Level.Warn

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.0")
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.6.0")

resolvers += "Typesafe repository" at "https://repo.typesafe.com/typesafe/releases/"
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.4.3")

test/controllers/BookControllerSpec.scala
package controllers

import play.api.libs.json.JsValue

import scala.concurrent.Future

import org.scalatestplus.play._

import play.api.mvc._
import play.api.test._
import play.api.test.Helpers._

class BookControllerSpec extends PlaySpec with Results{

  class TestController() extends Controller with BookController

  "Book API#listBooks" should {
    "size should be 2" in {
      val controller = new TestController
      val result: Future[Result] = controller.listBooks.apply(FakeRequest())
      val bodyText: JsValue = contentAsJson(result)
      bodyText must not be null
    }
  }

}

2. Prepare Swagger
Play with swagger-ui Project
> git clone https://github.com/swagger-api/swagger-ui.git

> npm install

> gulp

After that, we should see the distribution under the list folder.

Check if I have apache http server on my machine.
> apachectl -V
Server version: Apache/2.4.16 (Unix)
Server built:   Jul 22 2015 21:03:09
Server's Module Magic Number: 20120211:47
Server loaded:  APR 1.4.8, APR-UTIL 1.5.2
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture:   64-bit
Server MPM:     prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
-D APR_HAS_SENDFILE
-D APR_HAS_MMAP
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
-D APR_USE_FLOCK_SERIALIZE
-D APR_USE_PTHREAD_SERIALIZE
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
-D APR_HAS_OTHER_CHILD
-D AP_HAVE_RELIABLE_PIPED_LOGS
-D DYNAMIC_MODULE_LIMIT=256
-D HTTPD_ROOT="/usr"
-D SUEXEC_BIN="/usr/bin/suexec"
-D DEFAULT_PIDLOG="/private/var/run/httpd.pid"
-D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
-D DEFAULT_ERRORLOG="logs/error_log"
-D AP_TYPES_CONFIG_FILE="/private/etc/apache2/mime.types"
-D SERVER_CONFIG_FILE="/private/etc/apache2/httpd.conf"

Start the Server
> sudo apachectl start

Check the configuration
>cat  /etc/apache2/httpd.conf

DocumentRoot "/Library/WebServer/Documents"

Copy the swagger-ui directory there
> sudo cp -r /Users/carl/book/swagger/swagger-ui/dist/* /Library/WebServer/Documents/

Visit swagger-ui
http://localhost/

Put http://localhost:8000/api-docs as parameter in the input box, we will have the api doc.

Or

http://localhost/index.html?url=http://localhost:8000/api-docs

Or

http://localhost:8000/assets/lib/swagger-ui/index.html?/url=http://localhost:8000/api-docs

3. Add notation in the Project
Some Sample codes are in sillycat-scalarest project version-1.3.6-swagger branch.

build.sbt
import play.sbt.PlayScala

name := """sillycat-scalarest"""

version := "1.0"

lazy val root = project.in(file(".")).enablePlugins(PlayScala)

scalaVersion := "2.10.4"

ivyScala := ivyScala.value map { _.copy(overrideScalaVersion = true) }

libraryDependencies ++= Seq(
  "pl.matisoft" %% "swagger-play24" % "1.4",
  //for internal swagger-ui
  //"org.reflections" % "reflections" % "0.9.9" notTransitive(),
  //"org.webjars" % "swagger-ui" % "2.1.8-M1",
  "org.scalatest" %% "scalatest" % "2.2.5" % "test",
  "org.scalatestplus" %% "play" % "1.4.0-M4" % "test"
)

fork in run := false

conf/routes
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file           controllers.Assets.versioned(path="/public", file)

# API Routes
GET     /ping                   controllers.PingPongController.ping()
GET     /api/v1/book            controllers.BookController.listBooks
POST    /api/v1/book            controllers.BookController.saveBook
GET     /api/v1/book/:id        controllers.BookController.getBook(id:String)
PUT     /api/v1/book/:id        controllers.BookController.updateBook(id:String)
DELETE  /api/v1/book/:id        controllers.BookController.deleteBook(id:String)

# Swagger API
GET     /api-docs               @pl.matisoft.swagger.ApiHelpController.getResources
GET     /api-docs/api/v1   @pl.matisoft.swagger.ApiHelpController.getResource(path = "/api/v1")

app/controllers/PingPongController.scala
package controllers

import play.api.mvc.{Action, Controller}
import com.wordnik.swagger.annotations.{Api,ApiModel,ApiModelProperty,ApiOperation,ApiParam,ApiResponse,ApiResponses}

@Api(value = "/api/v1", description = "Operations with Classifier")
object PingPongController extends Controller{

  @ApiOperation(value = "Pings",
    notes = "Returns pong",
    response = classOf[String],
    httpMethod = "GET",
    produces = "text",
    position = 1)
  @ApiResponses(Array(
    new ApiResponse(code = 200, message = "Successful ping", response = classOf[String])
  )
  )
  def ping = Action {
    Ok("pong")
  }

}

Error Message
XMLHttpRequest cannot load http://localhost:8000/string. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 404.

Solution:
http://enable-cors.org/server.html

https://www.playframework.com/documentation/2.4.3/CorsFilter

Filter Class app/Filters.scala
import javax.inject.Inject

import play.api.http.HttpFilters
import play.filters.cors.CORSFilter

class Filters @Inject() (corsFilter: CORSFilter) extends HttpFilters {
  def filters = Seq(corsFilter)
}

Configuration in conf/application.conf
play.filters.cors {
  #pathPrefixes = ["/some/path", ...]
  allowedOrigins = ["http://localhost", "http://sillycat.ddns.net"]
  allowedHttpMethods = ["GET", "POST", "PUT"]
  #allowedHttpHeaders = ["Accept"]
  #preflightMaxAge = 3 days
}

4. Playframework Deployment
Build the binary
> sbt dist

Run the binary
> bin/sillycat-scalarest -Dconfig.file=conf/application.conf -Dhttp.port=8000 -Dhttp.address=0.0.0.0

Need to use the same ui version
> git checkout tags/v2.1.8-M1

References:
Playframework
http://sillycat.iteye.com/blog/2241901

http://sillycat.iteye.com/blog/2242284

Swagger
https://github.com/matiwinnetou/swagger-play24

http://swagger.io/getting-started/
https://github.com/swagger-api/swagger-ui

猜你喜欢

转载自sillycat.iteye.com/blog/2247372