introduction
The separation of front and back ends, APP interaction, etc., are mostly realized through API interfaces. Since data interaction is to be carried out, then this interface must be exquisite: it must be both practical and elegant!
So, how to write a set(s) of beautiful API interfaces?
1. Return format
The format required by the API interface is text/json
that we know that the format returned by the web page is generally text/html
. Therefore, Spring Boot provides two implementation methods for writing interfaces: class annotations and method annotations.
- class annotation
@RestController
We only need to write annotations on the class @RestController
, then the return format of this Controller is the same text/json
. As shown below
- method annotation
@ResponseBody
We only need to write an annotation on a method @ResponseBody
, then the return format of the method is text/json
. As shown below
It is worth reminding that although all are possible, I prefer to use class annotations, which will make our coding style very uniform and the code more compact, so that it will not look scattered.
Let's look at @RestController
the source code
2. Request method
@RequestMapping
mentioned in the source code of RequestMapping, this supports arbitrary request methods, similar to adaptive.
@GetMapping
clients can only request in the GET
way , which is suitable for querying data
@PostMapping
clients can only request with the POST
method , which is suitable for submitting data.
The @DeleteMapping
client can only request with the DELETE
method , which is used to delete data.
The @PutMapping
client can only request using the PUT
method to modify the data (but in actual use, I personally recommend that the POST method is more appropriate).
The above request is often used in interface development, and the picture is annotated source code. Of course there are others. For the request method and scope of use, please refer toRESTful API
3. Receive parameters
- @RequestParam
Let's write an example and illustrate:
public String getInfo(@RequestParam(name = "param",
required = false,
defaultValue = "param dafault value") String param)
name
Represents the submit parameter name.
required
It means whether this parameter is required, the default is true, without this parameter, this method cannot be called; here it is set to false, and it can be called with or without this parameter.
defaultValue
If the parameter value is empty, the default value is used.
- PathVariable
@RequestMapping("/get-info/{param}")
public String getInfo(@PathVariable("param") Object param)
We can directly follow the value after the request method, and save it ?参数名=
.
This kind of general cooperation @DeleteMapping
and @PutMapping
use.
- @RequestHeader
This uses Headers
the . I am used to receive TOKEN
. Examples will be given later.
4. Data format
Let's take a look at the data formats that Spring Boot can support.
The basic data types I usually use are int
, String
.
And in our daily life, we may also have Array
, List
, Map
. . .
So, does Spring Boot support it?
I will not discuss this here, because of the format, we will not use it. If you are interested, you can try it. The answer is, it can definitely be done.
5. Problems
How do we solve the 四
problem in ? And what about unification?
JSON!
There is no doubt that JSON can help us solve this problem, and of course XML can also.
How to use? How to write the code? front end? Does it support mobile?
6. Solutions
I have encapsulated the code into the JavaLib library, so let's call it directly.
- Encapsulate and submit POST data
@Test
public void testPostData() {
// int
int pInt = 0;
// String
String pString = "String";
// String []
String [] pStrings = {"String [0]", "String [1]"};
// List
List<String> pLists = List.of("list[0]", "list[1]");
// 。。
Map<String, Object> params = new HashMap<>();
params.put("p-int", pInt);
params.put("p-string", pString);
params.put("p-strings", pStrings);
params.put("p-list", pLists);
String url = "http://localhost:8080/api/get-info";
try {
String rs = HttpUtil.post(url, null, params);
System.out.println(rs);
} catch (IOException e) {
e.printStackTrace();
}
}
- Get data submitted by POST
@RestController
@RequestMapping("/api")
public class APIController {
@PostMapping("/get-info")
public String getInfo(HttpServletRequest request) {
try {
String jsonStr = RequestUtil.getPostData(request);
System.out.println(jsonStr);
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
At this point, I believe that you should be able to write the interface with ease! However, I still have something to share with you!
7. Sharing
Look at the Ajax
code :
$.ajax({
headers : {
Accept: "application/json; charset=utf-8",
'token' : '9B4BF951093F1F1A40BB2DAAA30B3838'
},
url: URI + '/admin/blog/add',
type: 'POST',
async: true,
data: {
...
},
timeout: 3000,
dataType: 'json',
beforeSend: function(xhr){},
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(xhr, textStatus){
console.log(xhr);
},
complete: function(){}
})
Now the question is how to get token
the value of ? I believe you are smart, you must still remember that we have already sold the key! That's right, it is @RequestHeader("token")
!
The problem is not over yet, what if we are not in the Controller?
the answer is
String token = request.getHeader("token");
System.out.println(token);
8. Epilogue
Here, I finally have to say goodbye to everyone!
You must be able to write beautiful, concise and elegant API interfaces.
If you encounter problems about the interface during development, welcome to communicate with me!
9. Update
Before, because I wrote the public interface document (refer to: [Work] Delivery service API document ), I used the MD format.
But in actual development, we may only write interfaces for the front end or APP. If we also need to write interfaces, it may be quite troublesome. So many people suggested me to update it. So take the time to update first, Spring Boot integrates Swagger, if you are interested, come and learn.
Without further ado, just look at the effect:
For the code, see here: api-demo
For a detailed explanation, please see here: Using Swagger2 to build powerful RESTful API documentation in Spring Boot
in addition:
1. If you want to learn more, you can look at TestController
2. References: