Discover how a simple change can make your web service speak clearly to every user and system.
Why Returning different status codes in Spring Boot? - Purpose & Use Cases
Imagine building a web service where you must tell users if their request succeeded, failed, or if something went wrong. You try to do this by writing many if-else checks and printing messages manually.
Manually managing status codes is confusing and error-prone. You might forget to send the right code, causing clients to misunderstand the response. It's hard to keep track of all possible outcomes and update them consistently.
Spring Boot lets you return different HTTP status codes easily by using built-in annotations and response objects. This makes your code cleaner and ensures clients get clear, correct signals about what happened.
if (error) { return "Error happened"; } else { return "Success"; }
@GetMapping
public ResponseEntity<String> get() {
if (error) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error happened");
}
return ResponseEntity.ok("Success");
}You can clearly communicate success, failure, or other states to users and systems, making your API reliable and easy to use.
When a user submits a form, your service can return 200 OK if all is good, 400 Bad Request if data is missing, or 500 Internal Server Error if something unexpected happens.
Manual status handling is confusing and risky.
Spring Boot simplifies returning correct HTTP codes.
Clear status codes improve communication with clients.
Practice
Solution
Step 1: Understand the purpose of ResponseEntity
ResponseEntity is a Spring class that allows you to control the HTTP status code, headers, and body of the response.Step 2: Identify the correct class for status codes
HttpStatusCode, HttpResponse, and StatusCode are not standard Spring Boot classes for returning responses with status codes.Final Answer:
ResponseEntity -> Option AQuick Check:
Use ResponseEntity to return status codes [OK]
- Confusing ResponseEntity with HttpStatusCode
- Trying to return status codes without ResponseEntity
- Using non-existent classes like HttpResponse
Solution
Step 1: Check the syntax for ResponseEntity with status and body
The method ResponseEntity.status(404).body("Not Found") correctly sets the status and body.Step 2: Identify incorrect syntax options
B uses a constructor with an int 404 instead of HttpStatus.NOT_FOUND. C uses an int instead of HttpStatus enum. D is not a valid constructor call.Final Answer:
return ResponseEntity.status(404).body("Not Found"); -> Option CQuick Check:
Use ResponseEntity.status().body() for custom status [OK]
- Using int instead of HttpStatus enum
- Incorrect constructor usage
- Missing method chaining for status and body
public ResponseEntity<String> getUser(boolean found) {
if (found) {
return ResponseEntity.ok("User found");
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
}
}Solution
Step 1: Analyze the if condition
If found is true, the method returns ResponseEntity.ok("User found"), which means HTTP 200.Step 2: Analyze the else condition
If found is false, it returns ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"), which means HTTP 404.Final Answer:
200 if found is true, 404 if false -> Option DQuick Check:
ResponseEntity.ok = 200, status(HttpStatus.NOT_FOUND) = 404 [OK]
- Mixing up true/false branches
- Assuming default status 200 always
- Confusing status codes with messages
public ResponseEntity<String> createItem() {
return new ResponseEntity<>("Item created", 201);
}Solution
Step 1: Check ResponseEntity constructor parameters
The constructor expects a body and an HttpStatus enum, not an int.Step 2: Identify the incorrect use of status code
Passing 201 as int causes a compilation error; should use HttpStatus.CREATED instead.Final Answer:
Using int 201 instead of HttpStatus enum -> Option BQuick Check:
Use HttpStatus.CREATED, not int 201 [OK]
- Passing int instead of HttpStatus enum
- Forgetting to import HttpStatus
- Assuming String body is invalid
Solution
Step 1: Verify correct use of HttpStatus enums
public ResponseEntity<String> addUser(boolean validInput, boolean loggedIn) { if (!loggedIn) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized"); } if (!validInput) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid input"); } return ResponseEntity.status(HttpStatus.CREATED).body("User created"); } uses HttpStatus.UNAUTHORIZED, HttpStatus.BAD_REQUEST, and HttpStatus.CREATED enums correctly.Step 2: Check logical order and syntax
This code checks !loggedIn first, then !validInput, then returns 201. Options B, C, and D misuse status codes or pass ints to constructors instead of using HttpStatus enums.Final Answer:
Uses HttpStatus enums with correct logic: !loggedIn (401), !validInput (400), then 201 -> Option AQuick Check:
Use HttpStatus enums and correct logic order [OK]
- Passing int status codes instead of HttpStatus enums
- Mixing up 400 and 401 status codes
- Incorrect order of condition checks
Ready to prove it?
Pass the test and this pattern moves unknown
