🎓 A1Learner
🔍
0 of 50 lessons completed

Answers with ResponseEntity

ResponseEntity is a wrapper that carries a body and a status together. It lets a method set the status of its answer.

Answer with 200

Ask for /hello. The answer carries the greeting with status 200.

@GetMapping("/hello")
public ResponseEntity<String> hello() {
    return ResponseEntity.ok("Hello, Spring Boot!");
}

Answer a POST with 201

This method wraps the new task with status 201. The body carries the task as JSON.

@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.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 ResponseEntity<TaskForm> create(@RequestBody TaskForm form) {
    return ResponseEntity.status(201).body(form);
  }
}

Key points

  • ResponseEntity wraps a body and a status together.
  • ResponseEntity.ok(body) answers with the body and status 200.
  • ResponseEntity.status(201).body(form) answers with status 201.
  • The body travels inside the ResponseEntity.
  • Return ResponseEntity from a method instead of a plain value.

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 wraps the form in a ResponseEntity with status 201. Spring Boot sends the task back as JSON with status 201.

Note

A plain return value always answers with status 200.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does a method answer a POST with status 201?