Swagger simple tutorial
HuskySir 2021-06-14 03:05:48

One 、 What is? swagger

Swagger Is a specification and complete framework , Used to generate 、 describe 、 Invocation and visualization RESTful Style Web service . The overall goal is to have the client and file system update at the same speed as the server . Method of file , Parameters and models are tightly integrated into server-side code , allow API To stay in sync at all times .Swagger Let deployment management and use powerful API It's very simple .

Simply speaking , It is a method that the back end provides to the front end to view various interfaces 、 Type, etc .

Two 、 To configure swagger

1、pom.xml

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

2、Swagger2Config class

stay src/main/java/com/example/demo/config New under the directory Swagger2Config class

1 /**
2  * Swagger2Configuration Configuration class
3 */
4 @Configuration
5 @EnableSwagger2
6 public class Swagger2Config {
7 }

3、Docket Method

Source code

 1 this.apiInfo = ApiInfo.DEFAULT; // Used for definition api Document summary information 
 2 this.groupName = "default";
 3 this.enabled = true;
 4 this.genericsNamingStrategy = new DefaultGenericTypeNamingStrategy();
 5 this.applyDefaultResponseMessages = true;
 6 this.host = "";
 7 this.pathMapping = Optional.absent();
 8 this.apiSelector = ApiSelector.DEFAULT;
 9 this.enableUrlTemplating = false;
10 this.vendorExtensions = Lists.newArrayList();
11 this.documentationType = documentationType;

call

 1 @Bean
 2 public Docket createApi(){
 3 return new Docket(DocumentationType.SWAGGER_2)
 4  .apiInfo(apiInfo())
 5 // Configure grouping 
 6 .groupName("user")
 7 // Configure whether to start 
 8  .enable(ture)
 9  .select()
10 /**
11  RequestHandlerSelectors: Configure how to scan the interface
12  basePackage: Specify packages to scan
13  any(): Scan all
14  none(): Don't scan
15  withClassAnnotation: Scan annotations on classes
16  withMethodAnnotation: Notes on scanning methods
17  **/
18 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
19 //path(): Filtered path
20 //.path(PathSelectors.ant("/xxx/*"))
21  .build();
22 }

4、ApiInfo Method

Source code

 1 public static final Contact DEFAULT_CONTACT = new Contact("", "", "");
 2 public static final ApiInfo DEFAULT;
 3 private final String version; // Document version number 
 4 private final String title; // Document page title 
 5 private final String description; // Details 
 6 private final String termsOfServiceUrl; // Web site address 
 7 private final String license;
 8 private final String licenseUrl;
 9 private final Contact contact; // Contact information 
10 private final List<VendorExtension> vendorExtensions;

call

1 private ApiInfo apiInfo(){
2 return new ApiInfoBuilder()
3 .title("Swagger2")
4 .description("RestFul API Interface ")
5 .version("1.0")
6  .build();
7 }

5、 Page effects

http://localhost:8080/swagger-ui.html

 groupName It can be grouped to differentiate back-end developers , If there are multiple back-end developers , Can be in Swagger2Config Class Docket Object and then through @Bean Inject , Different Docket Objects represent different groups

 1 @Bean
 2 public Docket createApi1(){
 3 return new Docket(DocumentationType.SWAGGER_2)
 4  .apiInfo(apiInfo())
 5 // Configure grouping 
 6 .groupName("user1") //user1 grouping
 7 // Configure whether to start 
 8  .enable(ture)
 9  .select()
10 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
11  .build();
12 }
13
14 @Bean
15 public Docket createApi2(){
16 return new Docket(DocumentationType.SWAGGER_2)
17  .apiInfo(apiInfo())
18 // Configure grouping 
19 .groupName("user2") //user2 grouping
20 // Configure whether to start 
21  .enable(ture)
22  .select()
23 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
24  .build();
25 }

3、 ... and 、Swagger Commonly used annotations

1、@ApiModel

