Spring Boot – ResponseEntity & HTTP Response Codes

Spring Boot – ResponseEntity & HTTP Response Codes


1. What is an HTTP Response?

From page 1, a response has 3 parts:

  1. Status Code – e.g. 200, 404, 500
  2. Headers – metadata (content-type, token, etc.)
  3. Body – actual response data

2. ResponseEntity in Spring Boot

ResponseEntity<T> lets you control status + headers + body.

Basic Example (page 1)

@GetMapping("/get-user")
public ResponseEntity<String> getUser() {
    return ResponseEntity.ok("My response body");
}

With Headers + Status (page 1)

@GetMapping("/get-user")
public ResponseEntity<String> getUser() {

    HttpHeaders headers = new HttpHeaders();
    headers.add("My-Header1", "SomeValue1");
    headers.add("My-Header2", "SomeValue2");

    return ResponseEntity
            .status(HttpStatus.OK)
            .headers(headers)
            .body("My response body");
}

Important:
status(), headers() return Builder objects.
body() must be last, because it finalizes the response.


3. No Body? Use build() (page 1)

@GetMapping("/get-user")
public ResponseEntity<Void> getUser() {

    HttpHeaders headers = new HttpHeaders();
    headers.add("My-Header1", "SomeValue1");

    return ResponseEntity
            .status(HttpStatus.OK)
            .headers(headers)
            .build();   // no body
}

4. Default Status Code

From page 1:

If you return an object directly, Spring returns 200 OK by default.

@GetMapping("/get-user")
public User getUser() {
    return new User("XYZ", 20); // 200 OK
}

5. @ResponseBody vs @RestController (page 2)

@ResponseBody

Tells Spring:

“Return this value as response body, not as a View name.”

@RestController

Internally includes:

@Controller
@ResponseBody

So every method automatically returns JSON/body.


Problem Example (page 2)

@Controller
public class UserController {

    @GetMapping("/get-user")
    public String getUser() {
        return "XYZ";
    }
}

❌ Spring will try to find XYZ.html view → 404 error
Because return value is treated as view name.


6. HTTP Status Code Categories (page 3)

Range Meaning
1xx Informational
2xx Success
3xx Redirection
4xx Client Error
5xx Server Error

7. Important 2xx Codes (page 3)

Code Meaning Use
200 OK Success GET, normal POST
201 Created New resource created POST
202 Accepted Processing later Async
204 No Content No body DELETE
206 Partial Content Partial result Large data

8. Important 3xx Codes (page 3)

Code Use
301 Moved Permanently Old → New API
308 Permanent Redirect Same as 301 but method preserved
304 Not Modified Cache optimization

9. Important 4xx Codes (page 3–4)

Code Meaning
400 Bad Request Invalid input
401 Unauthorized No auth
403 Forbidden No permission
404 Not Found Resource missing
405 Method Not Allowed Wrong HTTP method
422 Unprocessable Entity Business validation failed
429 Too Many Requests Rate limit exceeded

10. Important 5xx Codes (page 4)

Code Meaning
500 Internal Server Error Generic server failure
501 Not Implemented API not ready
502 Bad Gateway Reverse proxy failure

11. 100 Continue (page 4)

Used when client sends:

Expect: 100-continue

Flow:

  1. Client asks if server is ready
  2. Server validates headers
  3. Server replies 100 Continue
  4. Client sends body
  5. Server processes request

EXTRA INTERVIEW NOTES

ResponseEntity vs @ResponseStatus

ResponseEntity @ResponseStatus
Dynamic Static
Can change per request Fixed
Supports headers No

IN-DEPTH INTERVIEW Q&A

Q1. Why use ResponseEntity instead of returning Object?
👉 To control status, headers, body.

Q2. Why body() must be last?
👉 It finalizes the builder.

Q3. When use 204 vs 200?
👉 204 when no response body.

Q4. 401 vs 403?
👉 401 = not authenticated
👉 403 = authenticated but forbidden

Q5. 422 vs 400?
👉 400 = invalid format
👉 422 = business rule failed


  •  

Leave a Reply