当前位置:网站首页>Swagger and OpenAPI

Swagger and OpenAPI

2022-07-04 10:54:00 Eric%258436

** If there is a mistake , Thank you for correcting **

If there is a mistake , Thank you for correcting , Please send a private message to the blogger , There is a red envelope for hard work , Worship “ one-word teacher ”.

Please find the paragraphs you need according to the table of contents

Introduction : This blog is organized for individuals Java Learning notes , If there is a mistake , Thank you for correcting . System learning , Welcome to continue to pay attention , Follow up updates ~
Java communication qq Group 383245788. There are some resources and leaders in the group , Welcome to exchange .

This article aims to learn and communicate , personal Swagger The learning

Full text reference :OpenAPI----GitHub

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#oasDocument

Why study Swagger

Interface documentation is important for both front and back-end developers . Especially in recent years, after the separation of front and back ends, the interface document has become the top priority . Interface documentation is important , However, due to the project cycle and other reasons, back-end personnel often fail to update in time , The front-end personnel complain that the interface document is inconsistent with the actual situation .
Many people will complain that the interface documents written by others are not standardized , Not updated in time . At that time, I was really tired of writing interface documents when I wrote it myself . This pain can only be remembered through personal experience .
If the interface document can be generated dynamically in real time, the above problem will not occur .
Swagger It can perfectly solve the above problems .

Open API

Open API standard (OpenAPI Specification) Formerly called Swagger standard , yes REST-API Of API Description format .
Open API The file allows to describe the whole API, Include :

  • The type of each access address .POST or GET.
  • Parameters of each operation . Including input and output parameters .
  • Certification method .
  • Connection information , Statement , Use team and other information .
    Open API Specifications can use YAML or JSON Format . This is better for us to read with machines .
    OpenAPI standard (OAS) by RESTful API A language independent standard interface is defined , Allow people and computers to discover and understand the functions of services , Without access to the source code , Document or network traffic check . When properly defined , Consumers can use a minimal amount of implementation logic to understand and interact with remote services .
    then , Document generation tools can use OpenAPI Define to show API, Use various programming languages to generate code generation tools for server and client , Test tools and many other use cases .

Swagger brief introduction

Swagger It's a set around Open API Open source tools for specification building , Can help design , structure , Record and use REST API.
Swagger The tool includes components :

  • Swagger Editor : Browser based editor , You can write Open API standard . similar Markdown It has the function of previewing the description file in real time .
  • Swagger UI: take Open API The specification is rendered interactive API file . Use visualization UI Show description file .
  • Swagger Codegen: take OpenAPI The specification is generated into server stub and client library . adopt Swagger Codegen The description file can be generated into html Format and cwiki Form of interface documentation , At the same time, it can also generate client and server code in multiple languages .
  • Swagger Inspector: and Swagger UI It's kind of similar , But you can return more information , The requested actual parameter data will also be saved .
  • Swagger Hub: Integrating all the functions of the above projects , You can do it in terms of project and version , Upload your description file to Swagger Hub in . stay SwaggerHub Can complete all the work of the above project in , You need to register an account , It's divided into free version and paid version .
  • Use Swagger, It is to store the relevant information in the description file defined by it (yml or json Format ), You can update the interface document by maintaining the description file , And generate the end codes

Springfox

Use Swagger If you encounter a version update or iteration , Just change Swagger The description file of . However, when frequently updating project versions, many developers think that even if the description file is modified (yml or json) It's also a certain workload , Over time, directly modify the code , Instead of modifying the description file , In this way, it is meaningless to generate interface documents based on description files .
Marty Pitt I wrote one based on Spring The components of swagger-springmvc.
Spring-fox It is a new project developed from this component .
Spring-fox Is to generate interface documents based on code , So update the project version normally , Modify the code , Without having to follow the modification of the description file .
Spring-fox Use yourself AOP characteristic , hold Swagger Integrate into , The bottom is still Swagger. But it's a lot easier to use .
So in the actual development , It's all direct use spring-fox.

