While reading the last chapter, you encountered all of the required tools to set up RESTful endpoints and format returned data. Now come the final few pieces of knowledge needed to create fully functioning and valuable RESTful APIs: receiving data from the client.
In the Making HTTP Requests Using Spring section of this course, you learned about the three ways that a user can pass information to the server using the HTTP protocol. They are:
- Path Variables: Varying data within the path of a URL.
- Query Parameters: Key-value pairs directly after a URL path.
- Request Body: The body of a request, used to transmit larger or more complex data.
For each of the above, Spring provides an annotation allowing easy access to the information without manual parsing and translation. The next chapter will show you when and how they are used. Here are a few quick previews before you dive in deeper.
@RequestParam
This annotation retrieves query parameters from the URL by their name.
For example, with a URL structured like this: /user?id=100, you can grab the id parameter and map it to the variable userId like so:
@GetMapping(path = "/user")
public ResponseEntity<User> getUserById(
@RequestParam(name = "id") Long userId) {
return ResponseEntity.ok().body(userService.getUser(userId));
}
@PathVariable
This annotation tells Spring to pull information from the URL path and map it onto a variable. Here's a quick example structured like this: /tasks_api/tasks/1435
@GetMapping(value = "/tasks_api/tasks/{id}")
public Task getTask(@PathVariable Long id) {
return taskService.getTask(id);
}
@RequestBody
This annotation indicates the variable Spring will map the HTTP body onto. The next example shows you how this is done.
@PostMapping(path = "/user")
public ResponseEntity<User> saveNewUser(@RequestBody User user) {
User newUser = userService.saveUser(user);
return ResponseEntity
.created(new URI("/path/to/new/user"))
.body(newUser);
}
Summary: Client Data Annotations
You've now been introduced to the three primary annotations used to pull information from an incoming HTTP request:
@PathVariablepulls information from the URL path and maps it onto a variable.@RequestParamis used to retrieve query parameters from the URL by their name.@RequestBodyindicates the variable Spring will map the HTTP body onto.
The following lessons will discuss each of these annotations in more detail. Get ready to grab some incoming data!