RESTful風格的Web服務框架:Swagger


Swagger與SpringMVC項目整合

為了方便的管理項目中API接口,在網上找了好多關於API接口管理的資料,感覺目前最流行的莫過於Swagger了,功能強大,UI界面漂亮,並且支持在線測試等等,所以本人仔細研究了下Swagger的使用,下面就如何將Swagger與個人的SpringMVC項目進行整合做詳細說明:

最終API管理界面: 
首頁

詳細步驟:

Step1:項目中引入相關jar包:

    <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <version.spring>3.2.9.RELEASE</version.spring> <version.jackson>2.4.4</version.jackson> </properties> <dependencies> .... <dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> <version>0.9.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${version.jackson}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${version.jackson}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${version.jackson}</version> </dependency> </dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

Step2:添加自定義config文件

package com.spg.apidoc.common.configer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.mangofactory.swagger.configuration.SpringSwaggerConfig; import com.mangofactory.swagger.models.dto.ApiInfo; import com.mangofactory.swagger.plugin.EnableSwagger; import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; /** * 項目名稱:apidoc * * @description: * @author Wind-spg * @create_time:2015年2月10日 上午10:27:51 * @version V1.0.0 * */ @Configuration @EnableSwagger // Loads the spring beans required by the framework public class MySwaggerConfig { private SpringSwaggerConfig springSwaggerConfig; /** * Required to autowire SpringSwaggerConfig */ @Autowired public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) { this.springSwaggerConfig = springSwaggerConfig; } /** * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc * framework - allowing for multiple swagger groups i.e. same code base * multiple swagger resource listings. */ @Bean public SwaggerSpringMvcPlugin customImplementation() { return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns( ".*?"); } private ApiInfo apiInfo() { ApiInfo apiInfo = new ApiInfo( "My Apps API Title", "My Apps API Description", "My Apps API terms of service", "My Apps API Contact Email", "My Apps API Licence Type", "My Apps API License URL"); return apiInfo; } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

Step3:將此配置加入到Spring容器中,如下:

<bean class="com.spg.apidoc.common.configer.MySwaggerConfig" />
  • 1

Step4:在代碼中添加相關APIAnnotation,如下:

    @ResponseBody @RequestMapping( value = "addUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8") @ApiOperation(value = "添加用戶", httpMethod = "POST", response = BaseResultVo.class, notes = "add user") public String addUser(@ApiParam(required = true, name = "postData", value = "用戶信息json數據") @RequestParam( value = "postData") String postData, HttpServletRequest request) { LOGGER.debug(String.format("at function, %s", postData)); if (null == postData || postData.isEmpty()) { return super.buildFailedResultInfo(-1, "post data is empty!"); } UserInfo user = JSON.parseObject(postData, UserInfo.class); int result = userService.addUser(user); return buildSuccessResultInfo(result); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

說明: 
其中@ApiOperation和@ApiParam為添加的API相關注解,個參數說明如下: 
@ApiOperation(value = “接口說明”, httpMethod = “接口請求方式”, response = “接口返回參數類型”, notes = “接口發布說明”;其他參數可參考源碼; 
@ApiParam(required = “是否必須參數”, name = “參數名稱”, value = “參數具體描述”

Step5:添加Swagger UI配置

GitHub上下載SwaggerUI項目,將dist下所有內容拷貝到本地項目webapp下面,結果目錄如下圖所示: 
webapp目錄結構

Step6:修改index.html

將index.html中http://petstore.swagger.wordnik.com/v2/swagger.json修改為http://localhost:8080/{projectname}/api-docs

到此為止,所有配置完成,啟動你的項目,訪問http://localhost:8080/{projectName}/index.html即可看到如下所示頁面: 
首頁
接口詳細說明

項目最終demo可見個人GitHub 
https://github.com/itboyspg/spg-code/tree/master/apidoc 
參考: 
https://github.com/martypitt/swagger-springmvc 
https://github.com/swagger-api/swagger-ui

項目jar包下載:http://download.csdn.net/detail/fengspg/8550451

 

 
        當我們把我們的服務以REST的形式接口暴露出去,其他開發者要調用我們的接口首先要能夠詳細的了解我們的API,目前幾乎所有的開放平台都是把API以文檔的形式放在網站上,例如:新浪、淘寶、微信等等。
在開發者調用API之前對一些API說明的理解比較模糊,總想着能直接驗證一下自己的理解就好了,而不是需要去項目寫測試代碼來驗證自己的想法。即API文檔應具備直接執行能力。Swagger就是這樣的一個利器,Swagger 是一個規范和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。
 
下面說一下如何為現有項目添加Swagger
首先添加對Swagger的依賴

<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-core_2.10</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.10.0</version>
</dependency>

加入對Swagger的配置類:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
import com.wordnik.swagger.model.ApiInfo;

@Configuration
@EnableSwagger
public class MySwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;

/**
* Required to autowire SpringSwaggerConfig
*/
@Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}

/**
* Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc framework - allowing for multiple
* swagger groups i.e. same code base multiple swagger resource listings.
*/
@Bean
public SwaggerSpringMvcPlugin customImplementation(){
SwaggerSpringMvcPlugin ssmp = new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
.apiInfo(apiInfo())
.swaggerGroup("api-docs").build();
return ssmp;
}

private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(
"tk API SPECIFICATION",
"This is the tk api specification,here you can dig into the details of api and do api testing as well.",
"",
"",
"",
"");
return apiInfo;
}
}

