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

Example Analysis of REST Interface developed by SpringBoot

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you the SpringBoot development of REST interface example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to understand it!

The details are as follows:

HTTP verbs correspond to SQL commands

GET

Get resources from the server, but one or more, corresponding to the SELECTGET / users in the SQL command to get all the user information on the server GET / users/ID to obtain the user information of the specified ID

POST

Create a new resource on the server and create a new user corresponding to CREATEPOST / users in the SQL command

PUT

Update a resource on the server, and the client provides the changed complete resource, corresponding to the UPDATEPUT / users/ID in the SQL command to update all the information of the user of the specified ID

DELETE

Delete a resource from the server corresponding to DELETEDELETE / users/ID in the SQL command to delete the user information of the specified ID

PATCH

Update some attributes of a resource on the server, corresponding to UPDATEPATCH / users/ID in the SQL command to update a property of the user of the specified ID

Conventions in URL

Nouns are used in the plural in URL

The question of whether names in URL should be singular or plural has been debated for a long time. The nouns in URL generally correspond to tables in the database, which store similar data. In practice, I force the plural to look more comfortable.

/ users/users/1/roles/roles/1

As for some irregular and uncountable nouns, it is a matter of opinion.

/ heroes/heroes/1/people/people/1/foots/foots/1/feet/feet/1

Version

Version numbers are added to URL to deal with incompatible and destructive changes. When a new API is released, the client can freely migrate to the new API without getting into a dilemma by calling a completely different new API. Use the intuitive "V" prefix to indicate that the following number is the version number, no minor version number is required, and API versions should not be released frequently.

/ edu/v1/users/edu/v1/roles

Use query strings for optional, complex parameters

To make the URL smaller and more concise, set a basic URL for the resource, where optional and complex parameters are represented by a query string.

/ edu/v1/users?enabled=1&roleid=1

Provide paging information

It is not a good idea to return all the resources in the database at once, so you need to provide a paging mechanism. Usually use the well-known parameters offset and limit in the database

/ edu/v1/users?enabled=1&offset=1&limit=15

If the client does not pass these parameters, the default value, usually offset=0,limit=10, should be used.

Use verbs for non-resource requests

Sometimes the API call does not involve resources, in which case the server performs an operation disease to return the result to the client.

/ edu/v1/calc?p=100

Consider specific resources and cross-resource search

It is easy to provide a search for a specific stop, as long as you use the appropriate collection of resources and attach the search string to the query parameters.

/ edu/v1/users?username= Li Qinghai

If you need to provide a global search for all resources, you need to use other methods.

/ edu/v1/search?key= Li Qinghai

Response result

Use small hump nomenclature as attribute identifier

Typically, RESTful Web services will be used by clients written by JavaScript. The client converts the JSON response to a JavaScript object and then invokes its properties. Therefore, it is best to follow the general specification for JavaScript code.

Person.year_of_birth / / is not recommended, in violation of the general specification for JavaScript codes person.YearOfBirth / / is not recommended. The JavaScript construction method is named person.yearOfBirth / / recommended

Provide paging information

Paging information should be provided when a large number of results are returned.

{"page": 0, "size": 10, "total": 3465, "obj": []}

Developing REST Interface with Spring MVC

Common notes

@ RestController

@ RestController is a combination of @ ResponseBody and @ Controller.

@ RequestMapping

This comment can be applied either to a method of the controller or to this controller class. When a controller adds a @ RequestMapping annotation at the class level, this annotation is applied to all processor methods of the controller. The @ RequestMapping annotation on the processor method complements the declaration of @ RequestMapping at the class level.

@ PostMapping

Combinatorial annotations are abbreviations for @ RequestMapping (method = RequestMethod.POST).

@ PutMapping

Combinatorial annotations are abbreviations for @ RequestMapping (method = RequestMethod.PUT).

@ PatchMapping

Combinatorial annotations are abbreviations for @ RequestMapping (method = RequestMethod.PATCH).

@ DeleteMapping

Combinatorial annotations are abbreviations for @ RequestMapping (method = RequestMethod.DELETE).

@ GetMapping

Combinatorial annotations are abbreviations for @ RequestMapping (method = RequestMethod.GET).

@ PathVariable

Get the data in the url.

@ RequestParam

Gets the value of the request parameter.

REST Interface and Swagger programming API document example

For more information about the use of Swagger, please refer to the use of Swagger2 in the Spring Boot project. The code in the body of the method is not important, what matters is the signature of the method and the mapping to the HTTP verb.

