前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Swagger 详解

Swagger 详解

作者头像
Criss@陈磊
发布2019-08-02 11:37:35
1.7K0
发布2019-08-02 11:37:35
举报
文章被收录于专栏:测试技术圈测试技术圈

Swagger快速理解

Swagger:The Best APIs are Built with Swagger Tools 。Swagger可以定义一个标准的RESTful风格的API,与语言无关,是一个API的规范。

Swagger官网:http://swagger.io

GitHub地址:https://github.com/swagger-api

这里,提到Swagger就不得不说说Springfox,Springfox是一个开源的API Doc的框架, 它的前身是swagger-springmvc,可以将我们的Controller中的方法以文档的形式展现。官方定义为: Automated JSON API documentation for API's built with Spring。Swagger和SpringFox到底什么关系呢?

代码语言:javascript
复制
- Swagger Spec 是一个规范。
- Swagger Api 是 Swagger Spec 规范 的一个实现,它支持 jax-rs, restlet, jersey 等等。
- Springfox libraries 是 Swagger Spec 规范 的另一个实现,专注于 spring 生态系统。
- Swagger.js and Swagger-ui 是 javascript 的客户端库,能消费该规范。
- springfox-swagger-ui 仅仅是以一种方便的方式封装了 swagger-ui ,使得 Spring 服务可以提供服务。

在官网的Tools菜单中,我们会发现里面有很多工具或者系统的介绍。其中我们最常用的两个工具一个是swagger editor、一个是swagger UI。

Swagger Edit

Swagger Edit主要是用来设计,描述API的工具,主要是提供给接口开发人员使用的。swagger editor 编译完接口文档之后呢,会形成一个yaml文件。

Swagger UI

Swagger UI允许任何人 - 无论是您的开发团队还是最终消费者 - 在没有任何实现逻辑的情况下可视化和与API资源交互。 它是从您的OpenAPI规范自动生成的,其可视化文档使后端实现和客户端消费变得容易。

swagger-editor主要是编写api接口文档,但需要配合swagger-ui来查看,里面的代码格式为yaml,但编辑后可以导出yml/json文件

Swagger Edit和Swagger UI 互补性存在

如果只是手动写api文档,人工查看那么就做部署Swagger Edit和Swagger UI就可以了。

通过下面命令下载两个项目:

代码语言:javascript
复制
mkdir swagger 
chmod 777 swagger
cd swagger
git clone https://github.com/swagger-api/swagger-editor.git
git clone https://github.com/swagger-api/swagger-ui.git

PS: UI和Edit都是NodeJS的开发,一次需要先安装Nodejs的运行环境。

代码语言:javascript
复制
下载nodejs的安装包,具体要去网站上查看最新版本
wget https://nodejs.org/dist/v6.11.3/node-v6.11.3.tar.gz
tar -zxvf node-v6.11.3.tar.gz
mv node-v6.11.3 /user/local/node
cd /usr/local/node
./configure
make 
make install
node -v

先安装http-server

代码语言:javascript
复制
npm install -g http-server

-g表示全局

启动ui和edit

代码语言:javascript
复制
http-server –p 12321 swagger-editor
http-server –p 12421 swagger-ui

cd swagger-ui/dist

vim index.html

进入index.html后,修改如下字段