reference : Official website and Official source code -GitHub

Swagger Ultimate usage

To write SpringBoot project

To write SpringBoot project , In the project controller Contains a Handler, Test project , Ensure that the program can run correctly .

@RestController
@RequestMapping("/people")
public class DemoController {
    
	@RequestMapping("/getPeople")
	public People getPeople(Long id, String name){
    
		People peo = new People();
		peo.setId(id);
		peo.setName(name);
		peo.setAddress(" Cao County ");
		return peo;
	}
}

Import Spring-fox rely on

In the project pom.xml Import Spring-fox rely on . The latest version is 2.9.2, Therefore, the imported dependency is also this version . among springfox-swagger2 Is the encapsulation of the core content .springfox-swagger-ui It's right swagger-ui Encapsulation .

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>latest</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>latest</version>
</dependency>

adding annotations

stay SpringBoot Add... To the startup class of @EnableSwagger2 annotation .
Adding this annotation means scanning all controllers in the current project . application Swagger2

@SpringBootApplication
@EnableSwagger2
public class MyApp {
    
	public static void main(String [] args){
    
		SpringApplication.run(MyApp.class,args);
	}
}

visit swagger-ui

After starting the project, enter... In the browser http://ip:port/swagger-ui.html You can access swagger-ui page , All interfaces in the project can be operated visually in the page .

Swagger-UI Use

visit swagger-ui.html After that, you can see the names of all controllers that need to generate interface documents in the page .
Each controller contains various access methods of all controller methods . If you are using @RequestMapping mapping , All request methods below will be displayed . If you use @PostMapping Will be only Post Way to access , The following only shows Post One of the .
Click in a request mode try it out, The value required by the interface will appear . Click... After input Execute Button
There will be Request URL Different status codes have been returned accordingly
More usage details , You can go to the official website to study the documents

Swagger To configure

You can create... In a project SwaggerConfig, Configure the document content .

  • Configure basic information

Docket: Summary objects , Through the information of the object configuration description file .
apiInfo: Set... In the description file info. Parameter type ApiInfo
select(): return ApiSelectorBuilder object , Call... By object build() You can create Docket object
ApiInfoBuilder:ApiInfo Builder .

@Configuration
public class SwaggerConfig {
    
	@Bean
	public Docket getDocket(){
    
				return new Docket(DocumentationType.SWAGGER_2)
									.apiInfo(swaggerDemoApiInfo())
									.select()
									.build();
		}
		private ApiInfo swaggerDemoApiInfo(){
    
				return new ApiInfoBuilder()
									.contact(new Contact("luofu", "http://www.bjsxt.com","[email protected]"))
									// Document title 
									.title(" Here is  Swagger  The title of the ")
									// A document description 
									.description(" Here is  Swagger  Description of ")
									// Document version 
									.version("1.0.0")
									.build();
	}
}
  • Set the scanned package

Can pass apis() Method to set which package content is scanned

@Bean
public Docket getDocket() {
    
	return new Docket(DocumentationType.SWAGGER_2)
						.apiInfo(getApiInfo())
						.select()
						.apis(RequestHandlerSelectors.basePackage("com.bjsxt.controller"))
						.build();
}
  • Custom annotation settings do not require the method of generating interface documents

Custom annotation

  • The annotation name is optional .
@Target({
    ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotIncludeSwagger {
    
}

Add rules
through too public ApiSelectorBuilder apis(Predicate<RequestHandler>selector) You can set generation rules .
public static <T> Predicate<T> not(Predicate<T> predicate) : Indicates an impermissible condition .
withMethodAnnotation: Indicates that this annotation is a method level annotation .

@Bean
public Docket getDocket(){
    
			return new Docket(DocumentationType.SWAGGER_2)
								.apiInfo(swaggerDemoApiInfo())
								.select()
								.paths(allowPaths())
								.apis(not(withMethodAnnotation(NotIncludeSwagger.class)))
								.build();
}

add to NotIncludeSwagger annotation
Add... To the methods that do not need to generate interface documents @NotIncludeSwagger After the note , This method will not be Swagger Generate in the interface document .

@NotIncludeSwagger
@RequestMapping("/getPeople2")
public People getPeople2(Integer id, String name, String address){
    
		People peo = new People();
		peo.setId(id);
		peo.setName(name);
		peo.setAddress(address);
		return peo;
}

set range
adopt public ApiSelectorBuilder paths(Predicate<String> selector) You can set what rules to meet url Generated interface document . You can use regular expressions to match .
The following example shows that only /demo/ At the beginning url Can be swagger Generate interface document .
How to hope that all scans can be used paths(PathSelectors.any())

@Bean
public Docket getDocket(){
    
		return new Docket(DocumentationType.SWAGGER_2)
							.apiInfo(swaggerDemoApiInfo())
							.select()
							.paths(allowPaths())
							.build();
}
private Predicate<String> allowPaths(){
    
		return or(
				regex("/demo/.*")
		);
}

Swagger2 Commonly used annotations

  1. Api

@Api It's a class annotation . Control the content of interface information generated by the whole class .

  • tags: The name of the class . There can be multiple values , Multiple values represent multiple copies .
  • description: describe , Deprecated .
@RestController
@RequestMapping("/people")
@Api(tags = {
    "mydemo"},description = " describe ")
public class DemoController {
    
		\\ ***
}
  1. ApiOperation

@ApiOperation Write on the method , A general description of the method

  • value: Interface description
  • notes: Prompt information
@ApiOperation(value=" Interface description ",notes = " Interface prompt information ")
  1. ApiParam

@ApiParam Write in front of method parameters . It is used to describe the parameter or whether it is a required item .

  • name: Parameter name
  • value: Parameters to describe
  • required: Whether it is necessary
public People getPeople(Integer id, @ApiParam(value=" full name ",required = true) String name, String address)
  1. ApiModel

@ApiModel It's a class annotation , Main application Model, In other words, this annotation is usually written on entity classes .

  • value: name
  • description: describe
@ApiModel(value = " human beings ",description = " describe ")
public class People {
    
		\\ ***
}
  1. ApiModelProperty

@ApiModelProperty Can be used on methods or properties . Used to define the contents of this field when the object is used as a parameter .

  • value: describe
  • name: Override property name
  • required: Is it necessary
  • example: Sample content
  • hidden: Is it hidden .
@ApiModelProperty(value = " full name ",name = "name",required = true,example = " Zhang San ")
private String name;
  1. ApiIgnore

@ApiIgnore Used on methods or classes or parameters , Indicates that this method or class is ignored . And the custom annotations explained earlier @NotIncludeSwagger The effect is similar to . It's just that this annotation is Swagger Built in annotations , and @NotIncludeSwagger It's our custom annotation .

  1. ApiImplicitParam

@ApiImplicitParam Used in methods , Represents a separate request parameter , Overall function and @ApiParam similar .

  • name: Property name
  • value: describe
  • required: Is it necessary
  • paramType: Attribute types
  • dataType: data type
@PostMapping("/getPeople")
@ApiImplicitParam(name = "address",value = " Address ",required = true,paramType ="query",dataType = "string")
public People getPeople(Integer id, @ApiParam(value=" full name ",required = true) String name, String address){
    
		\\ ***
}

If you want to configure multiple parameters on the method , Use @ApiImplicitParams To configure . Examples are as follows :

@ApiImplicitParams(value={
    @ApiImplicitParam(name="id",value = " Number ",required = true),@ApiImplicitParam(name="name",value = " full name ",required = true)})

At the end of the article

Here's a message . Low starting point , Current net , It's dirty , It's normal !
Give us a brain teaser . We all know why Hou Yi only used three arrows to shoot the ninth day ?
Because he shot three times [ Manual doge]​!
You can see it here , If it helps you , Please also help me make some comments , Pay attention ~

原网站

版权声明
本文为[Eric%258436]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141413329060.html