Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spring Boot中使用Swagger2构建API文档 #1

Open
Yuicon opened this issue Aug 6, 2017 · 15 comments
Open

Spring Boot中使用Swagger2构建API文档 #1

Yuicon opened this issue Aug 6, 2017 · 15 comments

Comments

@Yuicon
Copy link
Owner

Yuicon commented Aug 6, 2017

程序员都很希望别人能写技术文档,自己却很不愿意写文档。因为接口数量繁多,并且充满业务细节,写文档需要花大量的时间去处理格式排版,代码修改后还需要同步修改文档,经常因为项目时间紧等原因导致文档滞后于代码,接口调用方的抱怨声不绝于耳。而程序员是最擅长"偷懒"的职业了,自然会有多种多样的自动生成文档的插件.今天要介绍的就是Swagger.

接下来我们在Spring Boot中使用Swagger2构建API文档

Swagger是一个简单但功能强大的API表达工具。它具有地球上最大的API工具生态系统,数以千计的开发人员,使用几乎所有的现代编程语言,都在支持和使用Swagger。使用Swagger生成API,我们可以得到交互式文档,自动生成代码的SDK以及API的发现特性等。

我们先来看看具体效果:
tim 20170806152444

可以看到Swagger-Ui是以controller分类,点击一个controller可以看到其中的具体接口,再点击接口就可以看到接口的信息了,如图:

tim 20170806152444

我们可以看到该接口的请求方式,返回数据信息和需要传递的参数.而且以上数据是自动生成的,即使代码有一些修改,Swagger文档也会自动同步修改.非常的方便.

  • 构建RESTful API

在使用Swagger2前我们需要有一个RESTful API的项目. Spring-Boot创建RESTful API项目非常的方便和快速,这里不再介绍如何创建,需要的可以参照项目代码

  • 添加Swagger2依赖

在pom.xml文件中加入以下依赖.

        <dependency>
            <groupId>io.springfox</groupId>
	    <artifactId>springfox-swagger2</artifactId>
	    <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
  • 创建Swagger2的Java配置类

    通过@Configuration注解,表明它是一个配置类,@EnableSwagger2 注解开启swagger2。apiInfo() 方法配置一些基本的信息。createRestApi() 方法指定扫描的包会生成文档,默认是显示所有接口,可以用@ApiIgnore注解标识该接口不显示。

