Skip to content

7.1.2 Sending data to the server

So far your API is able to return up to a dozen of the most recently created tacos. But how do those tacos get created in the first place?

Although you could use a CommandLineRunner bean to preload the database with some test taco data, ultimately taco data will come from users when they craft their taco creations. Therefore, we’ll need to write a method in TacoController that handles requests containing taco designs and save them to the database. By adding the following postTaco() method to TacoController, you enable the controller to do exactly that:

java
@PostMapping(consumes="application/json")
@ResponseStatus(HttpStatus.CREATED)
public Taco postTaco(@RequestBody Taco taco) {
  return tacoRepo.save(taco);
}

Because postTaco() will handle an HTTP POST request, it’s annotated with @PostMapping instead of @GetMapping. You’re not specifying a path attribute here, so the postTaco() method will handle requests for /api/tacos as specified in the class-level @RequestMapping on TacoController.

You do set the consumes attribute, however. The consumes attribute is to request input what produces is to request output. Here you use consumes to say that the method will only handle requests whose Content-type matches application/json.

The method’s Taco parameter is annotated with @RequestBody to indicate that the body of the request should be converted to a Taco object and bound to the parameter. This annotation is important—without it, Spring MVC would assume that you want request parameters (either query parameters or form parameters) to be bound to the Taco object. But the @RequestBody annotation ensures that JSON in the request body is bound to the Taco object instead.

Once postTaco() has received the Taco object, it passes it to the save() method on the TacoRepository.

You may have also noticed that I’ve annotated the postTaco() method with @ResponseStatus(HttpStatus.CREATED). Under normal circumstances (when no exceptions are thrown), all responses will have an HTTP status code of 200 (OK), indicating that the request was successful. Although an HTTP 200 response is always welcome, it’s not always descriptive enough. In the case of a POST request, an HTTP status of 201 (CREATED) is more descriptive. It tells the client that not only was the request successful but a resource was created as a result. It’s always a good idea to use @ResponseStatus where appropriate to communicate the most descriptive and accurate HTTP status code to the client.

Although you’ve used @PostMapping to create a new Taco resource, POST requests can also be used to update resources. Even so, POST requests are typically used for resource creation, and PUT and PATCH requests are used to update resources. Let’s see how you can update data using @PutMapping and @PatchMapping.

Released under the MIT License.