`
sillycat
  • 浏览: 2492105 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

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
分享到:
评论

相关推荐

    playFramework_Swagger

    playFramework_Swagger 使用 Swagger 在 play 框架中使用 Web 服务进行项目

    play-swagger_ui:Swagger UI的Playframework 1.3模块

    play-swagger-ui Playframework 1.3模块可将swagger ui集成到您的应用程序中。将其添加到您的项目将依赖项放入您的dependencies.yml文件中: require: - michiruf -> swagger_ui 0.0.1定义存储库以从github获取模块...

    play1.2.4集成Swagger

    play集成Swagger,希望能帮助到大家,目前好像只能支持1.2.4,其他版本的play测试了下貌似不行

    django-rest-framework 自定义swagger过程详解

    主要介绍了django-rest-framework 自定义swagger过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    Swagger,NET4.5版本的

    就是一个C#Swagger搭建好了的demo,方便拓展以及更新 4.5net framework

    django-rest-swagger:Django REST Framework的Swagger文档生成器:已弃用

    Swagger UI和Django REST Framework的API文档生成器 完整文档: : 安装 pip install django-rest-swagger 将rest_framework_swagger添加到您的INSTALLED_APPS设置中: INSTALLED_APPS = ( ... ' rest_framework...

    play-swagger:为播放框架提供Swagger支持

    Play-Swagger插件现已重命名为 。 该版本不再处于积极开发中。 Api-First-Hand经过精心维护,除了Play 2.4支持外,还提供Play-Swagger的所有功能。 如果您想查看Play-Swagger或创建问题,请导航至。 -- -- 玩招摇 ...

    swagger2Demo,swagger

    swagger2Demo,swagger,这个是写的一个demo,用于调试接口swagger确实好用,jdk1.8的,欢迎下载,

    swagger2.zip

    springboot 2.2.7集成swagger2.9.2,并生成markdown格式API文档. <!-- swagger2 依赖开始--> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <groupId>io.springfox ...

    swagger,基于swagger的前端UI实现

    现在市面上的swagger UI不足之处 1、原生UI显示的有些不够漂亮和清晰,特别是request 的model部分 2、每个服务都需要引入一套资源文件,不能作为一个中间件为其他API使用 3、默认通用配置繁琐,每个项目都需要复制...

    swagger官方文档离线版

    swagger官方文档离线版

    swagger-annotations-1.6.2-API文档-中文版.zip

    赠送jar包:swagger-annotations-1.6.2.jar; 赠送原API文档:swagger-annotations-1.6.2-javadoc.jar; 赠送源代码:swagger-annotations-1.6.2-sources.jar; 赠送Maven依赖信息文件:swagger-annotations-1.6.2....

    swagger-annotations-2.1.2-API文档-中文版.zip

    赠送jar包:swagger-annotations-2.1.2.jar; 赠送原API文档:swagger-annotations-2.1.2-javadoc.jar; 赠送源代码:swagger-annotations-2.1.2-sources.jar; 赠送Maven依赖信息文件:swagger-annotations-2.1.2....

    swagger-annotations-1.5.20-API文档-中文版.zip

    赠送jar包:swagger-annotations-1.5.20.jar; 赠送原API文档:swagger-annotations-1.5.20-javadoc.jar; 赠送源代码:swagger-annotations-1.5.20-sources.jar; 赠送Maven依赖信息文件:swagger-annotations-...

    swagger_java_swagger_

    swagger与springboot的集成

    swagger官方文档

    swagger官方文档swagger官方文档swagger官方文档swagger官方文档swagger官方文档

    swagger-annotations-1.5.24-API文档-中文版.zip

    赠送jar包:swagger-annotations-1.5.24.jar; 赠送原API文档:swagger-annotations-1.5.24-javadoc.jar; 赠送源代码:swagger-annotations-1.5.24-sources.jar; 赠送Maven依赖信息文件:swagger-annotations-...

    swagger-models-2.1.2-API文档-中文版.zip

    赠送jar包:swagger-models-2.1.2.jar; 赠送原API文档:swagger-models-2.1.2-javadoc.jar; 赠送源代码:swagger-models-2.1.2-sources.jar; 赠送Maven依赖信息文件:swagger-models-2.1.2.pom; 包含翻译后的API...

    swagger静态部分文件打包

    swagger静态部分文件打包,用于swagger的页面接口展示

Global site tag (gtag.js) - Google Analytics