Use scenarios : Use... On entity classes , When marking a class swagger The parsing class of

summary : Provide relevant swagger Other information about the model , Class will automatically introspect when used as a type in an operation

 1 String value() default "";
 2
 3 String description() default "";
 4
 5 Class<?> parent() default Void.class;
 6
 7 String discriminator() default "";
 8
 9 Class<?>[] subTypes() default {};
10
11 String reference() default "";
The attribute name data type The default value is explain
value String Class name Provide an alternate name for the model
description String "" Provide a detailed class description
parent Class<?> parent() Void.class Provide a parent class for the model to run to describe inheritance relationships
discriminator String "" Support model inheritance and polymorphism , Use the field name of the discriminator , You can assert which subtype you want to use
subTypes Class<?>[] {} Array of subtypes inherited from the model
reference String "" Specifies the reference to the corresponding type definition , Override any other metadata specified

Example

1 /**
2  * Student class Student entity
3 */
4 @ApiModel(value = "Student",description = " User entity class ")
5 public class Student implements Serializable {
6 }

2、@ApiModelProperty

Use scenarios : Used in being @ApiModel Annotated model class properties . Said to model Property description or data operation change

summary : Add and manipulate data for model properties

 1 String value() default "";
 2
 3 String name() default "";
 4
 5 String allowableValues() default "";
 6
 7 String access() default "";
 8
 9 String notes() default "";
