🎓 A1Learner
🔍
0 of 50 lessons completed

Empty Answers and 204

An empty answer is an answer with no body. 204 means the request went well and the answer carries nothing.

Delete with 204

This method answers DELETE requests for /tasks. It sends status 204 with no body.

@DeleteMapping("/tasks")
public ResponseEntity<Void> remove() {
    return ResponseEntity.noContent().build();
}

A void method answers with 200

This method also sends no body. Its status is the default 200.

@DeleteMapping("/tasks")
public void remove() {
}

Example

package com.example.demo;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

  @DeleteMapping("/tasks")
  public ResponseEntity<Void> remove() {
    return ResponseEntity.noContent().build();
  }
}

Key points

  • Some answers need no body, like an answer to a delete.
  • A delete that works well often answers with 204.
  • ResponseEntity.noContent().build() answers with 204 and no body.
  • A method that returns void answers with 200 and no body.
  • Use 204 when the request worked and there is nothing to send back.

In this example, the controller has one route. The route answers DELETE requests for /tasks. The method returns no body, only a status. ResponseEntity.noContent().build() builds an answer with status 204 and no body. The DELETE request gets status 204 back with an empty body.

Note

A 204 answer must carry no body at all.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does a method answer with 204 and no body?