00:00

ResponseEntity in Spring Boot

Last updated:

ResponseEntity in Spring Boot is the class you return from a controller method when you want full control over the HTTP response: the status code, the headers and the body. Returning a plain object always gives 200 OK with a JSON body; returning a ResponseEntity lets the same method say 201 Created with a Location header, 204 No Content, 304 Not Modified or 404 Not Found, which is what well-designed REST APIs need.

This tutorial explains what ResponseEntity contains, walks through its builder methods, and builds a complete product API that uses the right status and headers for each operation, including ETag caching and ProblemDetail errors. It finishes with tests written with MockMvcTester and a comparison with @ResponseStatus.

1. What Is ResponseEntity?

ResponseEntity<T> (org.springframework.http) represents a whole HTTP response. It extends HttpEntity<T>, which holds headers and a body, and adds a status code. The type parameter T is the body type: ResponseEntity<ProductResponse> carries a product, ResponseEntity<Void> carries no body.

PartTypeExample
Status codeHttpStatusCode201 Created
HeadersHttpHeadersLocation: /api/products/KB-100, ETag: "3"
BodyT, written as JSON by default{"sku":"KB-100","name":"Mechanical keyboard"}
Analogy: Returning a plain object is like handing over a parcel: the courier decides the label. Returning a ResponseEntity is like filling in the label yourself: delivery status, special instructions and the parcel, all chosen by you.

2. Why Use ResponseEntity

HTTP clients, proxies and browsers act on status codes and headers, not only on the body. A good REST API uses them deliberately:

OperationRecommended responseNeeds ResponseEntity?
Read a resource200 OK with body, optionally ETag and Cache-ControlOnly for headers
Create a resource201 Created with Location header and bodyYes
Update a resource200 OK with body, or 204 No ContentFor 204, yes (or @ResponseStatus)
Delete a resource204 No ContentYes (or @ResponseStatus)
Start a long-running job202 Accepted with Location of a status resourceYes
Resource unchanged since last read304 Not Modified, no bodyYes (ETag)

The choice of status codes for REST operations is covered in building a REST API.

3. How Spring MVC Writes a ResponseEntity

How Spring MVC turns a ResponseEntity into an HTTP responseA controller method returns a ResponseEntity. Spring MVC's HttpEntityMethodProcessor takes it, sets the status code and copies the headers to the servlet response. For GET and HEAD requests it compares the ETag or Last-Modified header with the request's conditional headers and sends 304 Not Modified without a body when they match. Otherwise an HttpMessageConverter, usually Jackson, writes the body as JSON according to the Accept header. Controller returns ResponseEntity HttpEntity- MethodProcessor status + headers ETag matches If-None-Match? 304, no body Message converter body to JSON (Jackson) HTTP response status line, headers, body
The status and headers are applied first; for conditional GETs Spring may answer 304; otherwise a message converter writes the body.

The automatic 304 handling is a useful bonus: if your GET response has an ETag and the client sends the same value in If-None-Match, Spring answers 304 Not Modified with an empty body, without extra code.

4. ResponseEntity Builder Methods

Create responses with the static builder methods rather than constructors; they read like the HTTP response they produce.

MethodStatusNotes
ResponseEntity.ok(body)200Shortcut for ok().body(body)
ResponseEntity.ok()200Builder: add headers, then body(...)
ResponseEntity.created(uri)201Sets the Location header
ResponseEntity.accepted()202For work that continues in the background
ResponseEntity.noContent()204Finish with build(); no body
ResponseEntity.badRequest()400 
ResponseEntity.notFound()404Finish with build()
ResponseEntity.unprocessableContent()422Spring Framework 7 name; unprocessableEntity() is deprecated
ResponseEntity.internalServerError()500 
ResponseEntity.status(code)AnyAccepts an HttpStatus or an int
ResponseEntity.of(optional)200 or 404200 with the value, or 404 with an empty body if the Optional is empty
ResponseEntity.ofNullable(body)200 or 404Same idea for a possibly null value (since Spring Framework 6.0.5)
ResponseEntity.of(problemDetail)From the problemBuilds an error response from a ProblemDetail (since 6.0)
Builder examples
return ResponseEntity.ok(product);

