0
0
SpringbootHow-ToBeginner · 4 min read

How to Return Custom Status Code in Spring Boot

In Spring Boot, you can return a custom status code by using ResponseEntity to set the status explicitly or by annotating your controller method with @ResponseStatus. ResponseEntity gives full control over the response, while @ResponseStatus sets a fixed status for the method.
📐

Syntax

There are two main ways to return a custom status code in Spring Boot:

  • Using ResponseEntity: Wrap your response body and status code inside a ResponseEntity<T> object.
  • Using @ResponseStatus annotation: Annotate your controller method or exception class with @ResponseStatus(HttpStatus.STATUS_CODE) to set a fixed status code.

This lets you control HTTP status codes like 200 OK, 201 Created, 404 Not Found, or any other standard code.

java
public ResponseEntity<String> methodName() {
    return new ResponseEntity<>("body content", HttpStatus.CREATED);
}

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}
💻

Example

This example shows a Spring Boot REST controller method returning a custom status code 201 Created using ResponseEntity. It also shows how to use @ResponseStatus on an exception to return 404 Not Found.

java
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ItemController {

    @GetMapping("/items/{id}")
    public ResponseEntity<String> getItem(@PathVariable String id) {
        if ("42".equals(id)) {
            return new ResponseEntity<>("Item found", HttpStatus.OK);
        } else if ("new".equals(id)) {
            return new ResponseEntity<>("Item created", HttpStatus.CREATED);
        } else {
            throw new ItemNotFoundException("Item not found");
        }
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    static class ItemNotFoundException extends RuntimeException {
        public ItemNotFoundException(String message) {
            super(message);
        }
    }
}
Output
GET /items/42 -> HTTP 200 OK with body "Item found" GET /items/new -> HTTP 201 Created with body "Item created" GET /items/99 -> HTTP 404 Not Found with no body
⚠️

Common Pitfalls

Common mistakes when returning custom status codes in Spring Boot include:

  • Not using ResponseEntity when you want dynamic status codes, leading to always returning 200 OK.
  • Using @ResponseStatus on methods that need to return different status codes dynamically (it only sets a fixed status).
  • Throwing exceptions without @ResponseStatus or exception handlers, which results in default 500 Internal Server Error.

Always choose ResponseEntity for flexible status control and @ResponseStatus for fixed status on exceptions or simple cases.

java
/* Wrong way: This always returns 200 OK even if item not found */
@GetMapping("/items/{id}")
public String getItemWrong(@PathVariable String id) {
    if ("42".equals(id)) {
        return "Item found";
    } else {
        return "Item not found"; // status code is still 200 OK
    }
}

/* Right way: Use ResponseEntity to set status dynamically */
@GetMapping("/items/{id}")
public ResponseEntity<String> getItemRight(@PathVariable String id) {
    if ("42".equals(id)) {
        return new ResponseEntity<>("Item found", HttpStatus.OK);
    } else {
        return new ResponseEntity<>("Item not found", HttpStatus.NOT_FOUND);
    }
}
📊

Quick Reference

Summary tips for returning custom status codes in Spring Boot:

  • Use ResponseEntity<T> to return any status code with a response body.
  • Use @ResponseStatus on exceptions or methods for fixed status codes.
  • Throw exceptions annotated with @ResponseStatus to handle error status codes cleanly.
  • Remember that returning a plain object or string defaults to HTTP 200 OK.

Key Takeaways

Use ResponseEntity to return custom HTTP status codes dynamically in Spring Boot controllers.
Annotate exceptions or methods with @ResponseStatus for fixed status codes.
Returning plain objects defaults to HTTP 200 OK, so use ResponseEntity for other codes.
Throw exceptions with @ResponseStatus to cleanly return error status codes.
Avoid mixing @ResponseStatus and ResponseEntity in the same method for clarity.