Swagger 详解

Swagger 这一个文章就够了

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到底什么关系呢?

- 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文件,即可看到接口文档说明了

参考:

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

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Swagger是一种API文档生成工具,它可以根据代码自动生成API文档,并且可以通过Swagger UI进行查看和测试。Swagger注解是用来描述API信息的一种方式,它可以帮助Swagger生成准确的API文档。 下面是Swagger注解的使用详解: 1. @Api:用于描述API的基本信息,包括API的名称、描述、版本号等。 2. @ApiOperation:用于描述API的操作,包括HTTP请求方法、请求路径、请求参数、返回值等。 3. @ApiParam:用于描述API的参数信息,包括参数名称、参数类型、是否必须、默认值等。 4. @ApiModel:用于描述API的数据模型,包括模型名称、模型属性等。 5. @ApiModelProperty:用于描述API的数据模型属性,包括属性名称、属性类型、是否必须、默认值等。 6. @ApiIgnore:用于忽略API的某些信息,比如某个参数或返回值。 7. @ApiResponses:用于描述API的响应信息,包括响应状态码、响应描述、响应数据类型等。 8. @ApiResponse:用于描述API的单个响应信息,包括响应状态码、响应描述、响应数据类型等。 9. @ApiError:用于描述API的错误信息,包括错误码、错误描述、错误数据类型等。 10. @ApiImplicitParam:用于描述API的隐式参数,比如请求头、请求体等。 11. @ApiImplicitParams:用于描述API的多个隐式参数。 总之,Swagger注解提供了丰富的API描述功能,可以帮助我们更好地生成准确的API文档,提高API的可读性和可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CrissChan

开心就好

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值