Springboot How to use the swagger gracefully

Source: Internet
Author: User
Tags html page json

You can refer to my GitHub project Kingboy-springboot-web, which contains detailed demos and instructions, as well as other related technologies. First, why does the swagger appear.

In the past, the process of our project development was often the case:

Products to the front and back of the staff called to meet: our needs are such, Balabala. Then the front end takes the prototype page to start drawing the foreground UI, and the backend looks at the requirement document to start writing the interface.

After writing an interface on the back end, it is necessary to test the writing is correct, then there are often such a process:

-Open a simulated HTTP request tool such as Postman
-fill in the request address of the interface
-if it is a post with the body request, but also splicing a long string of JSON string, even if the wrong one character is not
-Request background interface

When the current background development is complete, the front and back end two people start to tune, often the following scenario appears:

Dialogue one:

-Front End: What do you call the phone field name? My name PhoneNumber
-back end:??!!
-Front End: No, you change it.

Dialogue two:

-Front End: You can't get through this interface.
-back end: Well, let me see ... 2 minutes later ..... I forgot to update the interface document, the interface format has been changed, so not adjustable
-front: ...

Dialogue three:

-Front end: Is your ID in this interface passed the user ID or the order ID?
-Back end: Wait a while, I'll take a look ... 2 minutes later
........ ..... -Back-end: And so on, my code notes forgot to sync the changes, I check the database ...

The above scenarios often occur, the reason is because the front and back end can not be very good synchronization information, both delay time, and consumption of energy, and we focus on the core should be code.

Before the joint, the developer also writes the interface document (something that hurts), and when the code changes, it is common to modify the interface document (however ...).

So is there a tool that can help us do these things? Could we just focus on our code writing? There must be, that's swagger. second, the swagger solved what problem.

Swagger will automatically generate an HTML page based on our interface, where we can see all the interface information, the information contains the parameters, what each parameter means, if it is a request with the body, it will automatically help us to generate JSON format of the bogy. You can also make interface requests like the HTTP request tool, as shown below.

Interface code:

    @ApiOperation (value = "Update User", notes = "Update user, ID must pass")
    @PutMapping public
    apiresult UpdateUser (@RequestBody Userdto userdto) {
        return apiresult.success ("Success");
    }

    @DeleteMapping ("/{id}") Public
    Apiresult Removeuser (@ApiParam (value = "User ID") @PathVariable (value = "id  ") Integer ID,
                                @ApiParam (value = "User name") @RequestParam String username) {
        return apiresult.success ("Success");
    }

Generated HTML page


Three, Springboot integrated swagger environment Preparation

1. Introduction of dependency

Spring MVC
' org.springframework.boot:spring-boot-starter-web ',
"Com.fasterxml.jackson.datatype: Jackson-datatype-jsr310 ",
//swagger
" Io.springfox:springfox-swagger2: $swaggerVersion ",
" Io.springfox:springfox-swagger-ui: $swaggerVersion ",

2.Swagger Configuration
Let's write a swagger configuration class as follows:

/** * @author kingboy--KingBoyWorld@163.com * @date 2017/12/30 PM * @desc swagger Configuration class. */@EnableSwagger2//swagger switch means we enable swagger @Configuration//reputation in the project this is a configuration class @ConfigurationProperties (prefix = " Swagger ") is automatically assigned to the property provided in the//springboot. You can also use the @value ("${swagger. Property name}") directly on the property to assign the public class Swaggerconfiguration {//controller Interface's package private String BAS

    Epackage = "Com.kingboy.controller";

    Title of the current document private String title = "He is very lazy, nothing left";

    Detailed description of the current document private String Description = "He is very lazy, nothing left";

    The version of the current document is private String Version = "V1.0"; @Bean Public Docket Createrestapi () {return new docket (documentationtype.swagger_2). Apiinfo (
                Apiinfo ()). Select (). APIs (Requesthandlerselectors.basepackage (Basepackage))
    . Paths (Pathselectors.any ()). build (); } private Apiinfo Apiinfo () {return new Apiinfobuilder (). title. deScription (description). version (Version). build (); }//setter Getter ...}

