Hackforge Academy

Category: java

how to send custom status code in spring boot

Published on 22 Apr 2026

Explanation

Use ResponseEntity to return custom HTTP status codes along with response body. This is the most common and flexible approach in Spring Boot REST APIs.

Code:

@GetMapping("/ok")
public ResponseEntity<String> success() {
  return ResponseEntity.status(
HttpStatus.OK).body("Success"
);
}

Explanation

Return 201 CREATED when a new resource is successfully created, such as saving data into a database.

Code:

@PostMapping("/create")
public ResponseEntity<String> create() {
  return ResponseEntity.status(
HttpStatus.CREATED).body(
"Resource created successfully
");
}

Explanation

Return 400 BAD REQUEST when user input is invalid or missing required parameters.

Code:

@GetMapping("/bad")
public ResponseEntity<String> badRequest() {
  return ResponseEntity.status(
HttpStatus.BAD_REQUEST).body(
"Invalid request data");
}

Explanation

Return 404 NOT FOUND when requested data does not exist in the database.

Code:

@GetMapping("/user/{id}")
public ResponseEntity<String> getUser(
@PathVariable int id) {
  return ResponseEntity.status(
HttpStatus.NOT_FOUND).body("User not found");
}

Explanation

Return 500 INTERNAL SERVER ERROR when unexpected exceptions occur in the application.

Code:

@GetMapping("/error")
public ResponseEntity<String> serverError() {
  return ResponseEntity.status(
HttpStatus.INTERNAL_SERVER_ERROR).body(
"Something went wrong");
}

Explanation

Use @ResponseStatus annotation to directly assign a status code to a controller method.

Code:

@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/delete/{id}")
public void deleteUser(
@PathVariable int id) {
}

Explanation

Use exception handling with @RestControllerAdvice to return different status codes globally across the application.

Code:

@RestControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(Exception.class)
  public ResponseEntity<String> 
handleException(Exception ex) {
    return ResponseEntity.status(
HttpStatus.INTERNAL_SERVER_ERROR)
                         .body(
ex.getMessage());
  }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community