1 Working principle
There are more and more projects that are separated by the spring boot development front and back end, and the front and back ends are often the responsibility of different developers or teams. If the backend developed some rest interfaces, how can these interfaces be quickly and accurately described to front-end developers?
Swagger provides a technical implementation of automatic scan generation API interface documentation
2 Integration steps
The first step is to add Maven dependencies as follows:
<Dependency> <groupId>Io.springfox</groupId> <Artifactid>Springfox-swagger2</Artifactid> <version>2.7.0</version></Dependency><Dependency> <groupId>Io.springfox</groupId> <Artifactid>Springfox-swagger-ui</Artifactid> <version>2.7.0</version></Dependency>
The second step is to write the configuration class;
@Configuration @enableswagger2 Public classSwaggerconfig {@Bean PublicDocket Createrestapi () {return NewDocket (documentationtype.swagger_2). Apiinfo (Apiinfo ()). Select (). APIs ( Requesthandlerselectors.basepackage ("Com.example.demo.controller"). Paths (Pathselectors.any ()). build (); } Privateapiinfo Apiinfo () {return NewApiinfobuilder (). Title ("API Documentation"). Description (""). Termsofserviceurl (""). Version ("1.0"). build (); }}
In the third step, write the test controller:
@Api (description = "Test")
@RestController @requestmapping ("/demo")publicclass Democontroller { = "/user", method = requestmethod.get) public Object getusers (@ApiParam (value = "Name") @RequestParam (required = false) String name
New
List.add (name
Return
}
Launch the app and access http://localhost:8080/swagger-ui.html
3 API annotations
Swagger also provides some @ annotations for a detailed description of the API interface.
@Api: Modifies the entire class to describe the role of the controller.
@ApiOperation: Describes a method of a class, or an interface.
@ApiParam: A single parameter description.
@ApiModel: Use objects to receive parameters.
@ApiProperty: Describes a field of an object when it receives a parameter with an object.
@ApiResponse: A description of the HTTP response.
@ApiResponses: HTTP response overall description.
@ApiIgnore: Use this annotation to ignore this API.
@ApiError: The information returned by the error occurred.
@ApiParamImplicit: a request parameter.
@ApiParamsImplicit: Multiple request parameters.
4 Security issues
This open API document is generally used only in the development environment, and there are some security issues in the production environment. You can control this by adding @profile ({"Dev"}) annotations on the swagger configuration class so that swagger will only take effect under the dev profile.
Swagger Rest API Description