Spring Boot uses Swagger2 to automatically generate RESTful API documentation _spring-boot

Source: Internet
Author: User
There are many kinds of API document automatic generation tools, such as:
Swagger Spring REST Docs RAML Apidocjs Springrestdoc This article evaluates and compares these popular API document generation tools: https://opencredo.com/ rest-api-tooling-review/

Swagger is one of the more recommended.


Characteristics of Swagger:
1. Configuration in spring boot is very simple
2, when the project deployment, automatically generate documents according to code, through the HTML display
3, after the code changes, the document will be automatically updated when the project is redeployed, without the need to manually update the document
4, to ensure that the code and document consistency, will not appear inconsistent with the situation
5, can directly in the document interface test interface, no longer use a third party to debug the interface

A few simple steps, you can configure Swagger2 in spring boot to automate the API document generation:
1, the introduction of dependence:

		<!--document Automatic generation-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactid >springfox-swagger2</artifactId>
			<version>2.6.1</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId> springfox-swagger-ui</artifactid>
			<version>2.6.1</version>
		</dependency>

2. Create Swagger2 Configuration class:
@Configuration
@EnableSwagger2 Public
class Swagger2 {
	@Bean public
	Docket Createrestapi () {
		Return  new Docket (documentationtype.swagger_2)
				. Apiinfo (Apiinfo ()).
				Select ()
				. APIs ( Requesthandlerselectors.withmethodannotation (Apioperation.class))
				. Paths (Pathselectors.any ())
				. Build ( );
	}


	Private Apiinfo Apiinfo () {return
		new Apiinfobuilder ()
				. Title ("topic page API Documentation")
				. Description ("topic page API Documentation")
				. Termsofserviceurl ("Http://terms-of-services.url")
				. Version ("1.0")
				. Build ();
	}

By @configuration annotations, let spring load the class configuration, and then enable Swagger2 by @enableswagger2 annotations.
APIs () You can specify that a method with an annotation needs to generate an API document, and you can specify which package to scan to generate the document, such as:
APIs (Requesthandlerselectors.basepackage ("Com.xjj.web.controller"))

3, in the Controller method annotation various document description:
@RestController @RequestMapping ("/topic/") public class Topiccontroller {protected final Logger Logger = loggerfactory.g

	Etlogger (This.getclass ());

	@Autowired Topicservice Topicservice; @RequestMapping (value= "Gettopic", method = Requestmethod.get) @ApiOperation (value= "interface description ...) ", response = Topicresult.class) @ApiImplicitParams ({@ApiImplicitParam (name =" SN ", value =" number ", required = True, Da  Tatype = "String", Paramtype = "Query"), @ApiImplicitParam (name = "token", value = "User Token", required = True, DataType  = "string", Paramtype = "Query"}) public Jsonresult gettopicbysn (httpservletrequest request, @RequestParam String sn,

		@RequestParam String token) {Jsonresult result = null;
			try {Topic Topic = topicservice.gettopic (SN);
			if (topic = = NULL) {result = new Jsonresult (returncode.params_error, "error");
			}else {result = new Jsonresult (returncode.success, "success", topic);
			}}catch (Exception e) {logger.error ("Gettopicbysn Exception", e); Result= new Jsonresult (returncode.exception);
	return result; }
}

Where response = Topicresult.class indicates that the return value uses the Jsonresult subclass Topicresult to show more detail; if not specified, the document is generated using the return value Jsonresult. These two classes also require corresponding annotations (@ApiModel and @apimodelproperty):
@ApiModel public
class Jsonresult {
	@ApiModelProperty (value = "Status Code", example= "40001", required = True, position= -2
	private String code;
	@ApiModelProperty (value = "return message", example= "Congratulations, success." ", required = True, Position=-1)
	private String message;
	@ApiModelProperty (value = "concrete data")
	private Object data;

	constructors, getters, setters slightly ...
}
@ApiModel public
class Topicresult extends Jsonresult {
	@ApiModelProperty (value = "topic details", required = True)
	private Topic data;

	constructors, getters, setters slightly ...
}

For the inside topic class, also need corresponding @apimodel and @apimodelproperty annotation (code slightly).


For parameter annotations in controller, you can also place them directly in the argument list, for example:
@RestController
@RequestMapping ("/apply/") public
class Applycontroller {
	protected final Logger Logger = Loggerfactory.getlogger (This.getclass ());

	@Autowired
	applyservice Applyservice;

	@RequestMapping (value= "Store-mgr-setup", method = Requestmethod.post)
	@ApiOperation (value= "Interface description")
	public Jsonresult Applystoremgrsetup (httpservletrequest request,
					@ApiParam (value = "parameter description", required = True) @RequestBody Dianapply dianapply) {
		Jsonresult result = null;
		Other code slightly ...

		return result;
	}

4, API document viewing and debugging
Once the project is started, you can access the URL to see the automatically generated API documentation: http://localhost:8080/<project-name>/swagger-ui.html

Test: After filling in the corresponding parameters, click "Try it Out" below. button, you can complete a request call.


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.