使用swagger作为restful api的doc文档生成
初衷
记得以前写接口,写完后会整理一份API接口文档,而文档的格式如果没有具体要求的话,最终展示的文档则完全决定于开发者的心情。也许多点,也许少点。甚至,接口总是需要适应新需求的,修改了,增加了,这份文档维护起来就很困难了。于是发现了swagger,自动生成文档的工具。
swagger介绍
首先,官网这样写的:
Swagger – The World's Most Popular Framework for APIs.
因为自强所以自信。swagger官方更新很给力,各种版本的更新都有。swagger会扫描配置的API文档格式自动生成一份json数据,而swagger官方也提供了ui来做通常的展示,当然也支持自定义ui的。不过对后端开发者来说,能用就可以了,官方就可以了。
最强的是,不仅展示API,而且可以调用访问,只要输入参数既可以try it out.
效果为先,最终展示doc界面,也可以设置为中文:
在dropwizard中使用
详细信息见另一篇在dropwizard中使用Swagger
在spring-boot中使用
以前总是看各种博客来配置,这次也不例外。百度了千篇一律却又各有细微的差别,甚至时间上、版本上各有不同。最终还是去看官方文档,终于发现了官方的sample。针对于各种option的操作完全在demo中了,所以clone照抄就可以用了。
github sample源码
配置
1.需要依赖两个包:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-version}</version>
</dependency>
第一个是API获取的包,第二是官方给出的一个ui界面。这个界面可以自定义,默认是官方的,对于安全问题,以及ui路由设置需要着重思考。
2.swagger的configuration
需要特别注意的是swagger scan base package,这是扫描注解的配置,即你的API接口位置。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.test.web.controllers";
public static final String VERSION = "1.0.0";
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger API")
.description("This is to show api description")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.termsOfServiceUrl("")
.version(VERSION)
.contact(new Contact("","", "miaorf@outlook.com"))
.build();
}
@Bean
public Docket customImplementation(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
.build()
.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
.apiInfo(apiInfo());
}
}
当然,scan package 也可以换成别的条件,比如:
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.build();
}
3.在API上做一些声明
//本controller的功能描述
@Api(value = "pet", description = "the pet API")
public interface PetApi {
//option的value的内容是这个method的描述,notes是详细描述,response是最终返回的json model。其他可以忽略
@ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = {
@Authorization(value = "petstore_auth", scopes = {
@AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
@AuthorizationScope(scope = "read:pets", description = "read your pets")
})
}, tags={ "pet", })
//这里是显示你可能返回的http状态,以及原因。比如404 not found, 303 see other
@ApiResponses(value = {
@ApiResponse(code = 405, message = "Invalid input", response = Void.class) })
@RequestMapping(value = "/pet",
produces = { "application/xml", "application/json" },
consumes = { "application/json", "application/xml" },
method = RequestMethod.POST)
ResponseEntity<Void> addPet(
//这里是针对每个参数的描述
@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);
案例:
package com.test.mybatis.web.controllers;
import com.test.mybatis.domain.entity.City;
import com.test.mybatis.domain.entity.Hotel;
import com.test.mybatis.domain.mapper.CityMapper;
import com.test.mybatis.domain.mapper.HotelMapper;
import com.test.mybatis.domain.model.common.BaseResponse;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Created by miaorf on 2016/9/10.
*/
@Api(value = "Test", description = "test the swagger API")
@RestController
public class TestController {
@Autowired
private CityMapper cityMapper;
@Autowired
private HotelMapper hotelMapper;
@ApiOperation(value = "get city by state", notes = "Get city by state", response = City.class)
@ApiResponses(value = {@ApiResponse(code = 405, message = "Invalid input", response = City.class) })
@RequestMapping(value = "/city", method = RequestMethod.GET)
public ResponseEntity<BaseResponse<City>> getCityByState(
@ApiParam(value = "The id of the city" ,required=true ) @RequestParam String state){
City city = cityMapper.findByState(state);
if (city!=null){
BaseResponse response = new BaseResponse(city,true,null);
return new ResponseEntity<>(response, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@ApiOperation(value = "save city", notes = "", response = City.class)
@RequestMapping(value = "/city", method = RequestMethod.POST)
public ResponseEntity<BaseResponse<City>> saveCity(
@ApiParam(value = "The id of the city" ,required=true ) @RequestBody City city){
int save = cityMapper.save(city);
if (save>0){
BaseResponse response = new BaseResponse(city,true,null);
return new ResponseEntity<>(response, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@ApiOperation(value = "save hotel", notes = "", response = Hotel.class)
@RequestMapping(value = "/hotel", method = RequestMethod.POST)
public ResponseEntity<BaseResponse<Hotel>> saveHotel(
@ApiParam(value = "hotel" ,required=true ) @RequestBody Hotel hotel){
int save = hotelMapper.save(hotel);
if (save>0){
BaseResponse response = new BaseResponse(hotel,true,null);
return new ResponseEntity<>(response, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@ApiOperation(value = "get the hotel", notes = "get the hotel by the city id", response = Hotel.class)
@RequestMapping(value = "/hotel", method = RequestMethod.GET)
public ResponseEntity<BaseResponse<Hotel>> getHotel(
@ApiParam(value = "the hotel id" ,required=true ) @RequestParam Long cid){
List<Hotel> hotels = hotelMapper.selectByCityId(cid);
return new ResponseEntity<>(new BaseResponse(hotels,true,null), HttpStatus.OK);
}
@ApiOperation(value = "update the hotel", notes = "update the hotel", response = Hotel.class)
@RequestMapping(value = "/hotel", method = RequestMethod.PUT)
public ResponseEntity<BaseResponse<Hotel>> updateHotel(
@ApiParam(value = "the hotel" ,required=true ) @RequestBody Hotel hotel){
int result = hotelMapper.update(hotel);
return new ResponseEntity<>(new BaseResponse(result,true,null), HttpStatus.OK);
}
@ApiOperation(value = "delete the hotel", notes = "delete the hotel by the hotel id", response = City.class)
@RequestMapping(value = "/hotel", method = RequestMethod.DELETE)
public ResponseEntity<BaseResponse<Hotel>> deleteHotel(
@ApiParam(value = "the hotel id" ,required=true ) @RequestParam Long htid){
int result = hotelMapper.delete(htid);
return new ResponseEntity<>(new BaseResponse(result,true,null), HttpStatus.OK);
}
}
4.设定访问API doc的路由
在配置文件中,application.yml中声明:
springfox.documentation.swagger.v2.path: /api-docs
这个path就是json的访问request mapping.可以自定义,防止与自身代码冲突。
API doc的显示路由是:http://localhost:8080/swagger-ui.html
如果项目是一个webservice,通常设定home / 指向这里:
@Controller
public class HomeController {
@RequestMapping(value = "/swagger")
public String index() {
System.out.println("swagger-ui.html");
return "redirect:swagger-ui.html";
}
}
5.访问
就是上面的了。但是,注意到安全问题就会感觉困扰。首先,该接口请求有几个:
http://localhost:8080/swagger-resources/configuration/ui
http://localhost:8080/swagger-resources
http://localhost:8080/api-docs
http://localhost:8080/swagger-resources/configuration/security
除却自定义的url,还有2个ui显示的API和一个安全问题的API。关于安全问题的配置还没去研究,但目前发现一个问题是在我的一个项目中,所有的url必须带有query htid=xxx,这是为了sso portal验证的时候需要。这样这个几个路由就不符合要求了。
如果不想去研究安全问题怎么解决,那么可以自定ui。只需要将ui下面的文件拷贝出来,然后修改请求数据方式即可。
6. 设置在生产环境关闭swagger
具体参考 http://www.cnblogs.com/woshimrf/p/disable-swagger.html
参考:
1.swagger官网:http://swagger.io/
2.github: https://github.com/swagger-api/swagger-codegen/blob/master/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java
3.后续阅读文章:
- http://yukinami.github.io/2015/07/07/使用springfox生成springmvc项目的swagger的文档/
- http://www.aichengxu.com/view/2500558
使用swagger作为restful api的doc文档生成的更多相关文章
- 使用swagger作为restful api的doc文档生成——从源码中去提取restful URL接口描述文档
初衷 记得以前写接口,写完后会整理一份API接口文档,而文档的格式如果没有具体要求的话,最终展示的文档则完全决定于开发者的心情.也许多点,也许少点.甚至,接口总是需要适应新需求的,修改了,增加了,这份 ...
- doc文档生成带目录的pdf文件方法
准备软件: 福昕PDF阅读器 下载地址:http://rj.baidu.com/soft/detail/12882.html?ald 安装福昕PDF阅读器,会自动安装pdf打印机. 准备好设置好各级标 ...
- IDEA生成doc文档-生成chm文档
首先,打开IDEA,并找到Tools -> Generate JavaDoc- 可供查询的chm比那些HTML页面好看多了. 如果您用过JDK API的chm文档,那么您一定不会拒绝接受其它第三 ...
- sphinx doc 文档生成脚手架工具
sphinx 在python 语言开发中,是一个使用的比较多文档生成脚手架工具,我们帮助我们生成 专业的帮助文档,同时也有远端的免费saas 托管服务,方便分发 安装 sphinx 的安装好多方便,m ...
- 使用swagger实现web api在线接口文档
一.前言 通常我们的项目会包含许多对外的接口,这些接口都需要文档化,标准的接口描述文档需要描述接口的地址.参数.返回值.备注等等:像我们以前的做法是写在word/excel,通常是按模块划分,例如一个 ...
- 使用swagger实现web api在线接口文档(转载)
一.前言 通常我们的项目会包含许多对外的接口,这些接口都需要文档化,标准的接口描述文档需要描述接口的地址.参数.返回值.备注等等:像我们以前的做法是写在word/excel,通常是按模块划分,例如一个 ...
- 使用 swagger组件给asp.net webapi文档生成
1.名词解释 Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件的方法,参数和模 ...
- Web Api 多项目文档生成之SwaggerUI
SwaggerUI 可以生成不错的文档,但默认只能作用于单个api 项目,研究了一下源码发现只需修改一下SwaggerConfig.cs文件即可支持多API项目 1.使用生成脚本把xml文件复制到AP ...
- Node与apidoc的邂逅——NodeJS Restful 的API文档生成
作为后台根据需求文档开发完成接口后,交付给前台(angular vue等)做开发,不可能让前台每个接口调用都去查看你的后台代码一点点查找.前台开发若不懂你的代码呢?让他一个接口一个接口去问你怎么调用, ...
随机推荐
- 微信小程序体验(2):驴妈妈景区门票即买即游
驴妈妈因为出色的运营能力,被腾讯选为首批小程序内测单位.驴妈妈的技术开发团队在很短的时间内完成了开发任务,并积极参与到张小龙团队的内测问题反馈.驴妈妈认为,移动互联网时代,微信是巨大的流量入口,也是旅 ...
- HTML 事件(二) 事件的注册与注销
本篇主要介绍HTML元素事件的注册.注销的方式. 其他事件文章 1. HTML 事件(一) 事件的介绍 2. HTML 事件(二) 事件的注册与注销 3. HTML 事件(三) 事件流.事件委托 4. ...
- Sublime的使用
1.一个可扩展性强的编辑工具 2.如何安装扩展 通过View->Show Console菜单打开命令行. 按图操作: 在控制台输入,然后回车: import urllib.request,os; ...
- const,static,extern 简介
const,static,extern 简介 一.const与宏的区别: const简介:之前常用的字符串常量,一般是抽成宏,但是苹果不推荐我们抽成宏,推荐我们使用const常量. 执行时刻:宏是预编 ...
- Coroutine in Java - Quasar Fiber实现--转载
转自 https://segmentfault.com/a/1190000006079389?from=groupmessage&isappinstalled=0 简介 说到协程(Corout ...
- [原]Redis主从复制各种环境下测试
Redis 主从复制各种环境下测试 测试环境: Linux ubuntu 3.11.0-12-generic 2GB Mem 1 core of Intel(R) Core(TM) i5-3470 C ...
- Linux命令【第一篇】
1.创建一个目录/data 记忆方法:英文make directorys缩写后就是mkdir. 命令: mkdir /data 或 cd /;mkdir data #提示:使用分号可以在一行内分割两个 ...
- TCP的数据传输小结
TCP的交互数据流 交互式输入 通常每一个交互按键都会产生一个数据分组,也就是说,每次从客户传到服务器的是一个字节的按键(而不是每次一行) 经受时延的确认 通常TCP在接受到数据时并不立即发送ACK: ...
- hasOwnProperty()、propertyIsEnumerable()和isPrototypeOf()的用法
javascript中有原型这么一个概念,任何一个构造函数都有它对应的原型(prototype),我们可以给这个原型赋予一些我们想要的属性,像下面这样: function Gadget(name, c ...
- 用命令行工具创建 NuGet 程序包
NuGet.exe 下载地址 本文翻译自: https://docs.nuget.org/Create/Creating-and-Publishing-a-Package https://docs.n ...