在application.xml中增加配置:

<mvc:annotation-driven/>
<bean id="apiDoc" class="com.tk.framework.rest.framework.swaggerconfig.MySwaggerConfig"/>
<!-- Enable scanning of spring @Configuration classes -->
<context:annotation-config/>
<!-- Enable the default documentation controller-->
<context:component-scan base-package="com.mangofactory.swagger.controllers"/>

<!-- Pick up the bundled spring config-->
<context:component-scan base-package="com.mangofactory.swagger.configuration"/>

接着,給開放API的Resource類加上API Annotation,這樣上一步配置的Scanner就能夠掃描到該Resource開放的API了。 

@RestController
@RequestMapping(value = "/1/users")
@Api(value = "User", description = "User service api", position = 1)
public class UserResourceV1 extends BaseResources
{
private static final Logger logger = LoggerFactory.getLogger(UserResourceV1.class);
@Autowired
private UserService userService;

@ResourceDescription(Resource="user", Operation="getUser")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ApiOperation(httpMethod = "GET", nickname="getUser", value = "get user by userId")
public ResponseModel getUser(@ApiParam(value = "id for greeting", required = true)@PathVariable String id) throws RestException
{
UserModel u = null;
try
{
u = userService.findById(id);
}
catch (Exception e)
{
logger.error(e.getMessage());
throw new RestException(e.getMessage());
}
ResponseModel r = new ResponseModel();
r.setStatus(200);
r.setResult(u);
return r;
}

}

為Model添加Swagger的Annotation,這樣Swagger Scanner可以獲取更多關於Model對象的信息。 :

@ApiModel(value="User")
@Entity
@Table(name = "user")
public class UserModel {
/**
* id
*/
@ApiModelProperty(required = true)
private String id;
/**
* 姓名
*/
@ApiModelProperty(required = true)
private String name;
/**
* 年齡
*/
@ApiModelProperty(required = true, allowableValues="range[1,100]")
private Integer age;
/**
* 性別
*/
@ApiModelProperty(required = true, allowableValues = "F,M")
private String sex;
@ApiModelProperty(required = true)
private String password;


……

在Swagger Annotation中:
 
    @API表示一個開放的API,可以通過description簡要描述該API的功能。
    在一個@API下,可有多個@ApiOperation,表示針對該API的CRUD操作。在ApiOperation Annotation中可以通過value,notes描述該操作的作用,response描述正常情況下該請求的返回對象類型。
    在一個ApiOperation下,可以通過ApiResponses描述該API操作可能出現的異常情況。
    @ApiParam用於描述該API操作接受的參數類型
 
接下來,我們把這些信息和Swagger UI集成,以非常美觀,實用的方式把這些API信息展示出來。 
首先,從github(https://github.com/wordnik/swagger-ui)上下載Swagger-UI, 把該項目dist目錄下的內容拷貝到項目的webapp的目錄下。 
RESTful風格的Web服務框架:Swagger - 慕希顏 - 當下即道場
 
 然后,修改index.jsp, 把Swagger UI對象中的URL替換為自己的API路徑:

window.swaggerUi = new SwaggerUi({
url: "/api/api-docs",
dom_id: "swagger-ui-container",

啟動項目,最后如下圖所示:
 
RESTful風格的Web服務框架:Swagger - 慕希顏 - 當下即道場
 
 
RESTful風格的Web服務框架:Swagger - 慕希顏 - 當下即道場
 
RESTful風格的Web服務框架:Swagger - 慕希顏 - 當下即道場
 
 具有直接測試API的能力:
RESTful風格的Web服務框架:Swagger - 慕希顏 - 當下即道場
  
http://blog.163.com/xh_ding/blog/static/193903289201411592759809/
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM