springboot项目使用Swagger RestAPI最佳说明文档

springboot项目使用Swagger RestAPI最佳说明文档

我们在开发各种rest服务的时候,需要给出rest api的介绍使用。如果没有rest API的介绍使用文档,除了看源代码几乎没人知道怎么使用。那么如何来编写rest API的说明文档了? 当然我们可以自己写一个类似javadoc的工具,然后每次构建的时候生成对应的html, 或者字节开发注解,然后根据一定规则生成rest doc文档, 那么有没有一种开源的,统一并且便捷好用的rest 说明文档工具了? 当然有,那就是Swagger.

我们先看看Swagger官方网站是如何介绍该项目的。
Swagger–The World’s Most Popular API Tooling, 世界上最流行的API工具。

下面我们直接进入正题,如何在springboot项目中使用Swagger。总共分为三部
第一步,引入swagger依赖
第二部,在spring-boot中配置swagger-ui界面
第三步,提供API文档页基本信息
第四步,给rest API编写文档
项目在https://github.com/yqbjtu/springbootJpa/tree/2.0swagger。 欢迎下载和关注, 谢谢!

第一步引入swagger依赖

在pom文件中添加如下依赖

        <!-- Use Swagger for rest API -->
        <dependency>
        <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        <version>2.8.0</version>
        </dependency>
        <dependency>
           <groupId>io.springfox</groupId>
           <artifactId>springfox-swagger-ui</artifactId>
           <version>2.8.0</version>
        </dependency>

第二步 在spring-boot中配置swagger-ui界面

在我们项目中增加一个类WebMvcConfig。

package com.yq.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

第三步 提供API文档页基本信息

也是添加一个新类
package com.yq.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.service.Contact;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {
//swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage(“com.yq.demo.controller”))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(“Spring Boot 测试使用 Swagger2 构建RESTful API”)
.contact(new Contact(“EricYang”, “https://github.com/yqbjtu/springbootJpa.git“, “[email protected]”))
.version(“1.0”)
.description(“User API 描述”)
.build();
}

}

第四步,给rest API编写文档

这一步是我们的主要工作,这里我们给两个Controller编写api文档
第一个是HelloWorldController, 它有一个get rest api显示Hello World

    @ApiOperation(value = "hello demo", notes = "just for demo")
    @GetMapping(value = "/hello", produces = "text/plain;charset=UTF-8")
    public String hello() {
        return "Hello World";
    }

可以看到@GetMapping(value = “/hello”, produces = “text/plain;charset=UTF-8”)
其中的value = “/hello”就是我们rest的路径, 因为我们返回的是字符串,所以使用”text/plain;charset=UTF-8”
下面是另外一个UserController, API比较多, 我们选择其中2个,项目类容可以参看源代码

    @ApiOperation(value = "add new user", notes = "add new user to system")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userName", value = "userName", required = true, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "password", value = "密码", required = true ,dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "fullName", value = "fullName", required = true ,dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "email", value = "email", required = true ,dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "usertype", allowableValues="1,2,3", required = false ,dataType = "int", paramType = "query"),
        @ApiImplicitParam(name = "dateformat", value = "dateformat", required = false ,dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "timeforamt", value = "timeforamt", required = false ,dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "timezone", value = "timezone", required = false ,dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "language", value = "language", required = false ,dataType = "String", paramType = "query")
    })

    @PostMapping(value = "/add", produces = "application/json;charset=UTF-8")
    public  @ResponseBody User addNewUser(
            @RequestParam String userName,
            @RequestParam String password,
            @RequestParam String fullName,
            @RequestParam String email,
            @RequestParam Integer usertype,
            @RequestParam(value = "dateformat", defaultValue = "yyyy-MM-dd") String dateformat,
            @RequestParam(value = "timeforamt", defaultValue = "HH:mm:ss") String timeforamt,
            @RequestParam(value = "timezone", defaultValue = "GMT+8") String timezone,
            @RequestParam(value = "language", defaultValue = "zh_CN") String language) {

        User user = new User();
        user.setUsername(userName);
        user.setFullname(fullName);
        user.setEmail(email);
        user.setLanguage(language);
        user.setPassword(password);
        user.setActive(1);
        user.setUserType(usertype);
        user.setCan_delete(1);
        user.setTimeZone(timezone);
        user.setTimeFormat(timeforamt);
        user.setDateFormat(dateformat);
        userRepository.save(user);

        return user;
    }

下面这个是根据FullName进行查询的例子。其中只有一个path的参数fullname

    @ApiOperation(value = "findByFullName", notes = "find by fullName")
    @ApiImplicitParam(name = "fullname", value = "fullname", required = true, dataType = "String", paramType = "path")
    @GetMapping(value = "/findByFullName/{fullname}", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public User getUserByFullName(@PathVariable String fullname){
        User user = userRepository.getByFullName(fullname);
        return user;
    }

最后运行我们的项目, 在浏览器打开http://127.0.0.1:8080/swagger-ui.html

示例图1
这里写图片描述

选择运行findByFullName
这里写图片描述

猜你喜欢

转载自blog.csdn.net/russle/article/details/79769656