My blog: Lanling xiaosheng, welcome to browse blog!

In the previous chapter, we introduced the engineering structure of the SpringBoot project and some common annotations. This chapter takes a brief look at API design.

There are a lot of tutorials on the web about API design, and this chapter is a brief introduction to how to better design an API from your own practical experience.

What are the key requirements of the API

1 Any client can call, need a standard, make client and server agree, must be simple

2 THE API is independent of the client. The existing client can continue to run without modification when the API is developed.

RESTful URLS

The REST API is designed around this resource, which has a unique identifier and uses JSON

Use HTTP to define operations for resources

  1. GET Obtains resources
  2. POST creates the resource, but POST can also be used to trigger actions that don’t actually create the resource
  3. PUT Creates or updates
  4. DELETE to remove the

SpringBoot and RESTful

SpringBoot provides many annotations that make it easy to implement RESTful apis

@RequestMapping:

This annotation takes six parameters:

  • Value /path: indicates the path name
  • Params: request parameters
  • Method: Indicates the method type, such as GET, POST, PUT, and DELETE
  • Headers: Request must contain some specified header value for the method to process the request.
  • Consumes: (Content-type), for example, application/ JSON or text/ HTML.

For example, a request represents a GET request:

@RequestMapping(path = "/list",method = RequestMethod.GET, consumes ="application/json")
public HttpResponse list() { 
    List<User> user = new ArrayList<>(userMap.values());   
    return HttpResponse.ok().setData(user);
}Copy the code

@PostMapping

@requestMapping (path = “/**”,method = requestmethod.post)

@GetMapping

@requestMapping (path = “/**”,method = requestmethod.get)

@DeleteMapping

@requestMapping (path = “/**”,method = requestmethod.delete)

@PutMapping

@requestMapping (path = “/**”,method = requestmethod.put)

Specific design

The definition of URL varies from company to company. Here are some simple examples of my own experience:

1 Easy to understand URL

The API has versioning, which allows rapid iteration and prevents invalid requests from accessing the updated access point

http://www.example.com/api/v {version} / module name/operation name

Obtaining a single user

GET /api/v1/user/get/1

or

GET /api/v1/user/1

For paging or all queries, input is JSON

POST /api/v1/user/list

This addition and update is usually an API, but you can also use PUT

POST /api/v1/user/save

Deleting User Resources

DELETE /api/v1/user/delete/12

or

DELETE /api/v1/user/12

public class User { private Long id; private String userName; private Long age; . }Copy the code

Custom unified return result

package com.miroservice.chapter2.common; import com.fasterxml.jackson.annotation.JsonInclude; import java.io.Serializable; import java.util.*; @JsonInclude(JsonInclude.Include.NON_NULL) public class HttpResponse implements Serializable { private long code; private String message; private Long total; private Object data; private List<Object> table; private String requestid; public static final long CODE_SUCCESS = 200; public static final long CODE_ERROR = 500; public static final long CODE_VALIDATE_FAILED = 404; public static final long CODE_UNAUTHORIZED = 401; public static final long CODE_FORBIDDEN = 403; public HttpResponse() { this(200, (String) null); } public HttpResponse(long code, String message) { this.code = CODE_SUCCESS; this.code = code; this.message = message; this.requestid = UUID.randomUUID().toString().replaceAll("-", ""); } public static HttpResponse error(String message) { return new HttpResponse(500, message); } public HttpResponse setData(Object data) { this.data = data; return this; } public HttpResponse data(Object data) { return this.setData(data); } public HttpResponse addListItem(Object item) { if (this.table == null) { this.table = new ArrayList(); } this.table.add(item); return this; } public HttpResponse setTotal(Long total) { this.total = total; return this; } public HttpResponse setTotal(Integer total) { this.total = (long) total; return this; } public static HttpResponse ok() { return new HttpResponse(); } public HttpResponse set(String field, String value) { if (this.data == null || ! (this.data instanceof Map)) { this.data = new HashMap(); } ((Map) this.data).put(field, value); return this; } public long getCode() { return this.code; } public HttpResponse setCode(long code) { this.code = code; return this; } public String getMessage() { return this.message; } public HttpResponse setMessage(String message) { this.message = message; return this; } public Long getTotal() { return this.total == null && this.table ! = null ? Long.valueOf(String.valueOf(this.table.size())) : this.total; } public Object getData() { return this.data; } public List<Object> getTable() { return this.table; } public HttpResponse setTable(List table) { this.table = table; return this; } public HttpResponse table(List table) { return this.setTable(table); } public String getRequestid() { return this.requestid; } public HttpResponse setRequestid(String requestid) { this.requestid = requestid; return this; }}Copy the code

The Controller layer

*/ @restController@requestMapping ("/ API /v1/user") public class UserController { static Map<Long, User> userMap = new HashMap<Long, User>(); /** * @requestMapping (method = requestmethod.get, consumes = "application/json") @GetMapping(consumes = "application/json") public HttpResponse list() { List<User> user =  new ArrayList<>(userMap.values()); return HttpResponse.ok().setData(user); } /** * save * @param user * @return */ @postmapping ("/save") public HttpResponse save(@requestBody user user) { userMap.put(user.getId(), user); return HttpResponse.ok(); } /** * Get user * @param ID * @return */ @getMapping ("/get/{id}") public HttpResponse get(@pathVariable Long ID) {final User user = userMap.get(id); return HttpResponse.ok().setData(user); } /** * delete * @param id * @return */ @deletemapping ("/delete/{id}") public HttpResponse delete(@pathVariable Long id) { userMap.remove(id); return HttpResponse.ok(); }}Copy the code

That’s it, and you can also check out this blog’s #Spring Boot Getting Started Practice series! #

Reference: # Microsoft API practices #Spring REST DOC#

This article is published by OpenWrite!