0
0
Spring Bootframework~5 mins

Returning different status codes in Spring Boot

Choose your learning style9 modes available
Introduction

We use different status codes to tell the user or client what happened with their request. It helps them understand if it worked, failed, or needs more action.

When you want to confirm a successful request with a 200 OK status.
When a requested resource is not found and you want to send a 404 Not Found.
When a client sends bad data and you want to respond with 400 Bad Request.
When a new resource is created and you want to send 201 Created.
When the user is not authorized and you want to send 401 Unauthorized.
Syntax
Spring Boot
return new ResponseEntity<>(body, HttpStatus.STATUS_CODE);
Use ResponseEntity to customize the HTTP status code and response body.
Common status codes include HttpStatus.OK, HttpStatus.NOT_FOUND, HttpStatus.BAD_REQUEST, HttpStatus.CREATED, and HttpStatus.UNAUTHORIZED.
Examples
Sends a 200 OK status with a simple success message.
Spring Boot
return new ResponseEntity<>("Success", HttpStatus.OK);
Sends a 404 Not Found status with a message.
Spring Boot
return new ResponseEntity<>("Not Found", HttpStatus.NOT_FOUND);
Sends a 201 Created status after creating a resource.
Spring Boot
return new ResponseEntity<>("Created", HttpStatus.CREATED);
Sample Program

This Spring Boot controller returns different status codes based on the item ID. It shows how to send 200 OK, 201 Created, 400 Bad Request, and 404 Not Found.

Spring Boot
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StatusCodeController {

    @GetMapping("/item/{id}")
    public ResponseEntity<String> getItem(@PathVariable int id) {
        if (id == 1) {
            return new ResponseEntity<>("Item found", HttpStatus.OK);
        } else if (id == 2) {
            return new ResponseEntity<>("Item created", HttpStatus.CREATED);
        } else if (id == 3) {
            return new ResponseEntity<>("Bad request", HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity<>("Item not found", HttpStatus.NOT_FOUND);
        }
    }
}
OutputSuccess
Important Notes

Always choose the status code that best matches what happened to help clients understand your response.

You can also use @ResponseStatus annotation for simple cases without a body.

Summary

Use ResponseEntity to send custom HTTP status codes and messages.

Common status codes include 200, 201, 400, 401, and 404.

Returning correct status codes improves communication with clients.