10
11 String dataType() default "";
12
13 boolean required() default false;
14
15 int position() default 0;
16
17 boolean hidden() default false;
18
19 String example() default "";
20
21 /** @deprecated */
22 @Deprecated
23 boolean readOnly() default false;
24
25 ApiModelProperty.AccessMode accessMode() default ApiModelProperty.AccessMode.AUTO;
26
27 String reference() default "";
28
29 boolean allowEmptyValue() default false;
30
31 Extension[] extensions() default {@Extension(
32 properties = {@ExtensionProperty(
33 name = "",
34 value = ""
35  )}
36 )};
The attribute name data type The default value is explain
value String "" Property description
name String "" Override property name
allowableValues String "" Limit the value that a parameter can receive , Three methods , Fixed value , Fixed range
access String "" Filter properties
notes String "" Not yet in use
dataType String "" Data type of parameter , It can be a class name or raw data type , This value will override the data type read from the class property
required boolean false Whether it is a required parameter (false: Unnecessary parameters ;true: Must pass parameters )
position int "" Run to show sort properties in the model
hidden boolean false Hide model properties (false: Don't hide ;true: hide )
example String "" Sample values for properties
readOnly boolean false Specifies that the model property is read-only (false: Non read only ;true: read-only )
reference String "" Specifies the reference to the corresponding type definition , Override any other metadata specified
allowEmptyValue boolean false Run through null values (false: Null values are not allowed ;true: Run to pass null value )
extensions Extension[] {@Extension(properties={@ExtensionProperty(name = "",value = "")})}; Associated annotations

Example

 1 @ApiModelProperty(value = " Student number ")
 2 private Integer id; // Student number 
 3 @ApiModelProperty(value = " full name ")
 4 private String name; // full name 
 5 @ApiModelProperty(value = " achievement ")
 6 private Integer score; // achievement 
 7 @ApiModelProperty(value = " Native place ")
 8 private String birthplace; // Native place
 9 // The format of the date year - month - Japan 
10 @ApiModelProperty(value = " Birthday ")
11 @DateTimeFormat(pattern = "yyyy-MM-dd")
12 private Date birthday; // Birthday 

3、@ApiOperation

Use scenarios : Use it in a way , It means a http Requested operation

summary : Used to represent Controller Under class http Request method

 1 String value();
 2
 3 String notes() default "";
 4
 5 String[] tags() default {""};
 6
 7 Class<?> response() default Void.class;
 8
 9 String responseContainer() default "";
10
11 String responseReference() default "";
12
13 String httpMethod() default "";
14
15 /** @deprecated */
16 @Deprecated
17 int position() default 0;
18
19 String nickname() default "";
20
21 String produces() default "";
22
23 String consumes() default "";
24
25 String protocols() default "";
26
27 Authorization[] authorizations() default {@Authorization("")};
28
29 boolean hidden() default false;
30
31 ResponseHeader[] responseHeaders() default {@ResponseHeader(
32 name = "",
33 response = Void.class
34 )};
35
36 int code() default 200;
37
38 Extension[] extensions() default {@Extension(
39 properties = {@ExtensionProperty(
40 name = "",
41 value = ""
42  )}
43 )};
44
45 boolean ignoreJsonView() default false;
The attribute name data type The default value is explain
value String   Property description
notes String "" Remarks
tags String {""} Can be regrouped
response Class<?> response() Void.class An optional response class to describe the message payload , Corresponding to the response message object schema Field
responseContainer String "" The container that declares the response , Valid values are List,Set,Map, Any other values are ignored
responseReference String "" Declare a reference to the response
httpMethod String "" http Request mode
position int 0 Run to show sort properties in the model
nickname String "" nickname
produces String "" For example, "application/json, application/xml"
consumes String "" For example, "application/json, application/xml"
protocols String "" Possible values: http, https, ws, wss.
authorizations Authorization[] {@Authorization("")} Configure for advanced feature authentication
hidden boolean false Is it hidden
responseHeaders ResponseHeader[] {@ResponseHeader(name = "",response = Void.class)}; Possible responses header list
code int 200 http Status code
extensions Extension[] {@Extension(properties = {@ExtensionProperty(name = "",value = "")})}; Associated annotations
ignoreJsonView boolean false Whether to ignore json View

Example

1 @ApiOperation(" Add student information ")
2 @PostMapping(value = "/student")
3 public void AddStudent(Student student) {
4
5  studentService.AddStudent(student);
6 }

4、@ApiParam

Use scenarios : stay Rest Interface or Rest Interface parameters are used in front of

summary : by Rest Interface parameters add other metadata ( Import to yapi Will not be parsed in )

 1 String name() default "";
 2
 3 String value() default "";
 4
 5 String defaultValue() default "";
 6
 7 String allowableValues() default "";
 8
 9 boolean required() default false;
10
11 String access() default "";
12
13 boolean allowMultiple() default false;
14
15 boolean hidden() default false;
16
17 String example() default "";
18
19 Example examples() default @Example({@ExampleProperty(
20 mediaType = "",
21 value = ""
22 )});
23
24 String type() default "";
25
26 String format() default "";
27
28 boolean allowEmptyValue() default false;
29
30 boolean readOnly() default false;
31
32 String collectionFormat() default "";
The attribute name data type The default value is explain
name String "" Parameter name , The parameter name will be from filed/method/parameter Derived from the name , But you can cover it , Path parameters must always be named the part of the path they represent
value String "" Simple description of parameters
defaultValue String "" Describes the default value of the parameter
allowableValues String "" Limit the value of the parameter that can be received , There are three ways , Value list , Value range
required boolean false Whether it is a required parameter (false: Not necessarily ; true: Will pass )
access String "" Parameter filtering
allowMultiple boolean false Specifies whether a parameter can receive multiple values by multiple occurrences
hidden boolean false Hide parameters in parameter list
example String "" Nonrequest body (body) An example of a single parameter for a type
examples Example @Example({@ExampleProperty(mediaType = "",value = "")}); Parameter example , Only for requests of request body type
type String "" Add the ability to override detected types
format String "" Add provide custom format Format function
allowEmptyValue boolean false Add the ability to set the format to null
readOnly boolean false Add the ability to be specified as read-only
collectionFormat String "" Add and use array Type override collectionFormat The function of

Example

1 @ApiOperation(" Determine whether the verification code is correct ")
2 @RequestMapping(value = "/UpdatePassword" , method = RequestMethod.POST)
3 public CommonResult updatePassword(
4 @ApiParam(value = " Phone number ",required = true) @RequestParam String userPhone,
5 @ApiParam(value = " Verification Code ",required = true) @RequestParam String authCode){
6
7 return userMemberService.updatePassword(userPhone,authCode);
8 }

5、 Page effects

[email protected] And @ApiModelProperty effect

[email protected] effect

Four 、 export swagger Interface document

1、 Import module dependencies

pom.xml file

1 <!-- swagger2markup modular -->
2 <dependency>
3 <groupId>io.github.swagger2markup</groupId>
4 <artifactId>swagger2markup</artifactId>
5 <version>1.3.1</version>
6 </dependency>

2、 New test class

stay src/test/java/com/example/demo Create a new test class in the directory SwaggerTo

SwaggerTo

1 @RunWith(SpringRunner.class) // The test class uses the injected class 
2 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) // For unit testing 
3 public class SwaggerTo {
4 }

