POST Routes and JSON Bodies
A POST route is a route that takes data sent in a request. The data travels as JSON in the body of the request.
The form record
This record holds the fields of a task. JSON keys must match these names.
record TaskForm(String title, boolean done) {}Take a POST with a JSON body
The annotation marks the method for POST. The body arrives as a TaskForm.
@PostMapping("/tasks")
public TaskForm create(@RequestBody TaskForm form) {
return form;
}Send a task as JSON
Send this JSON body to POST /tasks. The answer echoes the same JSON.
{"title":"Buy milk","done":false}Example
package com.example.demo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
record TaskForm(String title, boolean done) {
}
@PostMapping("/tasks")
public TaskForm create(@RequestBody TaskForm form) {
return form;
}
}Key points
- @PostMapping marks a method as the answer for POST requests.
- POST sends data, so it fits making a new thing.
- The body is the part of a request that carries data.
- @RequestBody reads JSON from the body into a Java object.
- A record holds the fields of the JSON body.
- The method returns the same object, and Spring Boot sends it back as JSON.
In this example, the record TaskForm holds a title and a done flag. The controller has one route. The route answers POST requests for /tasks. The annotation @RequestBody reads the JSON body into a TaskForm. The method returns the same form. Spring Boot turns it back into JSON for the answer. The request sends one task, and the answer echoes the same task.
Note
JSON field names must match the record field names.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @RequestBody do?