Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Springboot integrates swagger-UI to develop API Project

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

When developing the API project on the server side, we can integrate the swagger plug-in into our project, so that it is convenient and quick for background developers to directly use the visual interface for test. A test code case: pom.xml io.springfox springfox-swagger2 ${version.springfox} io.springfox springfox-swagger-ui ${version.springfox} com.github.xiaoymin swagger-bootstrap-ui ${version.swagger-bootstrap-ui} io.swagger swagger -annotations ${version.swagger} io.swagger swagger-models ${version.swagger}

Package com.vicrab.api.server

Import com.vicrab.api.datasource.MongoDBTemplateRegister

Import org.mybatis.spring.annotation.MapperScan

Import org.springframework.boot.CommandLineRunner

Import org.springframework.boot.ExitCodeGenerator

Import org.springframework.boot.SpringApplication

Import org.springframework.boot.autoconfigure.SpringBootApplication

Import org.springframework.context.annotation.ComponentScan

Import org.springframework.context.annotation.Import

Import springfox.documentation.swagger2.annotations.EnableSwagger2

@ SpringBootApplication

@ EnableSwagger2

@ ComponentScan (basePackages = {"com.vicrab.api"})

@ MapperScan ("com.vicrab.api.repository.mapper")

@ Import (MongoDBTemplateRegister.class)

Public class Swagger2SpringBoot implements CommandLineRunner {

@ Overridepublic void run (String... Arg0) throws Exception {if (arg0.length > 0 & & arg0 [0] .equals ("exitcode")) {throw new ExitException ();}} public static void main (String [] args) throws Exception {new SpringApplication (Swagger2SpringBoot.class) .run (args);} class ExitException extends RuntimeException implements ExitCodeGenerator {private static final long serialVersionUID = 1L; @ Override public int getExitCode () {return 10;}}

}

Note explanation:

@ SpringBootApplication: notes specific to Springboot projects

@ EnableSwagger2: enable swagger project

@ ComponentScan (basePackages = {"com.vicrab.api"}): @ ComponentScan mainly defines the scanning path and finds out that the classes that need to be assembled are automatically assembled into the bean container of spring indicating that the objects in the com.vicrab.api package need to be loaded into the bean container of Spring.

@ MapperScan: the package annotated by MapperScan allows other classes to reference the annotated class

Some example codes:

Package com.vicrab.api.server.api

Import com.vicrab.api.server.model.OperateResult

Import com.vicrab.api.server.model.UserBase

Import com.vicrab.api.server.model.UserRegister

Import io.swagger.annotations.*

Import org.springframework.http.HttpStatus

Import org.springframework.http.ResponseEntity

Import org.springframework.web.bind.annotation.PathVariable

Import org.springframework.web.bind.annotation.RequestBody

Import org.springframework.web.bind.annotation.RequestHeader

Import org.springframework.web.bind.annotation.RequestMapping

Import org.springframework.web.bind.annotation.RequestMethod

Import org.springframework.web.bind.annotation.RequestParam

Import org.springframework.web.bind.annotation.RequestPart

Import org.springframework.web.multipart.MultipartFile

Import java.util.List

Import javax.validation.constraints.*

Import javax.validation.Valid