3、 New test method

generateMarkdownDocs()

 1 /**
 2  * Generate Markdown Format document
 3  * @throws Exception
 4 */
 5 @Test
 6 public void generateMarkdownDocs() throws Exception {
 7 // Output Markdown Format 
 8 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
 9 .withMarkupLanguage(MarkupLanguage.MARKDOWN) // Output format :ASCIIDOC,MARKDOWN,CONFLUENCE_MARKUP
10 .withOutputLanguage(Language.ZH) // Language type : chinese (ZH) Default English (EN)
11 .withPathsGroupedBy(GroupBy.TAGS) //Api Sort rule 
12  .withGeneratedExamples()
13  .withoutInlineSchema()
14  .build();
15
16 Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs?group=user")) //url, Note the port number and grouping 
17  .withConfig(config)
18  .build()
19 .toFolder(Paths.get("src/docs/markdown/generated")); // The storage path of the generated file , Generate multiple files 
20 }

At this time in src/docs/markdown/generated It will be generated in the directory definitions.md、overview.md、paths.md、security.md file , That is generated markdown file

generateMarkdownDocsToFile()

 1 /**
 2  * Generate Markdown Format document , And put it together into a file
 3  * @throws Exception
 4 */
 5 @Test
 6 public void generateMarkdownDocsToFile() throws Exception {
 7 // Output Markdown To single file 
 8 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
 9 .withMarkupLanguage(MarkupLanguage.MARKDOWN) // Output format :ASCIIDOC,MARKDOWN,CONFLUENCE_MARKUP
10 .withOutputLanguage(Language.ZH) // Language type : chinese (ZH) Default English (EN)
11 .withPathsGroupedBy(GroupBy.TAGS) //Api Sort rule 
12  .withGeneratedExamples()
13  .withoutInlineSchema()
14  .build();
15
16 Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs?group=user")) //url, Note the port number and grouping 
17  .withConfig(config)
18  .build()
19 .toFile(Paths.get("src/docs/markdown/generated/all")); // The storage path of the generated file , Aggregate into one file 
20 }

At this time in src/docs/markdown/generated It will be generated in the directory all.md file , That is generated markdown file

Be careful :

  • If in Swagger2Config Groups are declared in the class , namely Docket There are methods .groupName("user"), So in the test method url After the path, you need to add ?group=user. If Swagger2Config Group not declared in class , In the test method url The path does not need to be added ?group=user

  • When using test methods to generate files Need to close project , Otherwise, it will prompt Port occupied

  • You can modify Swagger2MarkupConfig.withMarkupLanguage() Method Generate different file formats , modify Swagger2MarkupConverter.toFile() Parameter values in methods Provide the corresponding generation file storage path

  • definitions.md Deposit Models Related information ,overview.md Store document overview information ,paths.md Deposit controller Related information ,security.md Store information related to identity authentication

4、 Export part of the document

all.md

 

Please bring the original link to reprint ,thank
Similar articles