代码语言:javascript
复制
...
const ui = SwaggerUIBundle({
//url: "http://petstore.swagger.io/v2/swagger.json",
url: "http://127.0.0.1:12321/json/1.json",
dom_id: '#swagger-ui',
...

然后保存后

打开浏览器:

代码语言:javascript
复制
swaggerEdit : http://127.0.0.1:12321
swaggerUI:http://127.0.0.1:12421/dist

Maven插件在原生工程里面快速生产Json的api文件(转自:https://blog.csdn.net/doctor_who2004/article/details/50816208)

在maven工程的pom文件中,放入如下插件:

代码语言:javascript
复制
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <configuration>
                    <charset>UTF-8</charset>
                    <docencoding>UTF-8</docencoding>
                    <failOnError>false</failOnError>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.github.kongchen</groupId>
                <artifactId>swagger-maven-plugin</artifactId>
                <configuration>
                    <apiSources>
                        <apiSource>
                            <springmvc>false</springmvc>
                            <locations>com.doctor.demo</locations>
                            <schemes>http,https</schemes>
                            <host>petstore.swagger.wordnik.com</host>
                            <basePath>/api</basePath>
                            <info>
                                <title>Swagger Maven Plugin Sample</title>
                                <version>v1</version>
                                <description>This is a sample for swagger-maven-plugin</description>
                                <termsOfService>
                                    http://www.github.com/kongchen/swagger-maven-plugin
                                </termsOfService>
                                <contact>
                                    <email>kongchen@gmail.com</email>
                                    <name>Kong Chen</name>
                                    <url>http://kongch.com</url>
                                </contact>
                                <license>
                                    <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
                                    <name>Apache 2.0</name>
                                </license>
                            </info>
                            Support classpath or file absolute path here. 1) classpath e.g: "classpath:/markdown.hbs", "classpath:/templates/hello.html" 2) file e.g: "${basedir}/src/main/resources/markdown.hbs", "${basedir}/src/main/resources/template/hello.html"
                            <templatePath>${basedir}/templates/strapdown.html.hbs</templatePath>
                            <outputPath>${basedir}/generated/document.html</outputPath>
                            <swaggerDirectory>generated/swagger-ui</swaggerDirectory>
                        </apiSource>
                    </apiSources>
                </configuration>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

Swagger和SpringMVC项目的整合(转自:https://www.cnblogs.com/jtlgb/p/6734177.html)

引入依赖

代码语言:javascript
复制
<!-- swagger-springmvc -->
    <dependency>
        <groupId>com.mangofactory</groupId>
        <artifactId>swagger-springmvc</artifactId>
        <version>1.0.2</version>
    </dependency>
    <dependency>
        <groupId>com.mangofactory</groupId>
        <artifactId>swagger-models</artifactId>
        <version>1.0.2</version>
    </dependency>
    <dependency>
        <groupId>com.wordnik</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.3.11</version>
    </dependency>
    <!-- swagger-springmvc dependencies -->
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>15.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.4.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.4.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.4.4</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml</groupId>
        <artifactId>classmate</artifactId>
        <version>1.1.0</version>
    </dependency>

Swagger配置

Swagger的配置实际上就是自定义一个Config类,通过java编码的方式实现配置。代码如下:

代码语言:javascript
复制
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* Created by xiaohui on 2016/1/14.
*/
@Configuration
@EnableSwagger
@EnableWebMvc
public class SwaggerConfig {

    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;
    }
}

在springmvc的配置文件中加入以下配置即可。

代码语言:javascript
复制
<bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />

  到目前为止,我们已经完成了对所有接口方法的扫描解析功能,那解析得到什么内容呢?这需要我们自定义,自定义操作的对象就是接口方法。先看段代码:

代码语言:javascript
复制
/**
* 根据用户名获取用户对象
* @param name
* @return
*/
@RequestMapping(value="/name/{name}", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "根据用户名获取用户对象", httpMethod = "GET", response = ApiResult.class, notes = "根据用户名获取用户对象")
public ApiResult getUserByName(@ApiParam(required = true, name = "name", value = "用户名") @PathVariable String name) throws Exception{
    UcUser ucUser = ucUserManager.getUserByName(name);

    if(ucUser != null) {
        ApiResult<UcUser> result = new ApiResult<UcUser>();
        result.setCode(ResultCode.SUCCESS.getCode());
        result.setData(ucUser);
        return result;
    } else {
        throw new BusinessException("根据{name=" + name + "}获取不到UcUser对象");
    }
}

上述代码是Controller中的一个方法,@ApiOperation注解对这个方法进行了说明,@ApiParam注解对方法参数进行了说明。关于这两个注解的使用,可以参看源码。这样子,Swagger就可以扫描接口方法,得到我们自定义的接口说明内容。

说明: 其中@ApiOperation和@ApiParam为添加的API相关注解,个参数说明如下: @ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”;其他参数可参考源码; @ApiParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”

Swagger-UI配置

Swagger扫描解析得到的是一个json文档,对于用户不太友好。下面介绍swagger-ui,它能够友好的展示解析得到的接口说明内容。

从https://github.com/swagger-api/swagger-ui 获取3.0版本以下,2.0版本以上。其所有的 dist 目录下东西放到需要集成的项目里,本文放入 src/main/webapp/WEB-INF/swagger/ 目录下。

修改swagger/index.html文件,默认是从连接http://petstore.swagger.io/v2/swagger.json获取 API 的 JSON,这里需要将url值修改为http://{ip}:{port}/{projectName}/api-docs的形式,{}中的值根据自身情况填写。比如我的url值为:http://localhost:8083/arrow-api/api-docs

因为swagger-ui项目都是静态资源,restful形式的拦截方法会将静态资源进行拦截处理,所以在springmvc配置文件中需要配置对静态文件的处理方式。

代码语言:javascript
复制
//所有swagger目录的访问,直接访问location指定的目录
<mvc:resources mapping="/swagger/**" location="/WEB-INF/swagger/"/>

 OK!大功告成,打开浏览器直接访问swagger目录下的index.html文件,即可看到接口文档说明了

是选择SwaggerUI+EDIT方式还是SpringMVC直接集成,就看你自己的需求了

参考:

https://blog.csdn.net/kinginblue/article/details/78513029 https://www.jianshu.com/p/52acab692a79 https://blog.csdn.net/doctor_who2004/article/details/50816208 https://www.cnblogs.com/jtlgb/p/6734177.html

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-03-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 质问 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Swagger快速理解
    • Swagger Edit
      • Swagger UI
        • Swagger Edit和Swagger UI 互补性存在
          • 通过下面命令下载两个项目:
          • 先安装http-server
          • 启动ui和edit
        • Maven插件在原生工程里面快速生产Json的api文件(转自:https://blog.csdn.net/doctor_who2004/article/details/50816208)
          • Swagger和SpringMVC项目的整合(转自:https://www.cnblogs.com/jtlgb/p/6734177.html)
            • 引入依赖
          • Swagger配置
            • Swagger-UI配置
          • 是选择SwaggerUI+EDIT方式还是SpringMVC直接集成,就看你自己的需求了
            • 参考:
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档