3. Configuration files, which are configured using the Yml file
Resources/application.yml

Swagger:
  basePackage:com.kingboy.controller
  title: User Service
  Description: User basic additions and deletions
  version:v1.0
Iv. How to use swagger

There are many annotations to the use of swagger, here we only talk about the most common annotations, and the most commonly used attributes in these annotations. @Api (value = "User Controller")
Add to the Controller class value represents the description of the class However, I found that there was no representation on the swagger page, so I did not add @ApiOperation (value = "Get user Information", notes = "Get user by id")
Added to the corresponding request processing method, value indicates that the description of the method is equivalent to a detailed description of the method, that is, a more complete description @ApiParam (value = "User ID")
The value on the normal parameter of the request method is a description of the parameter to note that @RequestParam annotations cannot be omitted, otherwise swagger will be parsed as body. @ApiModel (value = "User Information")
On the class of the request object to which the request method is added, for example, there is a request method Saveuser (user user), which needs to be added to the user class (which can be referenced in the following example) @ApiModelProperty (value = "User id", example = "1")
Added to the property on the parameter object of the request method, value Describes the property example represents the default value of the automatically generated JSON in the Swagger document @ApiImplicitParams (value = {})
This annotation must be used with the following @apiimplicitparam in the request method when there are many request parameters in the request method, such as Saveuser (String username, Integer age, Date birthday, String phone), this time if we still use @apiparam will make the method body becomes very chaotic. @ApiImplicitParam (name = "id", Paramtype = "path", value = "User ID")
The name of the property in the name parameter in @apiimplicitparams value paramtype This parameter must be specified, which represents the transport type of the parameter, with five values: path (url parameter), query (request parameter), body (Request body parameter), Header (header parameter), form (form parameter). Value to this attribute description again this emphasis, paramtype not less, paramtype not less, paramtype not less

Here's a look at the example:

Usercontroller

/** * @author kingboy--KingBoyWorld@163.com * @date 2017/11/26 PM 1:20 * @desc user Interface service. */@RestController @RequestMapping (value = "/user") public class Usercontroller {@ApiOperation (value = "Get user information", not ES = "Get user by id") @GetMapping (value = "/{id}") @ApiImplicitParams (value = {@ApiImplicitParam (name = "I D ", Paramtype =" path ", value =" User ID "), @ApiImplicitParam (name =" Username ", Paramtype =" Query ", value =" User Name ")}) public Apiresult GetUser (@PathVariable (value =" id ") Integer ID, @RequestParam String username) {R
    Eturn apiresult.success (new Userdto (ID, username, localdatetime.now ()));  } @ApiOperation (value = "Save User", notes = "Save user, ID for background auto generate") @PostMapping public apiresult Saveuser (@RequestBody
    Userdto userdto) {return apiresult.success (userdto); } @ApiOperation (value = "Update User", notes = "Update user, ID must pass") @PutMapping public apiresult updateUser (@RequestBody use Rdto userdto) {return ApiResult.success ("Success"); } @DeleteMapping ("/{id}") Public Apiresult Removeuser (@ApiParam (value = "User ID") @PathVariable (value = "id") Inte GER ID, @ApiParam (value = "User name") @RequestParam String username) {return apiresult
    . Success ("Success"); }

}

Userdto

@Data
@ApiModel (value = "User Information")
@NoArgsConstructor
@AllArgsConstructor public
class Userdto {

    @ Apimodelproperty (value = "User id", example = "1")
    private Integer ID;

    @ApiModelProperty (value = "User Name", example = "King")
    private String username;

    @ApiModelProperty (value = "Birthday", example = "1999-12-31 12:59")
    @JsonFormat (pattern = "Yyyy-mm-dd hh:mm")
    Private LocalDateTime birthday;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.