OpenApi specification

Declares a version for the document specification

Address: github.com/OAI/OpenAPI…

OpenApi introduction

The OpenApi specification has been developed over the years by companies such as Reverb Technologies and SmartBear, OpenApi plans to own the specification (after the donation), and The OpenApi Initiative hosts the community-driven specification on GitHub.

A specification is a language-neutral format for describing RestFul Web services in which applications can interpret generated files so that they can generate code, generate documentation, and create mock applications based on the services they describe.

The Open API Specification (OAS) is a way to document an API without having to write actual API code. This is an open source format that can be used to describe apis. In this process, we can use JSON or YAML format

OpenAPI documentation has three required sections or objects, and additional modules can be added:

1. Openapi – Indicates the semantic version number of the OpenAPI specification version

2. Info – Metadata about apis

3. Paths-api specifies available paths and operations

Industry automation interface document generation solution introduction

ApiDoc

Address: apidocjs.com/

Github:github.com/apidoc/apid…

Introduction: A tool that automatically generates API interface documentation directly from comments in source code

🌰

/** * @apigroup Product * @API {GET} / Product /{id} Query a Product * @apidescription interface description XXX * @APIParam {String} id Product ID (mandatory *) * @apisuccessexample SuccessExample * HTTP/1.1 200 * {* id: 'XXX ', * name:' XXX ', * desc: 'xxxx' * } * @apiErrorExample ErrorExample */ @GetMapping("/{id}") public Product detail(@PathVariable String id) { return JsonData.buildSuccess(); }Copy the code

advantages

  • Non-intrusive code
  • Support for cross-language use
  • User-friendly Introduction

Disadvantages: Node/NPM dependency

Swagger

Address: swagger. IO/tools/swagg…

Introduction: Add annotations to Java code to generate interface documentation

🌰

RestController @requestMapping (" API /v1/user") @API (tags = "User module ",value =" user UserController") Public Class UserController  { @Autowired private BannerService bannerService; @apiOperation (" page user list") @getMapping ("list") public JsonData list(){list <BannerDO> list = bannerService.list(); return JsonData.buildSuccess(list); }}Copy the code

advantages

  • Support SpringMVC, SpringBoot, SpringCloud and other mainstream Java frameworks
  • Java code friendly
  • Interface description
  • It is active in China, mainly driven by the Spring community
  • More functions

disadvantages

Bad for cross-language support (knife4J integration can fix this)

The code needs to introduce dependency packages and configurations

Relative lack of documentation

Springfox3. X and Swagger3.X introduction

Swagger is introduced

Open source interface documentation auto-generation tools, built on the OpenAPI specification, allow developers to quickly design, build, document, and use rest apis

Release notes

Current versions include swagger2.0 and 3.0

Swagger2 stopped maintenance in 2017, now the latest version is Swagger3 (OpenApi3) released in 2017.

Swagger consists of the following three parts

  • SwaggerEditor: Browser-based editor that we can use to write our OpenAPI specification
  • SwaggerUi: It renders the OpenAPI specification we wrote as an interactive API document
  • SwaggerCodegen: It simplifies the build process by generating server stubs and client SDKS from any API defined by the OpenAPI (formerly known as Swagger) specification

SpringFox introduction

(Is an unofficial project maintained by the Spring community)

Swagger is an open source API Doc framework. Marty Pitt wrote a Swagger-SpringMvc based on Spring components to integrate Swagger into SpringMvc. Its predecessor is Swagger-SpringMvc. Methods in our Controller can be presented as documents

Address: github.com/springfox/s…

Release notes

  • SpringFox3.0.0 (reduces some configuration of Swagger2)
  • Spring5 Webflux support with fewer dependencies
  • Support OpenApi 3.0.3
  • An integrated starter with SpringBoot is easier to use

Swagger3.0 SpringBoot2. X integration

Step1: pom adds dependencies

< the dependency > < groupId > IO. Springfox < / groupId > < artifactId > springfox - the boot - starter < / artifactId > < version > 3.0.0 < / version > </dependency>Copy the code

Step2: configure the file

#spring.application. Name =shop-managerp Or use the yML format spring.application.name=shop-manager # ===== to customize the swagger configuration ===== # swagger.enable=true Swagger. Application -name= ${spring.application. Name} # Swagger. Application-description =1024shop API infoCopy the code

Step3: configure the class