/**
 * Created by Yuicon on 2017/5/20.
 * https://github.com/Yuicon
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 指定controller存放的目录路径
                .apis(RequestHandlerSelectors.basePackage("com.digag.web"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                 // 文档标题
                .title("DigAg")
                // 文档描述
                .description("https://github.com/Yuicon")
                .termsOfServiceUrl("https://github.com/Yuicon")
                .version("v1")
                .build();
    }

}
  • 编辑文档接口信息

先看一个例子:

    @ApiOperation(value="创建条目")
    @RequestMapping(method = RequestMethod.POST)
    public JsonResult<Entry> saveEntry(@RequestBody @ApiParam(value = "条目对象", required = true) Entry entry, HttpServletRequest request) {
        return entryService.create(entry, request);
    }

Swagger2提供了一些注解来丰富接口的信息,常用的有:

@ApiOperation:用在方法上,说明方法的作用

  • value: 表示接口名称
  • notes: 表示接口详细描述

@ApiImplicitParams:用在方法上包含一组参数说明

@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

  • paramType:参数位置
  • header 对应注解:@RequestHeader
  • query 对应注解:@RequestParam
  • path 对应注解: @PathVariable
  • body 对应注解: @RequestBody
  • name:参数名
  • dataType:参数类型
  • required:参数是否必须传
  • value:参数的描述
  • defaultValue:参数的默认值

@ApiResponses:用于表示一组响应

@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

  • code:状态码

  • message:返回自定义信息

  • response:抛出异常的类

  • 访问文档

swagger2文档的默认地址是 /swagger-ui.html, 本地开发的访问 http://localhost:8080/swagger-ui.html就可以看到自动生成的文档了.

完整结果示例可查看项目代码

参考信息

Swagger注解文档
Swagger官方网站

@tustman
Copy link

tustman commented Aug 7, 2017

挺不错的. 我们新的项目也准备用这个来管理.

@Yuicon
Copy link
Owner Author

Yuicon commented Aug 7, 2017

@2cyhc2 😃 多谢支持

@yutaolian
Copy link

如果参数是javabean 如何隐藏javabean中的部分字段

@Yuicon
Copy link
Owner Author

Yuicon commented Aug 9, 2017

@yutaolian 在Swagger注解文档里 有个 @ApiModelProperty 注解 设置 hidden 属性

@zhuSilence
Copy link

@Yuicon
请问下,我在启动Springboot项目后,访问地址http://localhost:8083/swagger-ui.html 显示
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu Nov 30 10:45:37 CST 2017
There was an unexpected error (type=Not Found, status=404).
No message available

后台提示:
[ INFO ] [2017-11-30 10:45:37] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] [179] - Initializing Spring FrameworkServlet 'dispatcherServlet'
[ INFO ] [2017-11-30 10:45:37] org.springframework.web.servlet.DispatcherServlet [489] - FrameworkServlet 'dispatcherServlet': initialization started
[ INFO ] [2017-11-30 10:45:37] org.springframework.web.servlet.DispatcherServlet [508] - FrameworkServlet 'dispatcherServlet': initialization completed in 21 ms
[ ERROR] [2017-11-30 10:45:37] org.apache.velocity [96] - ResourceManager : unable to find resource 'error.vm' in any resource loader.
[ ERROR] [2017-11-30 10:45:37] org.apache.velocity [96] - ResourceManager : unable to find resource 'error.html.vm' in any resource loader.

找不到这个路径,请问是还需要配置什么吗?
下面是我的Swagger2文件和controller
@EnableSwagger2
@configuration
public class Swagger2 {

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            // 指定controller存放的目录路径
            .apis(RequestHandlerSelectors.basePackage("com.coocaa.salad.customer.controller"))
            .paths(PathSelectors.any())
            .build();
}

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            // 文档标题
            .title("Test")
            // 文档描述
            .description("**********")
            .termsOfServiceUrl("**********")
            .version("v1")
            .build();
}

}

@ApiOperation(value = "新增计划单接口", notes = "新增")
@Auth(verifyLogin = false)
@RequestMapping(value = "add", produces = "text/html;charset=UTF-8", method = {RequestMethod.POST})
@responsebody
public ResultMsg add(@RequestBody @ApiParam(value = "参数信息", required = true) CustomerModel model) throws Exception {
ResultMsg result = Filter.paramCheck(model);

    return result;
}

@Yuicon
Copy link
Owner Author

Yuicon commented Nov 30, 2017

@zhuSilence 项目代码 对照着看下有哪里不一样 我没你的项目代码也看不出来为什么

@zhuSilence
Copy link

zhuSilence commented Nov 30, 2017 via email

@851999206
Copy link

作者你好,我问一下现在我返回的统一格式的响应类,但是我现在想在页面看到实体的属性应该怎么做,如代码:我现在想要知道UserResponse的属性并显示在swaggerui 。但是现在只显示了ApiResult的属性。
public ApiResult userList( ){
UserResponse ress = new UserResponse();
ress.setList(service.userList());
return new ApiResult(ress);
}

@Yuicon
Copy link
Owner Author

Yuicon commented May 9, 2018

@851999206 你可以看下这个响应类的实现

@851999206
Copy link

@Yuicon 谢谢

@wanglulei
Copy link

请问一下,这个swagger能通过外网访问么

@Yuicon
Copy link
Owner Author

Yuicon commented May 22, 2019

@wanglulei swagger2文档的默认地址是 /swagger-ui.html, 本地开发的访问 http://localhost:8080/swagger-ui.html就可以看到自动生成的文档了. 和自定义的接口没什么区别

@wanglulei
Copy link

@Yuicon 我现在是在本地启动一个swagger的项目,然后通过nginx用一个外网ip指向我本地,接口是通的,但是swagger文档却不行。

@Yuicon
Copy link
Owner Author

Yuicon commented May 23, 2019

@wanglulei 看看有没有报什么错,我当时也部署到服务器了是没问题的

@wanglulei
Copy link

@Yuicon 好的,感谢。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants