Springboot using Swagger2 to implement restful APIs

Source: Internet
Author: User

Many times, we need to create an interface project to use for data transfers, which do not contain any business logic, such as our company. At this point we need to implement an interface project with a restful API.

This article describes springboot using Swagger2 to implement restful APIs.

This project uses Mysql+jpa+swagger2.

First add the Swagger2 to the Pom, the code is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 Http://maven.apache . org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.dalaoyang</ Groupid> <artifactId>springboot_swagger2</artifactId> <version>0.0.1-snapshot</version > <packaging>jar</packaging> <name>springboot_swagger2</name> <description>sprin        Gboot_swagger2</description> <parent> <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!--lookup parent from repository to </parent> <properties> <p Roject.build.sourceencoding>utf-8</projecT.build.sourceencoding> <project.reporting.outputencoding>utf-8</project.reporting.outputencoding > <java.version>1.8</java.version> </properties> <dependencies> <depende Ncy> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starte r-data-jpa</artifactid> </dependency> <dependency> <groupid>org.springfra Mework.boot</groupid> <artifactId>spring-boot-starter-web</artifactId> </dependency > <dependency> <groupId>org.springframework.boot</groupId> <artifacti        D>spring-boot-devtools</artifactid> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactid>mysql-connector-java&lt ;/artifactid> &Lt;scope>runtime</scope> </dependency> <dependency> <groupid>org.spring Framework.boot</groupid> <artifactId>spring-boot-starter-test</artifactId> <sco pe>test</scope> </dependency> <dependency> <groupid>io.springfox</g Roupid> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version&        Gt </dependency> <dependency> <groupId>io.springfox</groupId> <artifa     Ctid>springfox-swagger-ui</artifactid> <version>2.2.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>            Org.springframework.boot</groupid> <artifactId>spring-boot-maven-plugin</artifactId> </pLugin> </plugins> </build></project> 

The next step is the configuration file, as well as the integration JPA. The code is as follows:

##端口号server.port=8888##数据库配置##数据库地址spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false##数据库用户名spring.datasource.username=root##数据库密码spring.datasource.password=root##数据库驱动spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Create a Swagger2 configuration class that simply explains @Configuration annotations Let spring load the configuration @EnableSwagger2 turn on Swagger2.

Package Com.dalaoyang.config;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.configuration;import Springfox.documentation.builders.ApiInfoBuilder; Import Springfox.documentation.builders.pathselectors;import Springfox.documentation.builders.requesthandlerselectors;import Springfox.documentation.service.apiinfo;import Springfox.documentation.spi.documentationtype;import Springfox.documentation.spring.web.plugins.docket;import springfox.documentation.swagger2.annotations.enableswagger2;/** * @author Dalaoyang * @Description * @project Springboot_learn * @package com.dalaoyang.config * @email [email protected] * @date 2018/4/9 */@ Configuration@enableswagger2public class Swagger2config {@Bean public Docket Createrestapi () {return new do Cket (documentationtype.swagger_2). Apiinfo (Apiinfo ()). Select (). APIs (Request              Handlerselectors.basepackage ("Com.dalaoyang.swagger"))  . Paths (Pathselectors.any ()). build ();                } private Apiinfo Apiinfo () {return new Apiinfobuilder (). Title ("Building restful APIs using Swagger2")                 . Description ("Follow Blogger blog: https://www.dalaoyang.cn/"). Termsofserviceurl ("https://www.dalaoyang.cn/")    . Contact ("Dalaoyang"). Version ("1.0"). Build (); }}

Create a user class as model

Package Com.dalaoyang.model;import Io.swagger.annotations.apimodel;import Io.swagger.annotations.ApiModelProperty ; Import Javax.persistence.column;import Javax.persistence.entity;import Javax.persistence.generatedvalue;import Javax.persistence.id;import javax.validation.constraints.notnull;/** * @author Dalaoyang * @Description * @project Springboot_learn * @package Com.dalaoyang.model * @email [email protected] * @date 2018/4/9 */@Entity @apimodel ( Description = "User") public class User {@ApiModelProperty (value = "PRIMARY key Id", Hidden = true) @GeneratedValue @Id I    NT ID;    @ApiModelProperty (value = "User name") @NotNull @Column String userName;    @ApiModelProperty (value = "User password") @Column String UserPassword;    public int getId () {return id;    } public void setId (int id) {this.id = ID;    } public String GetUserName () {return userName;    } public void Setusername (String userName) {this.username = UserName; } public String Getuserpassword () {return userpassword;    } public void SetUserPassword (String userpassword) {This.userpassword = UserPassword;        The public User (int ID, string userName, String userpassword) {this.id=id;        This.username = UserName;    This.userpassword = UserPassword;        The public User (string userName, String userpassword) {this.username = UserName;    This.userpassword = UserPassword; Public User () {}}

JPA Data Manipulation Class Userrepository

package com.dalaoyang.repository;import com.dalaoyang.model.User;import org.springframework.data.jpa.repository.JpaRepository;/** * @author dalaoyang * @Description * @project springboot_learn * @package com.dalaoyang.repository * @email [email protected] * @date 2018/4/9 */public interface UserRepository extends JpaRepository<User,Integer> {    User findById(int id);}

Then add the contents of the document, in fact, as with the controller, but the method and parameters interspersed with some annotations.

Package Com.dalaoyang.swagger;import Com.dalaoyang.model.user;import com.dalaoyang.repository.UserRepository; Import Io.swagger.annotations.*;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.web.bind.annotation.*;import java.util.list;/** * @author Dalaoyang * @Description * @project Springboot_learn * @package Com.dalaoyang.swagger * @email [email protected] * @date 2018/4/9 */@ Restcontroller@requestmapping (value= "/users") @Api (value= "User Interface", tags={"User Action Interface"}) public class Userswagger {@    Autowired userrepository userrepository; @ApiOperation (value= "Get user Details", notes= "get user details based on user ID") @ApiImplicitParam (name = "id", value = "User id", required = Tru  E,paramtype = "Query", DataType = "Integer") @GetMapping (value= "/findbyid") public User FindByID (@RequestParam (value        = "id") int id) {User user = Userrepository.findbyid (ID);    return user; } @ApiOperation (value= "Get user list", notes= "Get user list") @GetMapping (value= "/getuserliSt ") Public List getuserlist () {return userrepository.findall (); } @ApiOperation (value= "Save user", notes= "Save User") @PostMapping (value= "/saveuser") public String Saveuser (@RequestBody @        Apiparam (name= "User Object", value= "incoming JSON format", required=true) User user) {Userrepository.save (username);    return "success!"; } @ApiOperation (value= "Modify user", notes= "Modify user") @ApiImplicitParams ({@ApiImplicitParam (name= "id", value= "PRIMARY key ID") , required=true,paramtype= "Query", datatype= "Integer"), @ApiImplicitParam (name= "username", value= "user name", required=t Rue,paramtype= "Query", DataType = "String"), @ApiImplicitParam (name= "password", value= "User password", Required=true,paramt  Ype= "Query", DataType = "string")}) @GetMapping (value= "/updateuser") public String UpdateUser (@RequestParam (value = "id") int ID, @RequestParam (value = "username") String username, @RequestParam (value = "Passwo Rd ") String password) {User user = new user (ID, username, password);        Userrepository.save (user);    return "success!"; } @ApiOperation (value= "Delete user", notes= "Delete user based on user ID") @ApiImplicitParam (name = "id", value = "User id", required = True,p Aramtype = "Query", DataType = "Integer") @DeleteMapping (value= "/deleteuserbyid") public String Deleteuserbyid (@Requ        Estparam (value = "id") int id) {User user = Userrepository.findbyid (ID);        Userrepository.delete (user);    return "success!"; }}

Start the project, Access http://localhost:8888/swagger-ui.html, and you can see the

In order to facilitate everyone to learn to watch, I have used several different methods of writing,

1. Delete the user, the code is as follows

    @ApiOperation(value="删除用户", notes="根据用户的id来删除用户")    @ApiImplicitParam(name = "id", value = "用户ID", required = true,paramType = "query", dataType = "Integer")    @DeleteMapping(value="/deleteUserById")    public String deleteUserById(@RequestParam(value = "id")int id){        User user = userRepository.findById(id);        userRepository.delete(user);        return "success!";    }


2. Get User Details

 @ApiOperation(value="获取用户详细信息", notes="根据用户的id来获取用户详细信息")    @ApiImplicitParam(name = "id", value = "用户ID", required = true,paramType = "query", dataType = "Integer")    @GetMapping(value="/findById")    public User findById(@RequestParam(value = "id")int id){        User user = userRepository.findById(id);        return user;    }

3. Get a list of users

@ApiOperation(value="获取用户列表", notes="获取用户列表")    @GetMapping(value="/getUserList")    public List getUserList(){        return userRepository.findAll();    }

4. Save the user

@ApiOperation(value="保存用户", notes="保存用户")    @PostMapping(value="/saveUser")    public String saveUser(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){        userRepository.save(user);        return "success!";    }

5. Modify the user

   @ApiOperation(value="修改用户", notes="修改用户")    @ApiImplicitParams({            @ApiImplicitParam(name="id",value="主键id",required=true,paramType="query",dataType="Integer"),            @ApiImplicitParam(name="username",value="用户名称",required=true,paramType="query",dataType = "String"),            @ApiImplicitParam(name="password",value="用户密码",required=true,paramType="query",dataType = "String")    })    @PutMapping(value="/updateUser")    public String updateUser(@RequestParam(value = "id")int id,@RequestParam(value = "username")String username,                             @RequestParam(value = "password")String password){        User user = new User(id, username, password);        userRepository.save(user);        return "success!";    }

And then to share with you my previous study recorded in Youdao Cloud notes about the use of Swagger2, who is the original author, I can not remember. If the original author see, you can talk about me privately, I give your name add, sorry.

@Api: Used on the requested class to represent a description of the class tags= "describes the role of the class, the annotations that can be seen on the UI interface" value= "This parameter makes little sense and is seen on the UI interface, so there's no need to configure" Example: @Api (tags= " App user Registration Controller ") @ApiOperation: Used in the method of request, explain the purpose of the method, function value=" description method of Use, function "notes=" method of Note description "Example: @ApiOperation (value=" User Registration ", notes=" mobile phone number, password are must lose, age with the edge, but must be a number ") @ApiImplicitParams: Used on the requested method, represents a set of parameter description @        Apiimplicitparam: Used in @apiimplicitparams annotations, specify each aspect of a request parameter name: Parameter Name value: Chinese character description of parameter, interpretation required: whether the parameter must be passed Paramtype: Where to put the parameters · Header-to-Request parameter acquisition: @RequestHeader · Query-to-Request parameter acquisition: @RequestParam · Path (for restful interfaces)--GET request parameters: @PathVariable · Body (not used) ·     form (infrequently used) DataType: parameter type, default string, other value datatype= "Integer" DefaultValue: Example of default value for parameter: @ApiImplicitParams ({ @ApiImplicitParam (name= "mobile", value= "phone number", required=true,paramtype= "form"), @ApiImplicitParam (name= "Password", value= "Password", required=true,paramtype= "form"), @ApiImplicitParam (name= "age", value= "ages", required=true,paramtype= " Form ", DATAtype= "Integer")}) @ApiResponses: Used on the requested method, represents a set of response @ApiResponse: used in @apiresponses, generally used to express a wrong response information code: number, such as 400     Message: Information, such as "request parameter not filled in" Response: Class @apioperation (value = "Select1 Request", notes = "Multiple parameters, multiple query parameter types") that throws an exception @ApiResponses ({ @ApiResponse (code=400,message= "request parameter not filled out"), @ApiResponse (code=404,message= "Request path not or page jump path not")}) @ApiModel: For the response class, Represents a message that returns response data (this is typically used when post is created, using a scenario such as @requestbody, when the request parameter cannot be described using the @apiimplicitparam annotation) @ApiModel Property: An example of an attribute that describes a response class on a property: import Io.swagger.annotations.apimodel;import Io.swagger.annotations.ApiModelProperty; Import java.io.Serializable; @ApiModel (description= "return response data") public class Restmessage implements serializable{@    Apimodelproperty (value = "succeeded") private Boolean success=true;    @ApiModelProperty (value = "Return object") private object data;    @ApiModelProperty (value = "Error number") Private Integer Errcode;    @ApiModelProperty (value = "error message") Private String message; Example of}post request incoming object: @ApiOperation (vAlue= "Save User", notes= "Save User") @RequestMapping (value= "/saveuser", method= requestmethod.post) public String Saveuser (@Re        Questbody @ApiParam (name= "User Object", value= "incoming JSON format", required=true) User user) {Userdao.save (username);    return "success!"; }

Springboot using Swagger2 to implement restful APIs

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.