为了账号安全,请及时绑定邮箱和手机立即绑定

Swagger 这一个文章就够了

标签:
MySQL

Swagger 这一个文章就够了

Swagger快速理解

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

Swagger官网:http://swagger.io

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

- 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 编译完接口文档之后呢,会形成一个文件。

Swagger UI

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

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

Swagger Edit和Swagger UI 互补性存在

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

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

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的运行环境。

下载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

npm install -g http-server

-g表示全局

启动ui和edit

http-server –p 12321 swagger-editor
http-server –p 12421 swagger-ui

cd swagger-ui/dist

vim index.html

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

...
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',
...

然后保存后

打开浏览器:

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文件中,放入如下插件:

<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)

引入依赖

<!-- 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编码的方式实现配置。代码如下:

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的配置文件中加入以下配置即可。

<bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />

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

/**
* 根据用户名获取用户对象
* @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配置文件中需要配置对静态文件的处理方式。

//所有swagger目录的访问,直接访问location指定的目录
<mvc:resources mapping="/swagger/**" location="/WEB-INF/swagger/"/>

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

参考:

·············
欢迎关注专栏:

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
软件测试工程师
手记
粉丝
14
获赞与收藏
64

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消