return ResponseEntity.created(location).body(product);

return ResponseEntity.noContent().build();

return ResponseEntity.status(HttpStatus.ACCEPTED)
        .location(URI.create("/api/exports/" + jobId))
        .build();

5. Setting Response Headers

The builder has shortcuts for common headers and generic methods for anything else:

Header examples
return ResponseEntity.ok()
        .eTag(String.valueOf(product.version()))                 // quoted automatically
        .lastModified(product.updatedAt())
        .cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)).cachePublic())
        .contentType(MediaType.APPLICATION_JSON)
        .header("X-Stock-Level", String.valueOf(product.stock()))
        .body(ProductResponse.from(product));

For several headers at once, use headers(h -> ...) with an HttpHeaders consumer. Custom headers should be documented, and should not be needed for anything a standard header already covers.

6. A Complete Example: A Product API

6.1 Domain and DTOs

Product.java
package com.javabytechie.shop.product;

import java.math.BigDecimal;

public record Product(String sku, String name, BigDecimal price, int stock, long version) {

    Product withPriceAndStock(BigDecimal newPrice, int newStock) {
        return new Product(sku, name, newPrice, newStock, version + 1);
    }
}
ProductDtos.java
package com.javabytechie.shop.product;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.PositiveOrZero;
import java.math.BigDecimal;

public final class ProductDtos {

    private ProductDtos() {
    }

    public record CreateProductRequest(@NotBlank String sku, @NotBlank String name,
                                       @Positive BigDecimal price, @PositiveOrZero int stock) {
    }

    public record UpdateProductRequest(@Positive BigDecimal price, @PositiveOrZero int stock) {
    }

    public record ProductResponse(String sku, String name, BigDecimal price, int stock) {

        static ProductResponse from(Product product) {
            return new ProductResponse(product.sku(), product.name(), product.price(), product.stock());
        }
    }
}

6.2 Service and Exceptions

ProductService.java
package com.javabytechie.shop.product;

import com.javabytechie.shop.product.ProductDtos.CreateProductRequest;
import com.javabytechie.shop.product.ProductDtos.UpdateProductRequest;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    private static final Logger log = LoggerFactory.getLogger(ProductService.class);
    private final Map<String, Product> products = new ConcurrentHashMap<>();

    public Product create(CreateProductRequest request) {
        Product product = new Product(request.sku(), request.name(), request.price(), request.stock(), 1);
        if (products.putIfAbsent(product.sku(), product) != null) {
            throw new DuplicateProductException(product.sku());
        }
        log.info("Created product {}", product.sku());
        return product;
    }

    public Product find(String sku) {
        return findOptional(sku).orElseThrow(() -> new ProductNotFoundException(sku));
    }

    public Optional<Product> findOptional(String sku) {
        return Optional.ofNullable(products.get(sku));
    }

    public Product update(String sku, UpdateProductRequest request) {
        Product updated = products.computeIfPresent(sku,
                (key, current) -> current.withPriceAndStock(request.price(), request.stock()));
        if (updated == null) {
            throw new ProductNotFoundException(sku);
        }
        return updated;
    }

    public void delete(String sku) {
        if (products.remove(sku) == null) {
            throw new ProductNotFoundException(sku);
        }
    }
}
ProductExceptions.java
package com.javabytechie.shop.product;

class ProductNotFoundException extends RuntimeException {
    ProductNotFoundException(String sku) {
        super("Product " + sku + " was not found");
    }
}

class DuplicateProductException extends RuntimeException {
    DuplicateProductException(String sku) {
        super("Product " + sku + " already exists");
    }
}

6.3 The Controller

ProductController.java
package com.javabytechie.shop.product;

import com.javabytechie.shop.product.ProductDtos.CreateProductRequest;
import com.javabytechie.shop.product.ProductDtos.ProductResponse;
import com.javabytechie.shop.product.ProductDtos.UpdateProductRequest;
import jakarta.validation.Valid;
import java.net.URI;
import java.time.Duration;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    private final ProductService service;

    public ProductController(ProductService service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest request) {
        Product product = service.create(request);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{sku}")
                .buildAndExpand(product.sku())
                .toUri();
        return ResponseEntity.created(location).body(ProductResponse.from(product));
    }

    @GetMapping("/{sku}")
    public ResponseEntity<ProductResponse> find(@PathVariable String sku) {
        Product product = service.find(sku);
        return ResponseEntity.ok()
                .eTag(String.valueOf(product.version()))
                .cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)))
                .body(ProductResponse.from(product));
    }

    @GetMapping("/lookup/{sku}")
    public ResponseEntity<ProductResponse> lookup(@PathVariable String sku) {
        return ResponseEntity.of(service.findOptional(sku).map(ProductResponse::from));
    }

    @PutMapping("/{sku}")
    public ResponseEntity<ProductResponse> update(@PathVariable String sku,
                                                  @Valid @RequestBody UpdateProductRequest request) {
        Product product = service.update(sku, request);
        return ResponseEntity.ok()
                .eTag(String.valueOf(product.version()))
                .body(ProductResponse.from(product));
    }

    @DeleteMapping("/{sku}")
    public ResponseEntity<Void> delete(@PathVariable String sku) {
        service.delete(sku);
        return ResponseEntity.noContent().build();
    }
}

ServletUriComponentsBuilder.fromCurrentRequest() builds the Location from the incoming request, so it is correct behind any host name or context path. The lookup endpoint shows ResponseEntity.of(Optional); section 7 explains why the main find endpoint uses an exception instead.

6.4 Try It

Terminal
curl -i -X POST localhost:8080/api/products -H "Content-Type: application/json" \
     -d '{"sku":"KB-100","name":"Mechanical keyboard","price":79.99,"stock":12}'
curl -i localhost:8080/api/products/KB-100
curl -i localhost:8080/api/products/KB-100 -H 'If-None-Match: "1"'
curl -i -X DELETE localhost:8080/api/products/KB-100
Responses (headers shortened)
HTTP/1.1 201
Location: http://localhost:8080/api/products/KB-100
Content-Type: application/json
{"sku":"KB-100","name":"Mechanical keyboard","price":79.99,"stock":12}

HTTP/1.1 200
ETag: "1"
Cache-Control: max-age=300
Content-Type: application/json
{"sku":"KB-100","name":"Mechanical keyboard","price":79.99,"stock":12}

HTTP/1.1 304
ETag: "1"

HTTP/1.1 204

The third call sent the ETag from the second response, so Spring answered 304 without a body, saving bandwidth. After a PUT, the version and therefore the ETag change, and the next conditional request gets the new data.

7. Returning Errors: Exceptions and ProblemDetail

You could return ResponseEntity.notFound().build() from every method, but then each endpoint decides its own error format, and the service layer must return Optionals everywhere. A cleaner design: the service throws, and one @RestControllerAdvice turns exceptions into ProblemDetail responses (the RFC 9457 format), using ResponseEntity where it needs headers:

ProductErrorHandler.java
package com.javabytechie.shop.product;

import java.net.URI;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
class ProductErrorHandler {

    @ExceptionHandler(ProductNotFoundException.class)
    ProblemDetail notFound(ProductNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(DuplicateProductException.class)
    ResponseEntity<ProblemDetail> duplicate(DuplicateProductException ex) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
        problem.setType(URI.create("https://javabytechie.com/problems/duplicate-product"));
        return ResponseEntity.of(problem).header("Retry-After", "0").build();
    }
}
Response for GET /api/products/XX-999
HTTP/1.1 404
Content-Type: application/problem+json

{"type":"about:blank","title":"Not Found","status":404,"detail":"Product XX-999 was not found","instance":"/api/products/XX-999"}

Compare this with the lookup endpoint: ResponseEntity.of(Optional) returns a 404 with an empty body, so clients get no explanation. Use it for simple internal endpoints; for public APIs, prefer one error format everywhere. More options are in exception handling in Spring Boot.

8. Testing ResponseEntity Responses

A @WebMvcTest loads only the web layer. MockMvcTester gives fluent AssertJ assertions on status, headers and JSON. The service is replaced with a Mockito mock through @MockitoBean.

ProductControllerTest.java
package com.javabytechie.shop.product;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import com.javabytechie.shop.product.ProductDtos.CreateProductRequest;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.assertj.MockMvcTester;

@WebMvcTest(ProductController.class)
class ProductControllerTest {

    @Autowired
    MockMvcTester mvc;

    @MockitoBean
    ProductService service;

    private final Product keyboard = new Product("KB-100", "Mechanical keyboard", new BigDecimal("79.99"), 12, 3);

    @Test
    void createReturns201WithLocation() {
        when(service.create(any(CreateProductRequest.class))).thenReturn(keyboard);

        assertThat(mvc.post().uri("/api/products").contentType(MediaType.APPLICATION_JSON)
                .content("""
                        {"sku":"KB-100","name":"Mechanical keyboard","price":79.99,"stock":12}
                        """))
                .hasStatus(HttpStatus.CREATED)
                .hasHeader("Location", "http://localhost/api/products/KB-100")
                .bodyJson().extractingPath("$.sku").isEqualTo("KB-100");
    }

    @Test
    void getReturnsETagAndThen304ForTheSameETag() {
        when(service.find("KB-100")).thenReturn(keyboard);

        assertThat(mvc.get().uri("/api/products/KB-100"))
                .hasStatus(HttpStatus.OK)
                .hasHeader("ETag", "\"3\"");

        assertThat(mvc.get().uri("/api/products/KB-100").header("If-None-Match", "\"3\""))
                .hasStatus(HttpStatus.NOT_MODIFIED);
    }

    @Test
    void missingProductReturnsProblemDetail() {
        when(service.find("XX-999")).thenThrow(new ProductNotFoundException("XX-999"));

        assertThat(mvc.get().uri("/api/products/XX-999"))
                .hasStatus(HttpStatus.NOT_FOUND)
                .bodyJson().extractingPath("$.detail").isEqualTo("Product XX-999 was not found");
    }
}
Version note: @MockitoBean (Spring Framework 6.2) replaced Spring Boot's @MockBean, which was deprecated in Spring Boot 3.4 and removed in 4.0. In Spring Boot 4, @WebMvcTest is in org.springframework.boot.webmvc.test.autoconfigure and needs the spring-boot-starter-webmvc-test dependency. See Spring Boot testing.

9. ResponseEntity vs @ResponseStatus vs Plain Objects

ApproachStatusHeadersBest for
Return the objectAlways 200None of your ownSimple reads with no special headers
@ResponseStatus(HttpStatus.CREATED) on the methodFixed per methodNone of your ownFixed statuses such as 201 or 204 without headers
ResponseEntityChosen at runtimeAnyLocation, ETag, caching, or a status that depends on the outcome

All three can live in one controller. Pick the simplest one that expresses the response; do not wrap every method in ResponseEntity.ok(...) just for consistency.

10. Common Mistakes

  • Returning 200 for everything, including errors with an "error" field in the body. Clients and monitoring then cannot tell success from failure.
  • Using ResponseEntity<?> or ResponseEntity<Object> to return a product on success and an error map on failure. Keep the success type specific and handle errors with exceptions.
  • Building Location URLs by hand with a hard-coded host. Use ServletUriComponentsBuilder.
  • Adding a body to 204 or 304 responses. These statuses must not have a body.
  • Returning ResponseEntity from services. HTTP belongs in the controller; see Spring Boot architecture.

11. Best Practices

  • Return 201 Created with a Location header for every create operation.
  • Return 204 No Content for deletes and for updates that have nothing to return.
  • Add an ETag to cacheable GET responses and let Spring answer 304 automatically.
  • Throw exceptions for errors and map them once to ProblemDetail in a controller advice.
  • Keep body types specific, such as ResponseEntity<ProductResponse>, never ResponseEntity<?>.
  • Use the builder methods instead of constructors for readable code.
  • Assert status and headers in tests, not just the body.

12. Summary

ResponseEntity in Spring Boot gives a controller full control over the HTTP status, headers and body. Use its builders to return 201 Created with a Location, 204 No Content for deletes, 202 Accepted for background work and ETag and Cache-Control headers for reads, where Spring answers 304 Not Modified by itself. Keep services free of HTTP types, throw exceptions for errors and translate them once into ProblemDetail responses, and use ResponseEntity.of(Optional) only where an empty 404 is acceptable. Test the status and headers with MockMvcTester, and your API will speak HTTP the way clients expect.

13. References