首页 > 其他分享 >swagger UI

swagger UI

时间:2022-11-08 18:40:13浏览次数:33  
标签:springfox value application API UI swagger Swagger

swagger UI_html

Swagger UI

swagger UI_html_02

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。


作用:

•接口的文档在线自动生成。•功能测试。

Swagger是一组开源项目,其中主要要项目如下:

•Swagger-tools:提供各种与Swagger进行集成和交互的工具。例如模式检验、Swagger 1.2文档转换成Swagger 2.0文档等功能。•Swagger-core: 用于Java/Scala的的Swagger实现。与JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架进行集成。•Swagger-js: 用于JavaScript的Swagger实现。•Swagger-node-express: Swagger模块,用于node.js的Express web应用框架。•Swagger-ui:一个无依赖的HTML、JS和CSS集合,可以为Swagger兼容API动态生成优雅文档。•Swagger-codegen:一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端代码。

swagger UI_spring_03

Maven

版本号请根据实际情况自行更改。

<dependency>


<groupId>io.springfox</groupId>


<artifactId>springfox-swagger2</artifactId>


<version>2.2.2</version>


</dependency>


<dependency>


<groupId>io.springfox</groupId>


<artifactId>springfox-swagger-ui</artifactId>


<version>2.2.2</version>


</dependency>

具体使用

在API上做一些声明

//本controller的功能描述
@Api(value = "pet", description = "the pet API")
public interface PetApi {


//option的value的内容是这个method的描述,notes是详细描述,response是最终返回的json model。其他可以忽略
@ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = {
@Authorization(value = "petstore_auth", scopes = {
@AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
@AuthorizationScope(scope = "read:pets", description = "read your pets")
})
}, tags={ "pet", })


//这里是显示你可能返回的http状态,以及原因。比如404 not found, 303 see other
@ApiResponses(value = {
@ApiResponse(code = 405, message = "Invalid input", response = Void.class) })
@RequestMapping(value = "/pet",
produces = { "application/xml", "application/json" },
consumes = { "application/json", "application/xml" },
method = RequestMethod.POST)
ResponseEntity<Void> addPet(
//这里是针对每个参数的描述
@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body);

设定访问API doc的路由

在配置文件中,application.yml中声明:

springfox.documentation.swagger.v2.path: /api-docs

这个path就是json的访问request mapping.可以自定义,防止与自身代码冲突。

API doc的显示路由是:http://localhost:8080/swagger-ui.html

如果项目是一个webservice,通常设定home / 指向这里:

@Controller
public class HomeController {


@RequestMapping(value = "/swagger")
public String index() {
System.out.println("swagger-ui.html");
return "redirect:swagger-ui.html";
}
}

swagger的常用API

Swagger使用的注解及其说明:

@Api:用在类上,说明该类的作用。

@ApiOperation:注解来给API增加方法说明。

@ApiImplicitParams : 用在方法上包含一组参数说明。

@ApiImplicitParam:用来注解来给方法入参增加说明。

@ApiResponses:用于表示一组响应

@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

l   code:数字,例如400


l message:信息,例如"请求参数没填好"


l response:抛出异常的类

@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)

 @ApiModelProperty:描述一个model的属性


swagger UI_spring_04


标签:springfox,value,application,API,UI,swagger,Swagger
From: https://blog.51cto.com/u_15501087/5834150

相关文章