ResponseEntity and status codes
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite app asks for product 99, but the server has no such product. Answering 200 with an empty body would lie, so the method must choose a status for each outcome.
ResponseEntity.ok, noContent and notFound
ResponseEntity<T> is the whole HTTP response as one Java object: the status, the headers and a body of type T. Its builder methods name the common answers: ok(body), noContent().build() and notFound().build().
A get method must answer 200 with a product, or 404 when there is none. The example returns a ResponseEntity from get and from delete.
Example 1 · get and delete with ResponseEntity
Runs in: the rest-lab practice project (Spring Boot 4.1)
@GetMapping("/{id}")public ResponseEntity<Product> get(@PathVariable long id) { return productService.findById(id) .map(ResponseEntity::ok) .orElseGet(() -> ResponseEntity.notFound().build());}
@DeleteMapping("/{id}")public ResponseEntity<Void> delete(@PathVariable long id) { if (productService.delete(id)) { return ResponseEntity.noContent().build(); } return ResponseEntity.notFound().build();}$ curl -i http://localhost:8080/api/v1/products/6
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:16:14 GMT
{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Accessories","price":1299.00,"stock":120,"isActive":true}
$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404
Content-Length: 0
Date: Fri, 16 Oct 2026 05:16:15 GMT
$ curl -i -X DELETE http://localhost:8080/api/v1/products/9
HTTP/1.1 204
Date: Fri, 16 Oct 2026 05:16:15 GMTWhat this code does
getanswers 200 with the product or 404 with no body; the return typeResponseEntity<Product>covers both.deletereturnsResponseEntity<Void>: 204 when the service removed the product, 404 when there was nothing to remove.- A 204 response has no
Content-Typeand no body at all: there is nothing to describe.
Why not just return the product? A method that returns Product always answers 200. It has no way to say "there is no such product". With ResponseEntity<Product> the method decides the status for each outcome, and the type still says what the body holds.
For a body-less response use ResponseEntity<Void>, as in delete. Any status works through ResponseEntity.status(HttpStatus.CONFLICT); the named methods are just shortcuts.
@ResponseStatus: the short form
@ResponseStatus(HttpStatus.CREATED) on a controller method sets the status of every successful call, while the method keeps returning the plain body. It fits only a fixed code.
When a method always answers with the same code, a full ResponseEntity is more than needed. The example uses @ResponseStatus, and shows ResponseEntity winning over it.
Example 2 · @ResponseStatus: 204 with a body, and ResponseEntity winning
Runs in: the rest-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/StatusMistakesController.java (two of its methods)// Mistake 3: 204 No Content on a method that returns a body@GetMapping("/lab/mistakes/no-content/{id}")@ResponseStatus(HttpStatus.NO_CONTENT)public Product noContentWithBody(@PathVariable long id) { return productService.findById(id).orElse(null);}
// Which wins: @ResponseStatus or the ResponseEntity status?@GetMapping("/lab/mistakes/both/{id}")@ResponseStatus(HttpStatus.CREATED)public ResponseEntity<Product> both(@PathVariable long id) { return ResponseEntity.of(productService.findById(id));}$ curl -i http://localhost:8080/lab/mistakes/no-content/3
HTTP/1.1 204
Content-Type: application/json
Date: Fri, 16 Oct 2026 05:16:15 GMT
$ curl -i http://localhost:8080/lab/mistakes/both/3
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:16:16 GMT
{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true}What this code does
- The first method returns the iPhone, but 204 means "no content", so the body is dropped and the client sees nothing.
- The second method has
@ResponseStatus(HttpStatus.CREATED)and returnsResponseEntity.of(...). The response is 200: theResponseEntitystatus wins and the annotation is ignored. - The
createmethod inProductControlleris the right use of the annotation:@ResponseStatus(HttpStatus.CREATED)and a plainProductreturn, always 201.
It fits only fixed codes. When the code depends on the outcome, return a ResponseEntity. If a method has both, the ResponseEntity status wins and the annotation is ignored, so do not mix them.
Watch the meaning of the code you choose. 204 means "no content": Tomcat drops whatever body the method returned. Putting @ResponseStatus(HttpStatus.NO_CONTENT) on a method that returns a product hides the product from the client.
Choosing codes: 200, 201, 204, 400, 404, 409
409 Conflict means the request clashes with the current state of the data: a duplicate SKU, not enough stock, an order that is already shipped. The client must change something before it can try again.
A client checks the status code first, so each outcome needs the one code the contract promises. The example returns null for a missing product, and shows why that lies.
Example 3 · Returning null for "not found": a 200 that lies
Runs in: the rest-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/StatusMistakesController.java (Mistake 2)// Mistake 2: returning null for "not found"@GetMapping("/lab/mistakes/null/{id}")public Product nullForMissing(@PathVariable long id) { return productService.findById(id).orElse(null);}$ curl -i http://localhost:8080/lab/mistakes/null/99 HTTP/1.1 200 Content-Length: 0 Date: Fri, 16 Oct 2026 05:16:15 GMT
What this code does
- Product 99 does not exist, yet the status is 200 with an empty body. A mobile app would try to read a product from nothing and crash, or show a blank screen.
- The right code is 404, as
ProductController.getin Example 1 answers. Every outcome needs its own honest code.
The ShopLite contract uses these codes:
- 200 OK: a read, an update (PUT or PATCH) or an order action, with the resource in the body
- 201 Created: a create, with the new resource and its
Locationheader (next lessons) - 204 No Content: a successful delete, no body
- 400 Bad Request: the request itself is wrong, such as broken JSON or a missing field; 404 Not Found: the resource in the URL does not exist
422 is for valid fields that break a rule about other data, such as an unknown categoryId. Never answer 200 for a failure, and never 500 for a client mistake: a 500 tells the client "our bug, try later".
Adding headers to a response
Cache-Control is a response header that tells browsers and apps how long they may reuse a response. max-age=600 allows 10 minutes without asking again; no-store forbids keeping it.
The category list changes rarely, but stock levels change all the time. The example adds headers to a category response with the builder.
Example 4 · src/main/java/com/shoplite/lab/category/CategoryController.java: headers
Runs in: the rest-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.category;
import java.time.Duration;import java.util.List;
import org.springframework.http.CacheControl;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/api/v1/categories")public class CategoryController {
private static final List<Category> CATEGORIES = List.of( new Category(1, "Electronics", null), new Category(2, "Mobiles", 1L), new Category(3, "Laptops", 1L), new Category(4, "Accessories", 1L), new Category(5, "Books", null), new Category(6, "Fashion", null), new Category(7, "Home & Kitchen", null));
@GetMapping public ResponseEntity<List<Category>> list() { return ResponseEntity.ok() .cacheControl(CacheControl.maxAge(Duration.ofMinutes(10))) // clients may reuse it for 10 minutes .header("X-Total-Count", String.valueOf(CATEGORIES.size())) .body(CATEGORIES); }}$ curl -i http://localhost:8080/api/v1/categories
HTTP/1.1 200
Cache-Control: max-age=600
X-Total-Count: 7
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:16:15 GMT
[{"id":1,"name":"Electronics","parentId":null},{"id":2,"name":"Mobiles","parentId":1},{"id":3,"name":"Laptops","parentId":1},{"id":4,"name":"Accessories","parentId":1},{"id":5,"name":"Books","parentId":null},{"id":6,"name":"Fashion","parentId":null},{"id":7,"name":"Home & Kitchen","parentId":null}]What this code does
ResponseEntity.ok()starts a 200 response;.cacheControl(...)and.header(...)add headers;.body(...)finishes it.CacheControl.maxAge(Duration.ofMinutes(10))becomesCache-Control: max-age=600(seconds). TheCategoryrecord moved into thecategorypackage; it is the one from the first lesson.- The body is the same JSON array as before. Headers never change the body, only what the client knows about it.
A response header carries information about the response, not the data itself. The builder adds them: .header("X-Total-Count", "7") for any header, and typed helpers such as .cacheControl(...), .eTag(...) or .location(uri) for standard ones.
Headers cost almost nothing to add, but each one is a promise to clients. Add only what a client needs, and name custom headers clearly.
Optional from a service mapped to 200 or 404
Optional<T> is a box that holds one value or nothing. A service returns Optional<Product> for "maybe a product", and the controller turns that maybe into 200 or 404.
The service says "maybe a product", and the controller must turn that into a status. The example maps an Optional to 200 or 404, and shows the get() mistake.
Example 5 · Optional to 200 or 404, and the get() mistake
Runs in: the rest-lab practice project (Spring Boot 4.1)
// Three ways to write the same get methodreturn ResponseEntity.of(productService.findById(id));
return productService.findById(id) .map(ResponseEntity::ok) .orElseGet(() -> ResponseEntity.notFound().build());
return productService.findById(id).isPresent() ? ResponseEntity.ok(productService.findById(id).get()) : ResponseEntity.notFound().build(); // works, but looks the product up twice
// Mistake 1: get() on an empty Optional@GetMapping("/lab/mistakes/get/{id}")public Product unsafeGet(@PathVariable long id) { return productService.findById(id).get();}$ curl -i http://localhost:8080/lab/mistakes/get/99
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:16:15 GMT
Connection: close
{"timestamp":"2026-10-16T05:16:15.698Z","status":500,"error":"Internal Server Error","path":"/lab/mistakes/get/99"}
Server log:
ERROR ... Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.util.NoSuchElementException: No value present] with root causeWhat this code does
- The first two forms answer exactly like Example 1: 200 or 404. Use
ResponseEntity.offor the simple case, andmapwhen you need headers on the 200 response. get()on an empty Optional throwsNoSuchElementException: No value present. Spring turns any uncaught exception into a 500, so the client is told the server broke when it only asked for a missing product.- The
isPresent()andget()pair works but calls the service twice; between the two calls another request could delete the product.
Two shortcuts look easier and are wrong. findById(id).get() throws NoSuchElementException on an empty Optional, so a missing product becomes a 500 and a stack trace in the log. orElse(null) answers 200 with an empty body, so the client thinks it worked.
The service decides whether a product exists; the controller only translates the answer into HTTP. That split keeps both easy to test.
Fix the error
Fix the missing product
GET /api/v1/products/99 must answer 404, but it fails. Pick the line that fixes it.
Product 99 does not exist. The service returns an empty Optional.
Error
java.util.NoSuchElementException: No value present Response: 500 Internal Server Error
Next step
Check your understanding
12 quick questions