# ResponseEntity and Correct HTTP Status Codes

> What is ResponseEntity and when should you use it instead of returning an object directly from a controller method?

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-responseentity
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What is ResponseEntity and when should you use it instead of returning an object directly from a controller method?

## Answer

When you return a plain object from a controller method, Spring assumes everything went fine: status 200, default headers, and your object serialised as the body. That is fine for simple reads, but REST APIs are richer than that. Creating a resource should return 201 with a Location header pointing to it, deleting should return 204 with no body, and a missing resource should return 404. ResponseEntity is the tool that gives you full control over the three parts of an HTTP response: status code, headers, and body.

Think of it as an envelope. Returning a bare object is like handing over a letter and letting the post office pick the envelope. ResponseEntity lets you choose the envelope, the stamp, and what goes inside. It is generic, ResponseEntity<T>, where T is the body type, and you build it with static helpers: ResponseEntity.ok(body), ResponseEntity.created(uri).body(x), ResponseEntity.noContent().build(), ResponseEntity.notFound().build(), or ResponseEntity.status(HttpStatus.ACCEPTED).header("X-Job-Id", id).body(x).

Let's match common operations to status codes since interviewers ask exactly this. GET success is 200, and 404 if absent. POST creating something is 201 Created with a Location header. PUT or PATCH updates return 200 with the updated body or 204 with none. DELETE returns 204, or 200 if you return a message. Validation failures are 400, unauthenticated is 401, authenticated but forbidden is 403, a conflict such as a duplicate email is 409, and unexpected server errors are 500. Understanding 401 versus 403 is a frequent trick: 401 means we do not know who you are, 403 means we know who you are and you may not do this.

ResponseEntity is also how you send files and custom headers. For a PDF download you return ResponseEntity<Resource> with Content-Type application/pdf and a Content-Disposition attachment header. For caching you can add ETag or CacheControl. For conditional flows such as returning 304 Not Modified, the builder has that too.

Alternatives exist and are worth naming. @ResponseStatus(HttpStatus.CREATED) on a method sets a fixed status while letting you return a plain object, which is simple when the status is always the same. For error cases, throwing an exception handled by @ControllerAdvice is cleaner than returning ResponseEntity.notFound() in every method, because the service can throw and the controller stays focused on the happy path. A common pattern is to use ResponseEntity for the success variations that need headers or non-200 codes, and exceptions for failures.

One caution: do not build ResponseEntity in the service layer. That couples business logic to HTTP. Services return domain objects or throw domain exceptions, and the controller decides the HTTP form. Finally, for an Optional result, ResponseEntity.of(optional) is a neat shortcut which gives 200 with the value or 404 when empty.

## Code examples

### Status codes and headers done properly

```
@RestController
@RequestMapping("/api/jobs")
@RequiredArgsConstructor
class JobController {
    private final JobService service;

    @PostMapping
    public ResponseEntity<JobDto> create(@Valid @RequestBody CreateJobRequest req) {
        JobDto job = service.create(req);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}").buildAndExpand(job.id()).toUri();
        return ResponseEntity.created(location).body(job);           // 201 + Location
    }

    @GetMapping("/{id}")
    public ResponseEntity<JobDto> get(@PathVariable Long id) {
        return ResponseEntity.of(service.findById(id));               // 200 or 404
    }

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

    @GetMapping("/{id}/export")
    public ResponseEntity<byte[]> export(@PathVariable Long id) {
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=job.pdf")
                .body(service.pdf(id));
    }
}
```

Each response uses the semantically correct status code and headers.

## Key points

- ResponseEntity controls status, headers and body.
- POST creating a resource should return 201 with a Location header.
- 401 means unauthenticated, 403 means forbidden.
- Keep ResponseEntity in controllers, not services.

## Common follow-up questions

- Difference between 401 and 403?
- When would you use @ResponseStatus instead?
- What does ResponseEntity.of(Optional) do?

## Interview tips

- Match verbs to status codes confidently; it shows REST maturity.
- Say services should throw domain exceptions and not build HTTP responses.

## Concepts covered

ResponseEntity, HTTP Status, Headers, REST Semantics

Previous: [Global Exception Handling with @ControllerAdvice](https://www.internhack.in/learn/interview/spring-boot-interview/spring-controlleradvice-global-exception-handling) · Next: [Spring Data JPA: Repositories, Derived Queries and @Query](https://www.internhack.in/learn/interview/spring-boot-interview/spring-data-jpa-repositories-queries) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [JPA Relationships and the N+1 Query Problem](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-relationships-n-plus-one)
- [Lazy vs Eager Fetching and LazyInitializationException](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-lazy-vs-eager-fetching)
- [@Transactional: Propagation, Rollback Rules and Self-Invocation](https://www.internhack.in/learn/interview/spring-boot-interview/spring-transactional-pitfalls)
- [Hibernate First-Level and Second-Level Cache](https://www.internhack.in/learn/interview/spring-boot-interview/spring-hibernate-caching)
- [Spring Security Filter Chain and JWT Authentication Flow](https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-filter-chain-jwt)
- [Password Encoding with BCrypt in Spring Security](https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-password-encoding)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
