With an @RestController, simply returning a User gives you JSON. Yet you often see code that wraps the return value in ResponseEntity. Why go to the trouble of wrapping it?
The answer is simple: ResponseEntity is a class for building the status, headers, and body together. This article covers the builder API, how to add headers, when to use @ResponseStatus instead, and common pitfalls.
This article assumes Spring Boot 3.x (Spring Framework 6.x). The ResponseEntity API works the same way in Spring Boot 4.x (Spring Framework 7). The test-related packages and starters have changed, though, so you will need to adapt the test code.
The Controller Used in This Article
Let’s start with the skeleton. The class is annotated with @RequestMapping("/api/users"), so each method’s path is relative to it.
public record UserRequest(String name) {}
public record UserResponse(Long id, String name, long version, Instant updatedAt) {}
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
// 以降のメソッドはここに書く
}
What Is ResponseEntity?
ResponseEntity<T> extends HttpEntity<T>. The easiest way to think of it is as the headers and body held by HttpEntity, plus a status code.
// 直接返す。常に200(固定ステータスなら@ResponseStatusで変えられる)
// 条件によってステータスやヘッダーを変えにくい
@GetMapping("/{id}")
public UserResponse get(@PathVariable Long id) {
return userService.find(id);
}
// ResponseEntityで返す。ステータスとヘッダーをメソッド内で決められる
@GetMapping("/{id}")
public ResponseEntity<UserResponse> get(@PathVariable Long id) {
return ResponseEntity.ok()
.header("X-Request-Id", UUID.randomUUID().toString())
.body(userService.find(id));
}
In both cases, an HttpMessageConverter converts the body to JSON. If you want to know how that works, see the article on @ResponseBody and HttpMessageConverter.
Also note that since Spring Framework 6.0, getStatusCode() returns HttpStatusCode, and getStatusCodeValue() is deprecated. When you need the numeric value, use getStatusCode().value().
Builder API Basics
Here are the most commonly used factory methods.
| Method | Status | Body |
|---|---|---|
ok(body) / ok().build() | 200 | Yes |
created(URI) | 201 | Yes |
accepted() | 202 | Yes |
noContent() | 204 | No |
badRequest() | 400 | Yes |
notFound() | 404 | No |
status(...) | Any | Yes |
The return type decides whether you can add a body. ok() and created() return a BodyBuilder, so you can call body(). By contrast, noContent() and notFound() return a HeadersBuilder, which only has build(). That is why notFound().body(...) causes a compile error.
ResponseEntity.status(HttpStatus.CONFLICT).body(conflict);
ResponseEntity.status(HttpStatusCode.valueOf(422)).build(); // Spring 6のHttpStatusCode
ResponseEntity.accepted().build(); // 非同期処理を受け付けただけの202
You can also use the constructor, as in new ResponseEntity<>(body, headers, HttpStatus.OK). However, the builder is recommended because it shows at a glance what is being returned.
Returning 201 Created and Location from a POST
After creating a resource, the standard approach is to return 201 along with the URL of the new resource in the Location header.
@PostMapping
public ResponseEntity<UserResponse> create(@RequestBody @Valid UserRequest req) {
UserResponse saved = userService.create(req);
URI location = ServletUriComponentsBuilder.fromCurrentRequest() // /api/users
.path("/{id}")
.buildAndExpand(saved.id())
.toUri();
return ResponseEntity.created(location).body(saved);
}
fromCurrentRequest() starts from the current request URL (/api/users), so appending /{id} gives /api/users/1. Unlike string concatenation such as "/api/users/" + id, this keeps working if you configure a context path. Using @Valid requires spring-boot-starter-validation.
One caveat: when the app runs behind a proxy or load balancer, ServletUriComponentsBuilder does not interpret X-Forwarded-* headers by itself. Unless you set server.forward-headers-strategy=framework (or native) in application.properties, the Location header will contain the internal hostname or http.
$ curl -i -X POST localhost:8080/api/users \
-H 'Content-Type: application/json' -d '{"name":"taro"}'
HTTP/1.1 201
Location: http://localhost:8080/api/users/1
Content-Type: application/json
{"id":1,"name":"taro","version":1,"updatedAt":"2026-11-30T01:00:00Z"}
Adding Headers
Add any header with header(), or use headers(HttpHeaders) to pass several at once. Cache-related headers have dedicated methods, which are less error-prone than writing them as strings.
@GetMapping("/{id}")
public ResponseEntity<UserResponse> get(@PathVariable Long id) {
UserResponse user = userService.find(id);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(Duration.ofMinutes(10)).cachePublic())
.eTag("\"v" + user.version() + "\"")
.lastModified(user.updatedAt())
.contentType(MediaType.APPLICATION_JSON)
.body(user);
}
If you set eTag() on a GET response, Spring MVC compares it with the request’s If-None-Match header and returns 304 Not Modified when they match.
$ curl -i localhost:8080/api/users/1 -H 'If-None-Match: "v1"'
HTTP/1.1 304
ETag: "v1"
Cache-Control: max-age=600, public
For file downloads, add a Content-Disposition header. For non-ASCII filenames such as Japanese ones, pass a charset to ContentDisposition and it handles the encoding for you.
HttpHeaders headers = new HttpHeaders();
headers.setContentDisposition(ContentDisposition.attachment()
.filename("報告書.pdf", StandardCharsets.UTF_8)
.build());
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_PDF)
.body(resource);
A complete download implementation, including file storage, is covered in the article on file uploads and downloads.
Choosing the Type Parameter
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build();
}
@GetMapping
public ResponseEntity<List<UserResponse>> list(Pageable pageable) {
Page<UserResponse> page = userService.findAll(pageable);
return ResponseEntity.ok()
.header("X-Total-Count", String.valueOf(page.getTotalElements()))
.body(page.getContent());
}
Using ResponseEntity<Void> makes it clear from the type that there is no body. Note that the Pageable parameter requires Spring Data’s (spring-data-commons) web support on the classpath.
ResponseEntity<?> lets you return different types for success and failure, which looks convenient. But it weakens type safety, and springdoc-openapi can no longer infer the response schema. A better approach is to handle failures with exceptions and fix the return type to the success type. For how to keep error formats consistent, see the article on unified error responses.
Returning 200 or 404 with Optional
// 値があれば200、空なら404
return ResponseEntity.of(userRepository.findById(id));
// nullなら404(Spring Framework 6.0.5以降)
return ResponseEntity.ofNullable(userService.findOrNull(id));
// mapで書くと、ヘッダーを足したり別のステータスにしたりしやすい
return userRepository.findById(id)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
ofNullable was added in 6.0.5, so it is not available in earlier versions.
The 404 returned here has an empty body. If you want to return error details as JSON, it is cleaner to throw an exception and let ProblemDetail handle it than to build it yourself with ResponseEntity.
Direct Return Values vs. @ResponseStatus vs. ResponseEntity
| Situation | Recommendation |
|---|---|
| Always 200, just returning a body | Direct return value |
| Fixed 201 or 204 | @ResponseStatus |
| Need Location or cache-related headers | ResponseEntity |
| Status depends on conditions | ResponseEntity |
Writing the same create operation three ways makes the differences clear.
// 1. 直接戻り値:200になる
@PostMapping
public UserResponse create1(@RequestBody UserRequest req) { return userService.create(req); }
// 2. @ResponseStatus:201に固定。Locationは付かない
@PostMapping @ResponseStatus(HttpStatus.CREATED)
public UserResponse create2(@RequestBody UserRequest req) { return userService.create(req); }
// 3. ResponseEntity:201 + Location + ボディ
@PostMapping
public ResponseEntity<UserResponse> create3(@RequestBody UserRequest req) {
UserResponse saved = userService.create(req);
return ResponseEntity.created(locationOf(saved)).body(saved);
}
If you’re unsure, ask two questions: is the status fixed, and do you need headers? That settles it quickly. Wrapping everything in ResponseEntity just makes your code verbose. For how to use @ResponseStatus and how it differs from ResponseStatusException, see the article on @ResponseStatus.
An Empty Body on a 201 Comes from build()
return ResponseEntity.created(location).build(); // ボディなしの201
Checking with curl shows that Location is set but there is no body.
$ curl -i -X POST localhost:8080/api/users \
-H 'Content-Type: application/json' -d '{"name":"taro"}'
HTTP/1.1 201
Location: http://localhost:8080/api/users/1
Content-Length: 0
A common problem is a frontend that expects to read the new ID or timestamp right after creation and finds nothing. If you need a body, replace build() with body(saved).
return ResponseEntity.created(location).body(saved); // 201 + JSONボディ
If Location alone is enough, change the return type to ResponseEntity<Void> so the type shows there is no body. Base the choice on whether clients need the created state right away, and apply the same policy across your whole API.
When Combined with @ResponseStatus, ResponseEntity Wins
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<UserResponse> create(@RequestBody UserRequest req) {
return ResponseEntity.ok(userService.create(req));
}
Spring MVC first applies the @ResponseStatus status, then overwrites it with the status from ResponseEntity. Checking with MockMvc gives 200.
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"taro\"}"))
.andExpect(status().isOk()); // 201ではない
Also, if you set reason on @ResponseStatus, sendError is called and the ResponseEntity body is not returned. The status should be decided in one place only, so make it a rule never to put @ResponseStatus on methods that return ResponseEntity.
When Headers You Set Don’t Reach the Client
First, use curl -i to check whether the server is sending the header. If curl shows it, the server is not the problem.
If curl shows the header but response.headers.get("Location") returns null in a browser fetch, you are missing the CORS exposedHeaders setting. allowedHeaders applies to the request side, so be careful not to mix them up.
@Configuration
public class WebConfig implements WebMvcConfigurer { // WebMvcConfigurerを実装した設定クラス
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:5173")
.exposedHeaders("Location", "X-Total-Count");
}
}
For configuration when using Spring Security, see the article on CORS configuration.
A custom Filter might also be overwriting the value with setHeader. And if the controller doesn’t set Cache-Control, Spring Security automatically adds no-cache, no-store, max-age=0, must-revalidate (along with Pragma and Expires).
To find where a value changes, the quickest approach is to set a breakpoint in the suspect Filter’s doFilter and compare the response headers before and after chain.doFilter. If you suspect Spring Security, temporarily set http.headers(h -> h.cacheControl(c -> c.disable())) and see whether the value changes. It also helps to remember that once the body has been written and the response is committed, headers added afterward have no effect.
Testing with MockMvc
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mockMvc;
@MockitoBean UserService userService; // Boot 3.3以前は@MockBean
UserResponse taro = new UserResponse(1L, "taro", 1, Instant.parse("2026-11-30T01:00:00Z"));
@Test
void createReturns201WithLocation() throws Exception {
given(userService.create(any())).willReturn(taro);
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"taro\"}"))
.andExpect(status().isCreated())
.andExpect(header().string("Location", "http://localhost/api/users/1"))
.andExpect(jsonPath("$.id").value(1));
}
@Test
void deleteReturns204() throws Exception {
mockMvc.perform(delete("/api/users/1"))
.andExpect(status().isNoContent())
.andExpect(content().string(""));
}
@Test
void returns304WhenEtagMatches() throws Exception {
given(userService.find(1L)).willReturn(taro);
mockMvc.perform(get("/api/users/1").header("If-None-Match", "\"v1\""))
.andExpect(status().isNotModified());
}
}
@MockitoBean is available in Spring Boot 3.4 and later. For 3.3 and earlier, use @MockBean from the org.springframework.boot.test.mock.mockito package.
MockMvc’s default host is localhost, so Location becomes http://localhost/.... You can check for 404 with status().isNotFound(). The basics of @WebMvcTest are covered in the article on testing controllers with MockMvc.
Summary
ResponseEntity is the class to use when you want to decide the status or headers inside the method. If the status is fixed, @ResponseStatus is enough, and if it’s always 200, returning the value directly is enough.
Remember created(uri).body() for 201, noContent().build() for 204, and ResponseEntity.of(Optional) for choosing between 200 and 404, and you’ll rarely get stuck. For error responses, don’t build each one with ResponseEntity; keep them consistent with exception handling and ProblemDetail instead.
Notes:
- Code left unchanged: I didn’t touch the code blocks, as you asked, so their Japanese comments (e.g.
// 以降のメソッドはここに書く) and the報告書.pdffilename are still in Japanese. I can translate the comments if you want. - Wording change: “日本語のファイル名” became “non-ASCII filenames such as Japanese ones” to suit English readers.
- Links: All internal links still point to
/ja/blog/..., as you asked. If English versions exist, you may want them to point to/en/instead.