@ javax.annotation.Generated (value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-04-19T17:09:30.945+08:00")

Api (value = "user", tags = {"user",}, description = "the user API")

Public interface UserApi {

@ ApiOperation (value = "get user information", notes = "get_user", response = OperateResult.class, tags = {"user",}) @ ApiResponses (value = {@ ApiResponse (code = 200,message = "OK", response = OperateResult.class), @ ApiResponse (code = 500,message = "system error", response = Void.class)}) @ RequestMapping (value = "/ user/ {user_key}", produces = {"application/json"}) Method = RequestMethod.GET) default ResponseEntity getUser (@ ApiParam (value = "user key", required = true) @ PathVariable ("user_key") String userKey) {/ / do some magic! Return new ResponseEntity (HttpStatus.OK) } @ ApiOperation (value = "getting user information by mailbox", notes = "get_user_by_email", response = OperateResult.class, tags = {"user",}) @ ApiResponses (value = {@ ApiResponse (code = 200,message = "OK", response = OperateResult.class), @ ApiResponse (code = 500,message = "system error", response = Void.class)}) @ RequestMapping (value = "/ user/email", produces = {"application/json"}) Method = RequestMethod.GET) default ResponseEntity getUserByEmail (@ NotNull @ ApiParam (value = "user mailbox", required = true) @ RequestParam (value = "user_email", required = true) String userEmail) {/ / do some magic! Return new ResponseEntity (HttpStatus.OK) } @ ApiOperation (value = "user login", notes = "login", response = OperateResult.class, tags = {"user",}) @ ApiResponses (value = {@ ApiResponse (code = 200,message = "OK", response = OperateResult.class), @ ApiResponse (code = 500,message = "system error", response = Void.class)}) @ RequestMapping (value = "/ user/login", produces = {"application/json"}) Method = RequestMethod.POST) default ResponseEntity login (@ NotNull @ ApiParam (value = "user mailbox", required = true) @ RequestParam (value = "user_email", required = true) String userEmail, @ NotNull @ ApiParam (value = "user password", required = true) @ RequestParam (value = "user_pwd", required = true) String userPwd) {/ / do some magic! Return new ResponseEntity (HttpStatus.OK);}

Scope of action API usage location

The object property @ ApiModelProperty is used on the field of the parameter object

The protocol set description @ Api is used on the Conntroller class

The protocol description @ ApiOperation is used on the controller method

The Response set @ ApiResponses is used on the controller method

Response @ ApiResponse is used in @ ApiResponses

@ api: value-Field description, description-comment this class

@ ApiOperation

Value-Field description

Notes-comment description

HttpMethod-indicates how this method is requested

Type-response of the return value of the method

@ ApiResponses

Code-HTTP status code of the response

Message-the information content of the response

Type-response of the return value of the method

@ ApiParam @ PathVariable @ RequestParam

A. @ ApiParam, as its name implies, is a parameter for annotating api, that is, it is used for swagger to provide developer documentation and comment content generated in the documentation.

@ ApiOperation (value = "Edit announcement", notes = "Edit announcement", httpMethod = "POST")

@ RequestMapping (value = "/ edit", method = RequestMethod.POST)

Public RequestResult edit (

@ ApiParam (name = "title", value = "announcement title", required = true) @ RequestParam ("title") String title

@ ApiParam (name = "content", value = "announcement content", required = true) @ RequestParam ("content") String content) {

B. @ RequestParam is used to obtain the parameters passed from the front end to the backend, either get or post. If the parameter passed by the frontend is consistent with the name field of the parameter you accept at the backend, you can omit it or write @ RequestParam String title directly. If it is inconsistent, you must write it in its entirety, otherwise it cannot be obtained, such as the bis_key below.

@ ApiOperation (value = "Edit announcement", notes = "Edit announcement", httpMethod = "POST")

@ RequestMapping (value = "/ edit", method = RequestMethod.POST)

Public RequestResult edit (

@ ApiParam (name = "bis_key", value = "bis_key", required = true) String bisKey

@ ApiParam (name = "title", value = "announcement title", required = true) @ RequestParam String title

@ ApiParam (name = "content", value = "announcement content", required = true) String content

C. @ PathVariable, which is used to obtain parameters in get mode, followed by url, to bind parameters.

@ ApiOperation (value = "delete announcement", notes = "delete announcement", httpMethod = "POST")

@ RequestMapping (value = "/ delete/ {bisKey}", method = RequestMethod.POST)

Public RequestResult remove (@ ApiParam (name = "bisKey", value = "announcement to be deleted", required = true) @ PathVariable String bisKey) {

Partial implementation code:

Import com.vicrab.api.bean.VicrabResult

Import com.vicrab.api.log.AuditLogAnnotation

Import com.vicrab.api.log.AuditLogEnum

Import com.vicrab.api.server.model.User

Import com.vicrab.api.server.model.UserBase

Import com.vicrab.api.server.model.UserRegister

Import com.vicrab.api.server.api.UserApi

Import com.vicrab.api.bean.OperateCode

Import com.vicrab.api.server.model.OperateResult

Import com.vicrab.api.service.UserService

Import com.vicrab.api.utils.MailUtils

Import io.swagger.annotations.ApiParam

Import org.apache.commons.lang3.StringUtils

Import org.slf4j.Logger

Import org.slf4j.LoggerFactory

Import org.springframework.beans.factory.annotation.Autowired

Import org.springframework.http.HttpStatus

Import org.springframework.http.ResponseEntity

Import org.springframework.stereotype.Controller

Import org.springframework.web.bind.annotation.PathVariable

Import org.springframework.web.bind.annotation.RequestBody

Import org.springframework.web.bind.annotation.RequestParam

Import javax.validation.constraints.*

Import javax.validation.Valid

@ javax.annotation.Generated (value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-03-16T11:20:10.134+08:00")

@ Controller

Public class UserApiController implements UserApi {

Private static final Logger logger = LoggerFactory.getLogger (UserApiController.class); @ Autowiredprivate UserService userService;@Overridepublic ResponseEntity getUser (@ ApiParam (value = "user key", required = true) @ PathVariable ("user_key") String userKey) {OperateResult operateResult = new OperateResult (); try {if (StringUtils.isBlank (userKey)) {operateResult = OperateResult.set (OperateCode.PARAM_ERROR); return new ResponseEntity (operateResult, HttpStatus.BAD_REQUEST) } User user = userService.getUser (userKey); operateResult = OperateResult.success (user); return new ResponseEntity (operateResult, HttpStatus.OK);} catch (Exception e) {logger.error ("api getUser error. {}", e); operateResult = OperateResult.exception (OperateCode.SYSTEM_ERROR, e); return new ResponseEntity (operateResult, HttpStatus.INTERNAL_SERVER_ERROR) } @ Overridepublic ResponseEntity getUserByEmail (@ NotNull @ ApiParam (value = "user mailbox", required = true) @ RequestParam (value = "user_email", required = true) String userEmail) {OperateResult operateResult = new OperateResult (); try {if (StringUtils.isBlank (userEmail)) {operateResult = OperateResult.set (OperateCode.PARAM_ERROR); return new ResponseEntity (operateResult, HttpStatus.BAD_REQUEST) } operateResult = userService.getUserByEmail (userEmail); return new ResponseEntity (operateResult, HttpStatus.OK);} catch (Exception e) {logger.error ("api getUser error. {}", e); operateResult = OperateResult.exception (OperateCode.SYSTEM_ERROR, e); return new ResponseEntity (operateResult, HttpStatus.INTERNAL_SERVER_ERROR) } @ Overridepublic ResponseEntity login (@ NotNull @ ApiParam (value = "user mailbox", required = true) @ RequestParam (value = "user_email", required = true) String userEmail, @ NotNull @ ApiParam (value = "user password", required = true) @ RequestParam (value = "user_pwd", required = true) String userPwd) {OperateResult operateResult = new OperateResult () Try {if (StringUtils.isBlank (userEmail) | | StringUtils.isBlank (userPwd)) {operateResult = OperateResult.set (OperateCode.PARAM_ERROR); return new ResponseEntity (operateResult, HttpStatus.BAD_REQUEST);} / / verify email if (! MailUtils.verifyEmail (userEmail)) {operateResult = OperateResult.set (OperateCode.EMAIL_PATTERN_ERROR) Return new ResponseEntity (operateResult, HttpStatus.BAD_REQUEST);} VicrabResult vicrabResult = userService.login (userEmail, userPwd); operateResult = OperateResult.set (vicrabResult.getOperateCode (), vicrabResult.getData ()); return new ResponseEntity (operateResult, HttpStatus.OK);} catch (Exception e) {logger.error ("api login error. {}", e); operateResult = OperateResult.exception (OperateCode.SYSTEM_ERROR, e) Return new ResponseEntity (operateResult, HttpStatus.INTERNAL_SERVER_ERROR);}} here focuses on the significance of many annotations. Download the swagger-ui project, put the directory containing doc.html on the first layer under the src/main/resources directory, and start accessing http://ip:port/doc.html

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report