Import java.util.Date;import javax.persistence.EntityNotFoundException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Page;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PatchMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam Import org.springframework.web.bind.annotation.RestController;import cn.com.infcn.jianshu.Service.UserService;import cn.com.infcn.jianshu.exception.BizException;import cn.com.infcn.jianshu.exception.LoginNameOrPasswordErrorException;import cn.com.infcn.jianshu.exception.ResourceExistsException;import cn.com.infcn.jianshu.model.User;import cn.com.infcn.jianshu.util.JsonResult;import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation;import io.swagger.annotations.ApiParam / * * system user Controller * @ author Li Qinghai * * / @ Api (value = "system user interface", tags = "system management") @ RestController@RequestMapping ("/ v3/edu/users") public class UserController {@ Autowired private UserService userService / * add users Register for * * @ param loginName * login account * @ param userName * user name * @ param password * login password * @ param roleId * user role * @ return * @ throws ResourceExistsException * / @ ApiOperation (value = "add user") @ PostMapping ("/") public JsonResult create (@ ApiParam (name = "loginName", value = "login account") Required = true) @ RequestParam (required = true) @ RequestBody String loginName, @ ApiParam (name = "userName", value = "user name", required = true) @ RequestParam (required = true) @ RequestBody String userName, @ ApiParam (name = "password", value = "login password", required = true) @ RequestParam (required = true) @ RequestBody String password, @ ApiParam (name = "roleId", value = "user role number" Required = true) @ RequestParam (required = true) @ RequestBody String roleId) throws ResourceExistsException {boolean exists = this.userService.exists (loginName) If (exists) {throw new ResourceExistsException (loginName);} User user = userService.create (loginName, password, userName, roleId); return JsonResult.success (user) } / * users log in by virtue of login account and login password * * @ param loginName * login account * @ param password * login password * @ throws EntityNotFoundException * / @ ApiOperation (value = "query user information by user number") @ GetMapping ("/ login") public JsonResult login (@ ApiParam (name = "loginName", value = "login account") Required = true) @ RequestParam (required = true) String loginName, @ ApiParam (name = "password", value = "login password", required = true) @ RequestParam (required = true) String password) throws LoginNameOrPasswordErrorException {User user = this.userService.login (loginName, password) If (null = = user) {throw new LoginNameOrPasswordErrorException ();} return JsonResult.success (user) } / * query user information by user number * * @ param id * user number * @ throws EntityNotFoundException * / @ ApiOperation (value = "query user information by user number") @ GetMapping ("/ {id}") public JsonResult read (@ ApiParam (name = "id", value = "user number") Primary key ", required = true) @ PathVariable (required = true) String id) throws EntityNotFoundException {User user = this.userService.getOne (id) Return JsonResult.success (user) } / * account is logged out without deleting user data * * @ param userId * user ID * @ return * / @ ApiOperation (value = "logout account") @ PatchMapping ("/ {id}") public JsonResult cancel (@ ApiParam (name = "id", value = "user number, primary key", required = true) @ PathVariable (required = true) String id) throws EntityNotFoundException {this.userService.cancel (id) Return JsonResult.success () } / * * reset password * * @ param id * user ID * @ param password * New login password * @ return * / @ ApiOperation (value = "reset password") @ PatchMapping ("/") public JsonResult updatePassword (@ ApiParam (name = "id", value = "user number") Primary key ", required = true) @ RequestParam (required = true) String id, @ ApiParam (name =" password ", value =" New login password ", required = true) @ RequestParam (required = true) String password) {this.userService.updatePassword (id, password) Return JsonResult.success () } / * multiple conditional combination query * * @ param userName * user name * @ param roleId * user role * @ param start * start date * @ param end * end date * @ param page * pagination, starting at 0 * @ param size * number of rows per page Default 10 * @ return * @ throws BizException * / @ ApiOperation (value = "user information query") @ GetMapping ("/") public JsonResult query (@ ApiParam (name = "userName", value = "user name") Query keywords ", required = false) @ RequestParam (required = false) String userName, @ ApiParam (name =" roleId ", value =" user role number ", required = false) @ RequestParam (required = false) String roleId, @ ApiParam (name =" start ", value =" user role number ", required = false) @ RequestParam (required = false) Date start, @ ApiParam (name =" end ", value =" user role number " Required = false) @ RequestParam (required = false) Date end, @ ApiParam (name = "page", value = "paging" Page, starting with 1, defaultValue = "1", required = true) @ RequestParam (defaultValue = "1", required = true) int page, @ ApiParam (name = "size", value = "rows per page, positive integer", defaultValue = "10", required = true) @ RequestParam (defaultValue = "10", required = true) int size) throws BizException {Page datas = this.userService.findDatas (userName, roleId, start, end, page, size) If (null = = datas | | null = = datas.getContent () | | datas.getContent () .isEmpty ()) {throw new BizException ("user does not exist");} return JsonResult.success (datas);}}

Swagger2 interface document effect diagram

The above is all the contents of the article "sample Analysis of SpringBoot developing REST Interface". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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

Development

Wechat

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

12
Report