@component //Spring scan @enableopenapi // EnableOpenApi specification @configurationproperties ("swagger")// configure prefix @data public class SwaggerConfiguration {/** * Enable swagger */ private Boolean enable; /** * private String applicationName; /** * Project version information */ private String applicationVersion; /** * Private String applicationDescription; @bean public Docket Docket() {return new Docket(documentationType.oas_30). PathMapping ("/") It can be controlled by variables, API Info(apiInfo()) // Selects which interfaces to publish for Swagger. Select () //apis() controls which interfaces are exposed to Swagger. / / RequestHandlerSelectors. Any () all exposed / / RequestHandlerSelectors basePackage (" com. Keep. * ") specified package / / position The withMethodAnnotation(apiOperation.class) tag has this annotation ApiOperation .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title(applicationName) .description(applicationDescription) .contact(new Contact(" author ", "website "," mailbox ")).version(applicationVersion).build(); }}Copy the code

🦂 note

http://localhost: port/swagger – UI/index. The HTML

If the access fails, check whether an interceptor blocks related resource configurations

Swagger3.X Common annotations and configurations

@Api

Module configuration, used in the Controller class, describes the Api interface

@api (tags = "userModule ",value =" UserController") public class UserController {}Copy the code

@ApiOperation

Interface configuration, used in methods, describes interface methods

@apiOperation (" pagepath ") @getMapping ("list") public JsonData list(){return jsonData.buildSuccess (); }Copy the code

@ApiParam

Method parameter configuration, used in input arguments or annotations

@apiOperation (" user login") @getMapping ("login") public JsonData login(@apiparam (name = "phone", Value = "phone number ",example = "13888888888") @requestParam ("phone") String phone, @apiparam (name = "PWD ", Value = "password ",example = "123456") @requestParam (" PWD ")String PWD){return jsondata.buildSuccess (); }Copy the code

or

@requestMapping (value = "/test",method = requestmethod.get) @apiOperation (value = "ApiImplicitParams ") @apiImplicitParams ({ @apiIMPLICITParam (name = "name1",value = "name1", defaultValue = "null string ", Required = true,paramType = "query"), @APIIMPLICITParam (name = "name2",value = "name2", defaultValue = "null String ", Required = true,paramType = "query")}) public String @APIIMPLICITParam (name = "name2",value = "name2", defaultValue =" null String ", Required = true,paramType = "query") Test (String name1,String name2) {//language=JSON String aa = "{\n "name": "",\n "age": 21\n}"; return name1+name2; }Copy the code

@Apilgnore

Ignore that this interface does not generate documentation

@apiignore @apiOperation (" delete user ") @deletemapping ("/delete/{id}") public JsonData deleteById(@pathVariable int id) { return JsonData.buildSuccess(); }Copy the code

Swagger3.X object annotation ApiModel explanation

@ApiModel

Used for class representation to describe the class, used for parameters received by the entity class, value- for object name, description- description

This is typically used for post creation, using objects to submit scenarios like this

@ApiModelProperty

For methods, fields; Identifies specification or data manipulation changes to Model properties

Value: indicates the field description

Name: Override attribute name

DateType: Override attribute type

Required: Indicates whether the field is mandatory

It’s an example

Hidden hidden:

🌰

@API (tags = "user module ",value =" user Controller") @restController @RequestMapping(" Api /v1/user") @slf4j public class UserController {@apiOperation (" new user ") @requestMapping (value = "/saveUser",method = requestMethod. POST) //public JsonData saveUser(@requestBody UserParam UserParam){public JsonData saveUser(UserParam UserParam){// Used for form requests Log.info (" usercontroller.saveuser new userParam :{}",userParam); Return jsonData.builderror (" Added successfully "); }}Copy the code
@data Public class UserParam {@apiModelProperty (value = "ApiModelProperty ") private int ID; @APIModelProperty (value = "email ", Required = true,example = "[email protected]") private String email; @APIModelProperty (value = "phone number ", Required = false) private String phone; @APIModelProperty (value = "userName ") private String name; }Copy the code

Swagger3.X Response result ApiResponse

@ApiResponse

Describe the interface response

🌰 Note to guide Swagger3 package to have the following properties

@apiImplICITParams ({@apiIMPLICITParam (name = "id",value = "primary key ID ",defaultValue = "Null string ",required = true,paramType = "query")}) @apiresponses ({@apiResponse (responseCode = "401",description =" Please authenticate "), @apiResponse (responseCode = "403",description = "not found "), @apiResponse (responseCode = "404",description =" not found "), @requestMapping (value = "/getBannerById",method = "responseCode ") @requestMapping (value = "/getBannerById",method =" responseCode" RequestMethod.GET) public JsonData getBannerById(@RequestParam Long id){ try { BannerDO bannerDO = bannerService.getBannerById(id); return JsonData.buildSuccess(bannerDO); }catch (Exception e){ log.error("BannerController.getBannerById Exception -> error:{}, param:{}",e,id); } return jsondata. buildError(" query failed ",-1); }Copy the code

It’s not easy to get a thumbs up from someone who feels good