We connect Swagger module in Play Framework

  • Tutorial
Documenting Play Framework using Swagger

The original source for setting up the swagger module


The Play Framework is an MVC web framework for the Java and Scala programming languages ​​from a company formerly called Typesafe, now called Lightbend.


website:


Play framework

article from Habr:


Impressions of working with Play! Framework 2.1 + Java

wiki


Play (framework)

programmer notes


Play Framework - everything you wanted to know about it, but for some reason were afraid to ask

Swagger is a host of tools throughout the API development life cycle, from design and documentation, to testing and deployment.


website:


Swagger

articles from Habr:


Documenting # microservices

3 best tools for describing RESTful API

wiki:


OpenAPI

Swagger (software)

Moving away from the introduction, we can proceed to install the API documentation, which is generated on the fly.


For demonstration, we will use the play framework of the 2nd version: Play 2


Swagger module


To automatically generate API specifications, you need the swagger-play2 module


Swagger ui


At the office. The Swagger.io website provides the Swagger UI , which accepts the Swagger specification in json format and generates a dynamic web interface for learning, experimenting and understanding the API.


Customize Play


Now, let's start integrating the swagger module. For testing, the Play Framework version is used.2.6.3


  1. Add plugin as dependency to the build file build.sbt


    libraryDependencies += "io.swagger" %% "swagger-play2" % "1.6.0"


  2. We connect the Swagger module inconf/application.conf

    play.modules.enabled += "play.modules.swagger.SwaggerModule"
    api.version = "v1" // Specify the api version.

More settings can be added conf/application.confto auto- generate additional fields in the Swagger specification.


Documenting API


  • Swagger annotations available in package io.swagger.annotations
  • Swagger annotations are used to document APIs in Controller classes.

Sample code is described below. Add the following code to the controller class.


@Api(value = "Example Controller", produces = "application/json")

For each method to which we need to add documentation, we must define the following annotation.
A standard response class has already been provided, here it is Response.class.


 @ApiOperation(value = "Get API", notes = "Get list of id & values.", response = Response.class)

For each additional response that the API can return, you can add the following annotation.


@ApiResponses({
    @ApiResponse(code = 403, message = "Invalid Authorization", response = ErrorStatus.class),
    @ApiResponse(code = 500, message = "Internal Server Error", response = ErrorStatus.class) })

Parameters in controller methods can be added as follows:


@ApiOperation(value = "Get User", response = User.class)
public Promise getUser(
    @ApiParam(value = "User Id", name = "userId") String userId){
        User user = getUser(userId);
        return ok(user);
    }

Routes


We can access the auto-generated Swagger specification by adding a route to the configuration file. conf/routes


GET     /docs/swagger.json    controllers.ApiHelpController.getResources

Now, we can reach the Swagger specification from /docs/swagger.json


Add Swagger UI to Play Framework


Since Swagger UI is just a dynamic frontend with HTML / JS, it can be provided primarily through Nginx or httpd .
Alternatively, we can also provide the Swagger UI from the play framework.
It also solves the problem with any CORS error that may occur when the API and Swagger UI are on different domains.
Copy the Swagger UI distribution/public/swagger-ui into your Play project.


In the config file of the routes, add the following directories


GET     /docs/              controllers.Assets.at(path="/public/swagger-ui",file="index.html")
GET     /docs/swagger.json  controllers.ApiHelpController.getResources
GET     /docs/*file         controllers.Assets.at(path="/public/swagger-ui",file)

В случае, если Вы хотите в корне приложения / сделать перенаправление на Swagger спецификацию по умолчанию, тогда добавим этот маршрут в конфиг маршрутов:


GET           /              controllers.Default.redirect(to = "/docs/")

Обновите index.html, чтобы поменять ссылку на Swagger спецификацию.


С


var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
    url = decodeURIComponent(url[1]);
} else {
    url = "http://petstore.swagger.io/v2/swagger.json";
}

На


var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
    url = decodeURIComponent(url[1]);
} else {
    url = "swagger.json";
}

Исследовать API


Однажды, sbt скомпилируется и запустит playframework, перейдите на http://localhost:9000/docs/ чтобы увидеть вживую работающий Swagger UI.


Хорошо


  • Использование Swagger Спец, сделанно очень просто для эффективной коммуникации с API для любого того, кто собирается испоьзовать API.
  • Автоматическая генерация кода клиента из Swagger спецификации сделала потребление и тестирование API очень простым.

Все ещё недостаточно хорошо


Существует несколько проблем в Swagger UI.


  • Иногда Вам нужно перезагрузить страницу, чтобы она вновь заработала.
  • If there is no connection to the API service, the UI cannot explicitly say so.
  • The API link path prefix is ​​not currently handled in the Swagger UI.
  • The Swagger specification generation includes a security configuration that is not correctly implemented (not completely).
  • Perhaps you should use the major versions of the Play Framework since there is a delay in support for the latest versions.

Total


Total Swagger Spec / UI is a great tool for describing and providing access to any API.


Swagger connection video can be seen here .


Also popular now: