Status Codes
A status code is a number in an answer that says how a request went. 200 means the request went well.
Read the status of a greeting
Ask for /hello and read the status of the answer. It is 200.
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}Make a task with 201
This method answers a POST with status 201. The body carries the new task.
@PostMapping("/tasks")
public ResponseEntity<TaskForm> create(@RequestBody TaskForm form) {
return ResponseEntity.status(201).body(form);
}Example
package com.example.demo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
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) {
}
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
@PostMapping("/tasks")
public ResponseEntity<TaskForm> create(@RequestBody TaskForm form) {
return ResponseEntity.status(201).body(form);
}
}Key points
- 200 means the request went well.
- 201 means a new thing was made.
- 204 means the request went well with no body.
- 400 means the request was wrong.
- 404 means the address does not exist.
- A plain return value answers with status 200.
In this example, the record TaskForm holds a title and a done flag. The controller has two routes. The first route answers GET requests for /hello. It returns the greeting, so the status is 200. The second route answers POST requests for /tasks. It wraps the new task with status 201. The POST request sends one task, and the answer echoes it with status 201.
Note
Status codes are numbers, not text.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does status 201 mean?