swaggerui+springmvc--building a visual interface for RESTful APIs

Source: Internet
Author: User
Tags return tag

Today we are going to introduce a tool that currently has the foreseeable benefit of automatically maintaining the latest interface documentation.
As we all know, the interface document is very important, but as the code continues to update, the document is difficult to continue to follow the update, today to introduce the tool, the perfect solution to this problem. And, for those who want to use our interface, there is no need to give him a document, tell him the address, at a glance.recently the project has been dealing with the interface, and just came into contact with a new interface tool, take it out to share with you. As for the rest interface, I've already covered it in my previous article, and here's how to build a visual interface for RESTful APIs with Swaggerui. The end result is this:It can support all forms of rest submission, such as Post,get,put,delete. hereYou can see our method annotations, the parameters required, the type of parameters and comments, the type of the return value of comments, etc., most importantly, we can test the rest interface directly.Next, let's start with the incremental effectFirst step: first, introduce a dependent jar package
<span style= "White-space:pre" ></span><!--swagger-->< dependency><groupid>com.mangofactory</groupid><artifactid>swagger-springmvc</ Artifactid><version>0.9.5</version></dependency><dependency> <groupId>com.fast Erxml.jackson.core</groupid> <artifactId>jackson-annotations</artifactId> <vers Ion>2.4.4</version> </dependency> <dependency> <groupid>com.fasterxml. Jackson.core</groupid> <artifactId>jackson-databind</artifactId> <version>2. 4.4</version> </dependency> <dependency> <groupid>com.fasterxml.jackson.c Ore</groupid> <artifactId>jackson-core</artifactId> <version>2.4.4</versi On> </dependency> 
The second step, create the Swagger configuration file class, basically do not change, only need to modify the method path to match.
package Com.gochina.mis.util;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.Bean; Import Org.springframework.context.annotation.componentscan;import Org.springframework.context.annotation.configuration;import Com.mangofactory.swagger.configuration.springswaggerconfig;import Com.mangofactory.swagger.models.dto.ApiInfo; Import Com.mangofactory.swagger.plugin.enableswagger;import Com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; @Configuration @enableswaggerpublic class Swaggerconfig { Private Springswaggerconfig springswaggerconfig; @Autowiredpublic void Setspringswaggerconfig (springswaggerconfig Springswaggerconfig) {this.springswaggerconfig = Springswaggerconfig;} @Bean public Swaggerspringmvcplugin customimplementation () {
        return new Swaggerspringmvcplugin (This.springswaggerconfig). Apiinfo (Apiinfo ()). IncludePatterns ("/album/*");// Here is the support of regular matching, only configured here can be seen on the page.    }private apiinfo apiinfo () {apiinfo apiinfo = new Apiinfo (null,null,null,null,null,null); return apiinfo;}}
Step Three:Adding a configuration file class to the spring container
<span style= "White-space:pre" ></span><!--swagger--><bean class= " Com.gochina.mis.util.SwaggerConfig "/>
here, our backstage environment code is finished, and then add the JS interface provided by Swaggerui Download Swagger-ui
Https://github.com/swagger-api/swagger-ui
Put the files under the dist into the WebApp
Configure Mvc:resource to prevent spring interception.
<span style= "White-space:pre" ></span><mvc:resources mapping= "/api-doc/**" location= "/api-doc/"/ >
The index.html in the Http://petstore.swagger.wordnik.com/v2/swagger.json Modify to Http://localhost:8080/{projectname}/api-docs
here, all the basic configurations are completed, and next, you need to annotate each interface. Here's an example. Interface class
Package Com.gochina.mis.api;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.beans.beanutils;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.modelattribute;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.responsebody;import Com.gochina.mis.bean.album;import Com.gochina.mis.bean.resultpo;import Com.gochina.mis.service.albumservice;import Com.gochina.mis.util.JsonUtil; Import Com.gochina.mis.util.stringutil;import Com.gochina.mis.vo.basevo;import com.gochina.mis.vo.RequestAlbumVo; Import Com.wordnik.swagger.annotations.api;import com.wordnik.swagger.annotations.ApiOperation; @Controllerpublic Class Albumaction {private static Logger Logger = Loggerfactory.getlogger (albumaction.class); @Autowiredprivate Albumservice Albumservice; @ReSponsebody@requestmapping (value= "album", method = Requestmethod.post,produces = "Application/json;charset=utf-8") @ Apioperation (value= "third Party Add album", HttpMethod = "POST", response=basevo.class, notes = "Third Party Add album") public String Postalbum (@ Modelattribute ("Requestalbumvo") Requestalbumvo requestalbumvo) {Basevo result = new Basevo (); Album Album = new Album (), if (requestalbumvo!=null) {logger.info ("Incoming parameter: requestalbumvo:{}", Jsonutil.beantojson ( REQUESTALBUMVO)); try {beanutils.copyproperties (REQUESTALBUMVO, album); Result=albumservice.save (album);} catch ( Exception e) {e.printstacktrace (); result.setsuccess (false); Result.setmsg ("Add album failed! Logger.error ("Add album failed incoming parameter: requestalbumvo:{}, error message: {}", Jsonutil.beantojson (REQUESTALBUMVO), E.getmessage ());}} else {result.setsuccess (false); Result.setmsg ("argument is illegal! ");} Logger.info ("Incoming parameter: requestalbumvo:{}, return result: {}", Jsonutil.beantojson (REQUESTALBUMVO), Jsonutil.beantojson (Result)) ; return Jsonutil.beantojson (Result);}}
As we can see, the SPRINGMVC is used here, the request parameter is passed to the entity class, and the annotation for the incoming parameter is placed in the entity request parameter Entity
Package Com.gochina.mis.vo;import Com.wordnik.swagger.annotations.apimodelproperty;public class RequestAlbumVo {@ Apimodelproperty (value = "album name", required = true) private String name; @ApiModelProperty (value = "Third-party album ID", required = True) Private string thirdalbumid;//third party album Id@apimodelproperty (value = "Third party album ID", required = True) private string Thirdsystemid ;//third-party system id@apimodelproperty (value = "Standard figure", required = false) Private String standardpic;//standard figure @apimodelproperty (value = " Vertical graph ", required = False) private string ystandardpic;//vertical graph @apimodelproperty (value =" watermark Picture ", required = false) private string markpic;//watermark Picture @apimodelproperty (value = "watermark Picture position", required = false) Private String markposition;// Watermark Picture Location @apimodelproperty (value = "Label", required = false) Private String tag;//label @apimodelproperty (value = "Score", required = f alse) private string score;//rating @apimodelproperty (value = "description", required = False) private string description;//description public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getthirdalbumid () {return thirdalbumid;} public void Setthirdalbumid (String thirdalbumid) {this.thirdalbumid = Thirdalbumid;} Public String Getthirdsystemid () {return thirdsystemid;} public void Setthirdsystemid (String thirdsystemid) {this.thirdsystemid = Thirdsystemid;} Public String Getstandardpic () {return standardpic;} public void Setstandardpic (String standardpic) {this.standardpic = Standardpic;} Public String Getystandardpic () {return ystandardpic;} public void Setystandardpic (String ystandardpic) {this.ystandardpic = Ystandardpic;} Public String Getmarkpic () {return markpic;} public void Setmarkpic (String markpic) {this.markpic = Markpic;} Public String getmarkposition () {return markposition;} public void Setmarkposition (String markposition) {this.markposition = markposition;} Public String Gettag () {return tag;} public void Settag (String tag) {This.tag = tag;} Public String Getscore () {return score;} public void SetScore (String score) {This.score = score;} Public StRing GetDescription () {return description;} public void SetDescription (String description) {this.description = description;}}
Returns the parameter, which is also used by the entity
Package Com.gochina.mis.vo;import Java.sql.timestamp;import com.wordnik.swagger.annotations.apimodelproperty;/** *  return information * @author LBQ-PC * */public class Basevo {/** * status */@ApiModelProperty (value = "state") Private Boolean success;/** * message */@ApiModelProperty (value = "message") Private String msg;/** * Server Current time */@ApiModelProperty (value = "Server current timestamp, sample:14345538 ") Private Long currenttime = new Timestamp (System.currenttimemillis ()). GetTime ();p ublic Boolean getsuccess () {return Success;} public void Setsuccess (Boolean success) {this.success = success;} Public String getmsg () {return msg;} public void setmsg (String message) {this.msg = message;} Public Long GetCurrentTime () {return currenttime;} public void Setcurrenttime (Long currenttime) {this.currenttime = CurrentTime;}}
Run Access: http://localhost:8080/api-doc/index.html, of course, we can also add permission validation to this page
It's done ! For developers, each interface only needs to add some annotations, and Swaggerui automatically generates pages that are presented at the beginning of our article for easy invocation and testing.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

swaggerui+springmvc--building a visual interface for RESTful APIs

Related Article

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.