Lesson 5 of 12 · 10 min · Building REST APIs
HTTP status codes, ResponseEntity and DTOs
What you will learn
- The HTTP status codes a REST API uses and what each means
- Return the right status with
ResponseEntityand@ResponseStatus - Create resources with
201 Createdand aLocationheader - Why you should not expose JPA entities in the API
- Design request and response DTOs and map to and from entities
In simple words
Every answer from a web server starts with a three-digit number that tells the caller what happened: 200 means "fine", 404 means "not found", 500 means "the server broke". Using the right number lets apps react correctly without reading the message. DTOs (data transfer objects) are the forms you hand over the counter: a separate, simple shape for what goes in and out of the API, so your internal database objects can change without breaking callers.
Words to know
- Status code: a number in the HTTP response saying whether the request worked.
- ResponseEntity: a Spring class that lets you set the status, headers and body of a response.
- DTO (data transfer object): a simple object that carries data across a boundary, such as an API.
- Entity: an object mapped to a database table (JPA).
Status codes to know
| Code | Name | Use it when |
|---|---|---|
| 200 | OK | a successful GET, PUT or PATCH that returns a body |
| 201 | Created | a POST created a resource; send a Location header |
| 202 | Accepted | work was accepted and will finish later |
| 204 | No Content | success with no body, typically DELETE or PUT |
| 400 | Bad Request | the request is malformed or invalid (validation errors) |
| 401 | Unauthorized | not authenticated (no or bad credentials) |
| 403 | Forbidden | authenticated but not allowed |
| 404 | Not Found | the resource does not exist |
| 405 | Method Not Allowed | the resource does not support that method |
| 409 | Conflict | a state conflict, such as a duplicate or a version mismatch |
| 415 | Unsupported Media Type | the body format is not supported |
| 422 | Unprocessable Content | well-formed but semantically invalid (some teams use this instead of 400 for validation) |
| 429 | Too Many Requests | rate limit exceeded |
| 500 | Internal Server Error | an unexpected bug on the server |
| 502/503/504 | Bad gateway, unavailable, timeout | a dependency or the service is down or slow |
Families: 2xx success, 3xx redirection, 4xx the client is at fault, 5xx the server is at fault. Do not return 200 with an error message in the body, and do not return 500 for a bad request. Clients, monitoring tools and retry logic all depend on the code.
Setting the status in Spring
ResponseEntity gives full control:
@GetMapping("/{id}")
public ResponseEntity<OrderResponse> get(@PathVariable long id) {
return service.find(id) // Optional<OrderResponse>
.map(ResponseEntity::ok) // 200 with body
.orElseGet(() -> ResponseEntity.notFound().build()); // 404
}
@PostMapping
public ResponseEntity<OrderResponse> create(@RequestBody CreateOrderRequest request) {
OrderResponse created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(created.id()).toUri();
return ResponseEntity.created(location).body(created); // 201 + Location: /orders/101
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable long id) {
service.delete(id);
return ResponseEntity.noContent().build(); // 204
}
@ResponseStatus fixes the status of a method or exception when it is always the same:
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public OrderResponse create(@RequestBody CreateOrderRequest request) { ... }
@ResponseStatus(HttpStatus.NOT_FOUND)
public class OrderNotFoundException extends RuntimeException { ... }
Prefer throwing a domain exception and mapping it centrally (the exception handlers lesson) over returning ResponseEntity.notFound() from every controller. A returned void or object defaults to 200. ResponseStatusException (throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Order 5 not found")) is a quick option for small apps.
Location header on 201: the standard way to tell the caller where the new resource lives, so they can fetch it. PUT versus PATCH: PUT replaces the whole resource (idempotent); PATCH changes some fields.
Why not expose entities
An entity is shaped for the database:
@Entity
class Order {
@Id @GeneratedValue Long id;
@ManyToOne(fetch = LAZY) Customer customer;
@OneToMany(mappedBy = "order") List<OrderLine> lines;
String internalNotes; // not for customers
LocalDateTime deletedAt; // internal flag
}
Returning it directly from a controller causes real problems:
- Leaking data: internal fields, password hashes and notes go out unless every field is annotated away.
- Tight coupling: renaming a column or adding a relationship changes your public API and breaks mobile apps.
- Lazy-loading surprises: serialising a lazy association triggers queries (or
LazyInitializationException), and bidirectional relationships create infinite recursion in JSON. - Mass assignment: accepting an entity as
@RequestBodylets a caller set fields they should not, such asid,roleorprice. - One shape for all use cases: a list screen needs three fields, a detail screen thirty.
DTOs
Use separate types for input and output:
public record CreateOrderRequest(
@NotNull Long customerId,
@NotEmpty List<Long> productIds) {}
public record OrderResponse(long id, String customer, BigDecimal amount, String status, Instant createdAt) {}
public record OrderSummary(long id, BigDecimal amount) {} // a smaller shape for lists
Records are ideal: immutable, concise, and Jackson serialises them. Map between entity and DTO in the service layer (or a dedicated mapper), never in the entity:
@Service
public class OrderService {
public OrderResponse get(long id) {
Order order = repository.findById(id).orElseThrow(() -> new OrderNotFoundException(id));
return toResponse(order);
}
private OrderResponse toResponse(Order o) {
return new OrderResponse(o.getId(), o.getCustomer().getName(), o.getAmount(),
o.getStatus().name(), o.getCreatedAt());
}
}
For many DTOs, mapping libraries reduce boilerplate: MapStruct generates mapping code at compile time (fast, type-safe, preferred); ModelMapper uses reflection. Hand-written mappers are fine for small projects and easy to debug. Spring Data projections (interfaces or records of selected columns) let a query return a DTO directly without loading the entity.
DTO design tips:
- Name by role:
CreateOrderRequest,UpdateOrderRequest,OrderResponse,OrderSummary. - Never include fields the caller must not set (id, createdAt, status) in request DTOs.
- Use
BigDecimal(or integer minor units such as paise) for money, neverdouble. - Use ISO-8601 for dates (
Instant,LocalDate), and enums as strings. - Keep responses stable: add fields rather than remove or rename, or version the API (
/v2/orders). - Use a consistent envelope or none; for lists, include pagination info (
Pageconverted to a DTO withcontent,page,size,totalElements).
Designing good responses
- Return the created or updated resource from
POST,PUTandPATCHso clients need no extra call. - For errors, return a structured body (the next lessons use RFC 9457
ProblemDetail) with the right status code. - Do not return
nullfor "no data": return an empty list for collections,404for a single missing resource. - Use idempotency keys for payment-like
POSTendpoints, so a retry does not create two orders.
Common mistakes
- Returning entities from controllers.
- Accepting entities as request bodies (mass assignment).
200 OKwith an error body, or500for client mistakes.- No
Locationheader after a201. - Using
doublefor money. - Changing DTO fields casually, breaking mobile clients.
Try it yourself
- Return
201with aLocationheader from your create endpoint and check it withcurl -i. - Return
404for an unknown id and204for a successful delete. - Replace an entity in a response with a record DTO, and prove an internal field no longer appears.
- Write
CreateOrderRequestwithoutidandstatus, and try sending those fields; confirm they are ignored. - Add a
Page-based list endpoint that returns a pagination DTO.
Check yourself
What status code should a successful POST that creates a resource return?
201 Created, with a Location header pointing to the new resource.
What is the difference between 401 and 403?
401 means the caller is not authenticated (credentials missing or invalid); 403 means they are authenticated but not permitted to do this.
Why should you not return JPA entities from a controller?
It leaks internal fields, couples the API to the database model, can trigger lazy loading and infinite JSON recursion, and allows mass assignment when used as input.
Where should entity-to-DTO mapping happen?
In the service layer or a dedicated mapper, not in the entity or the controller.
Interview questions
What are DTOs and why do we use them?
Data transfer objects are simple classes (often records) that define the shape of API input and output, decoupling the public contract from internal entities and preventing leaks, recursion and mass-assignment problems.
How do you return a custom status code from a Spring controller?
Use ResponseEntity (ResponseEntity.status(...), created, noContent), @ResponseStatus on a method or exception, or throw a ResponseStatusException; for exceptions map them centrally with @RestControllerAdvice.
PUT or PATCH for updating an order's status?
PATCH, since only one field changes; PUT replaces the whole resource and requires sending all fields. Both should be idempotent.
Summary
- Use correct status codes: 200, 201 with
Location, 204, 400, 401, 403, 404, 409, 500. - Control responses with
ResponseEntity,@ResponseStatusor domain exceptions mapped centrally. - Never expose entities; use request and response DTOs (records) and map in the service layer.
- Keep the API contract stable; use
BigDecimaland ISO dates.
Going deeper
- MDN: HTTP response status codes: every code explained.
- Spring MVC: ResponseEntity: building responses.
- Spring MVC: Exceptions and @ResponseStatus: mapping exceptions to statuses.
- RFC 9110: HTTP semantics: the standard definition of methods and status codes.
See how much of this you can explain
A free mock interview asks you new questions on Spring Boot, REST and JPA for Java Full Stack Developer and scores every answer, with what to fix.