引言:随着技术的革新,现在的系统基本上都是前后端分离,并且在各自的道路上越走越远,而前后端之间通信或者联系的桥梁就是API,而这里基于RESTful风格的API框架就来了!欲知后事如何,客官别急,往下戳!!!

一、Swagger是什么

1.官网:https://swagger.io/

2.Swagger是一款让我们更好地书写API文档的框架

3.功能:书写API、展示接口、测试接口(传参数,包括request和response)--很直观,很精简

4.这个神奇的东西的真面目

RestFul风格API(Swagger)--从零开始Swagger

注:由于小编是菜鸟,所以我最直观的感受是swagger可以把我们写的后端接口(java接口)直观地展示再前台(如上图),而且非常容易上手使用,不信请继续往下看[嘻嘻]

二、Swagger的使用

1.maven项目,springboot等

2.使用步骤:

    1、pom.xml中引入Swagger相关的jar包

RestFul风格API(Swagger)--从零开始Swagger

 1 <dependency>
 2     <groupId>io.springfox</groupId>
 3     <artifactId>springfox-swagger-ui</artifactId>
 4     <version>2.7.0</version>
 5 </dependency>
 6 
 7 <dependency>
 8     <groupId>io.springfox</groupId>
 9     <artifactId>springfox-swagger2</artifactId>
10     <version>2.7.0</version>
11 </dependency>

     2、Swagger配置类

@Configuration通过这个注解让spring来加载配置
@EnableSwagger2注解用来启用swagger2

第三个注解没啥用,可不加

RestFul风格API(Swagger)--从零开始Swagger

package com.bjq.demo.wfw.show.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

@Configuration
@EnableSwagger2
public class SwaggerConfig { /** * 下面代码所示,通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。 * @return */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { Contact contact = new Contact("","",""); return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2构建RESTful APIs") .description("基于swager的RESTful API Swagger UI 框架") .termsOfServiceUrl("") .contact(contact) .version("1.0") .build(); } }

完成这两步后,基本上swagger就配置好了

     3、再接口中使用注解

RestFul风格API(Swagger)--从零开始Swagger

三、效果

RestFul风格API(Swagger)--从零开始Swagger

 

分类:

技术点:

相关文章: