ResponseEntity and Status Codes
Returning the right status code is as important as returning the right data.
The Restaurant Waiter Analogy:
You place an order at a restaurant in Hyderabad.
- If the waiter brings the food, they smile (Data found -> 200 OK).
- If you ask for a dish that isn't on the menu, they say "Sorry, not available" (Wrong endpoint or ID -> 404 Not Found).
- If you try to pay with an expired credit card, they say "Payment failed" (Bad input -> 400 Bad Request).
ResponseEntity gives you the control of the waiter. You get to decide exactly what status code to send back to the client, along with the data.
- ResponseEntity<T>: A wrapper class that represents the entire HTTP response. It holds the body (data), the status code, and headers.
- Common Codes:
200 OK: Success (Default).201 CREATED: Usually returned after a POST request.404 NOT FOUND: Resource doesn't exist.400 BAD REQUEST: Client sent invalid data.500 INTERNAL SERVER ERROR: Your Java code crashed.
package com.devinhyderabad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
@RequestMapping("/api/books")
class BookController {
private List books = new ArrayList<>(List.of(
new Book(101, "Book 1", "Sai")
));
// 1. GET: Return 404 if book not found, 200 if found
@GetMapping("/{id}")
public ResponseEntity getBook(@PathVariable int id) {
for (Book book : books) {
if (book.getId() == id) {
return ResponseEntity.ok(book); // 200 OK with body
}
}
return ResponseEntity.notFound().build(); // 404 Not Found, empty body
}
// 2. POST: Return 201 Created
@PostMapping
public ResponseEntity createBook(@RequestBody Book newBook) {
newBook.setId(102);
books.add(newBook);
// Return 201 CREATED status with the newly created object as body
return ResponseEntity.status(HttpStatus.CREATED).body(newBook);
}
}
class Book {
private int id;
private String title;
private String author;
public Book() {}
public Book(int id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
} Test the GET /api/books/999 in Postman. You will now see 404 Not Found at the bottom instead of 200 OK.
Interview Question: "Why should you use ResponseEntity instead of just returning the object?"
Answer: Returning the object ties you to a 200 OK status always. ResponseEntity gives the developer fine-grained control over the HTTP response. It allows us to return custom status codes (like 201 for creation, 404 for not found) and add custom HTTP headers (like Location for newly created resources), which is crucial for proper RESTful API design.
Enterprise Note: Frontend frameworks like Angular heavily rely on HTTP status codes. If your API returns 401 Unauthorized, the Angular HTTP interceptor will automatically redirect the user to the login page. If you return 200 OK with an error message in the body, the interceptor won't catch it, breaking the security flow.
Key Takeaways
- ✅ ResponseEntity controls the full HTTP response: body, status, headers
- ✅ Return 201 CREATED after successful POST, not just 200 OK
- ✅ Return 404 NOT FOUND when a resource doesn't exist
- ✅ Frontend frameworks rely on correct HTTP status codes for security flows
Want to track your progress?
Log in to save your place and pick up where you left off.
Progress track karna chahte ho?
Login karo apni progress save karne ke liye aur jahan chhoda tha wahan se shuru karo.
Login