Request and response DTOs
50 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite stores a cost price that only the owner may see. If the API returns the stored object as it is, every customer app receives that secret too.
Why controllers never expose entities
A DTO (data transfer object) is a small class or record whose only job is to carry data in or out of the API. Request DTOs say what a client may send, response DTOs say what it gets back. The stored object, the entity, stays inside the server.
The first version returns the stored Product straight to the client. The examples show what leaks out, and how a client can overwrite fields it must never touch.
Example 1 · Product.java (the entity) and an endpoint that returns it
Runs in: the rest-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.product;
import java.math.BigDecimal;import java.time.OffsetDateTime;
public class Product {
private long id; private String sku; private String name; private long categoryId; private String categoryName; private BigDecimal price; private BigDecimal costPrice; // what the shop paid the supplier: internal private int stock; private boolean active; private OffsetDateTime createdAt; // set by the server
public Product() { }
public Product(long id, String sku, String name, long categoryId, String categoryName, BigDecimal price, BigDecimal costPrice, int stock, boolean active, OffsetDateTime createdAt) { this.id = id; this.sku = sku; this.name = name; this.categoryId = categoryId; this.categoryName = categoryName; this.price = price; this.costPrice = costPrice; this.stock = stock; this.active = active; this.createdAt = createdAt; }
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getSku() { return sku; } public void setSku(String sku) { this.sku = sku; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getCategoryId() { return categoryId; } public void setCategoryId(long categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getCostPrice() { return costPrice; } public void setCostPrice(BigDecimal costPrice) { this.costPrice = costPrice; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public OffsetDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }}
package com.shoplite.lab.product;
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.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class EntityProductController {
private final ProductService productService;
public EntityProductController(ProductService productService) { this.productService = productService; }
@GetMapping("/lab/entity-products/{id}") public ResponseEntity<Product> get(@PathVariable long id) { return ResponseEntity.of(productService.findEntity(id)); }
@PutMapping("/lab/entity-products/{id}") public Product replace(@PathVariable long id, @RequestBody Product product) { product.setId(id); return productService.saveEntity(product); // whatever the client sent is stored }}$ curl http://localhost:8080/lab/entity-products/6
{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Accessories","price":1299.00,"costPrice":780.00,"stock":120,"active":true,"createdAt":"2026-06-01T10:00:00+05:30"}What this code does
- Every getter becomes a JSON field: any customer can now see that the shop pays Rs 780 for earphones it sells at Rs 1299.
isActive()is a getter for the propertyactive, so the JSON says"active", not the contract's"isActive", andcreatedAtappears though the contract's product has no such field.- The
ProductServicekeeps these entities now and hands them out only through two package-private methods used by this "what goes wrong" controller.
Example 2 · Mass assignment: the client edits fields it must not touch
Runs in: the rest-lab practice project (Spring Boot 4.1)
curl -X PUT http://localhost:8080/lab/entity-products/6 -H "Content-Type: application/json" -d '{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Free Gifts","price":1299.00,"costPrice":1.00,"stock":120,"active":true,"createdAt":"2020-01-01T00:00:00+05:30"}'curl http://localhost:8080/lab/entity-products/6{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Free Gifts","price":1299.00,"costPrice":1.00,"stock":120,"active":true,"createdAt":"2019-12-31T18:30:00Z"}
{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Free Gifts","price":1299.00,"costPrice":1.00,"stock":120,"active":true,"createdAt":"2019-12-31T18:30:00Z"}What this code does
- The
replacemethod of Example 1 takes@RequestBody Product, so the client wrote the cost price, the creation time and a made-upcategoryNamestraight into the store. createdAtcame back as2019-12-31T18:30:00Z: Jackson converted the time to UTC while reading it. Same moment, different text, another reason the server, not the client, sets times.- With a request DTO these fields do not exist, so the strict Jackson setting rejects them with 400 (Example 3).
An entity is the object the application stores: here a Product class with everything the shop keeps about a product, including fields clients must never see, such as the supplier costPrice. In the JPA section it becomes the class mapped to the products table. Returning the entity sends every getter to the client: the cost price, internal timestamps, and Java naming such as "active" instead of the contract's "isActive". Accepting the entity as @RequestBody is worse. The client can then set any field it likes, including costPrice, createdAt or categoryName. This is called mass assignment.
There is also a slower problem. If the API returns the entity, renaming a database column renames a JSON field and breaks every mobile app in use. DTOs keep the API contract and the storage free to change separately.
Find the bug
Find the leaking line
Each snippet exposes the entity. Tap the line that should use a DTO, then check the fix.
Return one product to the app.
Round 1 of 2Records as DTOs: request and response
A response DTO is the record that holds exactly the fields the API contract shows for a resource, such as ProductResponse. It has no field the client must not see.
The API needs one record for each kind of input and one for the answer. The example builds ProductResponse and makes the service return it.
Example 3 · ProductResponse.java and the service returning DTOs
Runs in: the rest-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.product;
import java.math.BigDecimal;
// Exactly the product JSON of the ShopLite contract, nothing morepublic record ProductResponse(long id, String sku, String name, long categoryId, String categoryName, BigDecimal price, int stock, boolean isActive) {
public static ProductResponse from(Product product) { return new ProductResponse(product.getId(), product.getSku(), product.getName(), product.getCategoryId(), product.getCategoryName(), product.getPrice(), product.getStock(), product.isActive()); }}
public Optional<ProductResponse> findById(long id) { return Optional.ofNullable(products.get(id)).map(ProductResponse::from);}
public ProductResponse create(CreateProductRequest request) { long id = nextId.getAndIncrement(); Product product = new Product(id, request.sku(), request.name(), request.categoryId(), CATEGORY_NAMES.get(request.categoryId()), request.price(), null, request.stock() == null ? 0 : request.stock(), request.isActive() == null || request.isActive(), OffsetDateTime.now(INDIA).truncatedTo(ChronoUnit.SECONDS)); return ProductResponse.from(add(product));}
// ProductController: the same six methods, now typed with ProductResponse, e.g.// public ResponseEntity<ProductResponse> get(@PathVariable long id)$ curl http://localhost:8080/api/v1/products/3
{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true}
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB101","name":"Zebronics Keyboard","categoryId":4,"price":999.00,"costPrice":1.00}'
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:22:49 GMT
Connection: close
{"timestamp":"2026-10-16T05:22:49.839Z","status":400,"error":"Bad Request","path":"/api/v1/products"}
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"id":1,"sku":"ACC-KB102","name":"Zebronics Keyboard","categoryId":4,"price":999.00}'
HTTP/1.1 400
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:22:50 GMT
Connection: close
{"timestamp":"2026-10-16T05:22:50.031Z","status":400,"error":"Bad Request","path":"/api/v1/products"}
Server log:
WARN ... JSON parse error: Unrecognized property "costPrice" (class com.shoplite.lab.product.CreateProductRequest), not marked as ignorable]
WARN ... JSON parse error: Unrecognized property "id" (class com.shoplite.lab.product.CreateProductRequest), not marked as ignorable]What this code does
- The response has exactly the contract's eight fields: no
costPrice, nocreatedAt, andisActivespelled as promised. CreateProductRequest(from the @RequestBody lesson) has nocostPriceorid, so sending them is a 400. The contract says exactly this: "a bodyidis an unknown field".fromis the one place that knows both shapes. When the entity gains a field, the API stays the same until someone decides to add it toProductResponse.
Request DTOs describe one operation's input: CreateProductRequest (POST, stock and isActive optional), UpdateProductRequest (PUT, all fields) and PatchProductRequest (PATCH, any subset). None has id, costPrice or createdAt, so a client cannot send them: with the strict Jackson setting, trying is a 400.
A static factory ProductResponse.from(product) copies the fields out of the entity in one place, and the service returns ProductResponse, so the entity never reaches the controller; the Layered architecture module explains this split in full. Records fit DTOs well: they are short, immutable and need no getters, and Jackson reads and writes them by component name.
Jackson rules: @JsonProperty, dates and BigDecimal prices
@JsonProperty("isActive") sets the JSON name of a field when the Java name differs. Jackson names a class property after its getter, so boolean isActive() becomes "active"; a record component named isActive stays "isActive".
The contract wants the name isActive and a price with exactly two decimals. The example compares double with BigDecimal, two kinds of date, and @JsonProperty.
Example 4 · Jackson rules: double vs BigDecimal, LocalDateTime vs OffsetDateTime, @JsonProperty
Runs in: the rest-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/jackson/JacksonRulesController.javapackage com.shoplite.lab.jackson;
import java.math.BigDecimal;import java.time.LocalDateTime;import java.time.OffsetDateTime;import java.time.ZoneOffset;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class JacksonRulesController {
private static final ZoneOffset INDIA = ZoneOffset.ofHoursMinutes(5, 30);
record PriceAndTime(double priceAsDouble, BigDecimal priceAsBigDecimal, LocalDateTime localTime, OffsetDateTime offsetTime, @JsonProperty("isActive") boolean active) { }
@GetMapping("/lab/jackson-rules") public PriceAndTime rules() { LocalDateTime ordered = LocalDateTime.of(2026, 9, 21, 21, 5); return new PriceAndTime(17999.00, new BigDecimal("17999.00"), ordered, ordered.atOffset(INDIA), true); }}
// src/main/java/com/shoplite/lab/customer/CustomerResponse.javapackage com.shoplite.lab.customer;
import java.time.OffsetDateTime;
public record CustomerResponse(long id, String fullName, String email, String phone, OffsetDateTime createdAt) {}$ curl http://localhost:8080/lab/jackson-rules
{"priceAsDouble":17999.0,"priceAsBigDecimal":17999.00,"localTime":"2026-09-21T21:05:00","offsetTime":"2026-09-21T21:05:00+05:30","isActive":true}
$ curl http://localhost:8080/api/v1/customers/3
{"id":3,"fullName":"Meena Iyer","email":"meena.iyer@example.com","phone":null,"createdAt":"2026-06-02T09:05:00+05:30"}What this code does
- The same price as
doubleloses its second decimal (17999.0); asBigDecimalit stays17999.00. LocalDateTimehas no offset, so the client cannot tell India time from any other;OffsetDateTimecarries+05:30, the format the contract uses forcreatedAtandorderedAt.@JsonProperty("isActive")renames the Java componentactivein the JSON. The customer endpoint (fixed data in a small labCustomerController) shows the contract's customer JSON, with"phone":nullfor Meena, who gave no number.
Money must be BigDecimal. Jackson writes new BigDecimal("17999.00") as 17999.00, keeping the scale, but a double 17999.00 comes out as 17999.0, breaking the contract's "exactly two decimals". Dates come out as ISO-8601 text: OffsetDateTime keeps its offset (2026-09-21T21:05:00+05:30), while LocalDateTime has no offset at all, so a client in another country cannot know the real moment.
One trap on the way in: Jackson converts an OffsetDateTime read from a request body to UTC by default, so "2020-01-01T00:00:00+05:30" is stored as 2019-12-31T18:30Z. Same moment, different text. ShopLite clients never send times; the server sets them.
Leaving out null fields and nesting objects
@JsonInclude(JsonInclude.Include.NON_NULL) on a DTO leaves fields that are null out of the JSON, instead of writing "phone": null. ShopLite does not use it: its contract keeps every field present.
Should a missing phone number appear as null, or not appear at all? The example shows the choice, and a record nested inside another record.
Example 5 · CustomerCard.java (NON_NULL) and ProductCard.java (nested)
Runs in: the rest-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.customer;
import com.fasterxml.jackson.annotation.JsonInclude;
// Lab only: leaves null fields out. ShopLite's contract keeps them as null.@JsonInclude(JsonInclude.Include.NON_NULL)public record CustomerCard(long id, String fullName, String phone) {}
package com.shoplite.lab.product;
import java.math.BigDecimal;
// Lab only: the category nested as an object. ShopLite v1 uses flat categoryId and categoryName.public record ProductCard(long id, String name, BigDecimal price, CategorySummary category) {
public record CategorySummary(long id, String name) { }
static ProductCard from(ProductResponse product) { return new ProductCard(product.id(), product.name(), product.price(), new CategorySummary(product.categoryId(), product.categoryName())); }}$ curl http://localhost:8080/lab/customer-cards/1
{"id":1,"fullName":"Asha Rao","phone":"9876543201"}
$ curl http://localhost:8080/lab/customer-cards/3
{"id":3,"fullName":"Meena Iyer"}
$ curl http://localhost:8080/lab/product-cards/1
{"id":1,"name":"Redmi Note 13 5G","price":17999.00,"category":{"id":2,"name":"Mobiles"}}What this code does
- With
NON_NULL, Meena's card has nophonefield at all. A client must then handle "field missing" and "field present" separately, which is why the ShopLite contract keepsnullfields. ProductCardnests aCategorySummaryrecord, and Jackson writes it as an object inside the object. Two small lab controllers serve these cards from the same data.- Both records are lab-only. ShopLite's v1 product JSON stays flat (
categoryId,categoryName), and changing that now would break clients.
A nested object is a record inside a record: ProductCard holds a CategorySummary(id, name) and Jackson writes "category":{"id":2,"name":"Mobiles"}. Nesting groups related fields and leaves room to add more later.
ShopLite v1 chose flat fields, categoryId and categoryName, and both shapes are fine. What is not fine is switching: changing one shape into the other renames fields, which is a breaking change that needs /api/v2.
A list response vs a page response object
A page response is an object that wraps one page of items with content, page, size, totalElements and totalPages. A bare list ([...]) has nowhere to put those numbers.
A list that grows needs paging numbers, and a bare array has no room for them. The code below compares a page response with a bare list.
public record PageResponse<T>(List<T> content, int page, int size, long totalElements, int totalPages) { ... }
@GetMappingpublic PageResponse<ProductResponse> list(...) { ... } // products, customers, orders
@GetMappingpublic List<CategoryResponse> list() { ... } // small fixed lists onlyExample 6 · A page response for a growing list
Runs in: the rest-lab practice project (Spring Boot 4.1)
curl "http://localhost:8080/api/v1/products?categoryId=2&size=2"{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true}],"page":0,"size":2,"totalElements":3,"totalPages":2}What this code does
contentholdsProductResponseobjects, so paging and DTOs work together: the page object is a DTO too.totalElements3 andtotalPages2 tell an app to show "Page 1 of 2" and fetchpage=1next; a bare array could not say that.
A list that grows with traffic (products, customers, orders) always gets a page object, so the server never sends ten thousand products at once. A bare array is fine only for small lists that cannot grow, such as the categories or one order's items, as the contract says.
The object also leaves room to grow. Adding a field such as "hasNext" to the page object later is not a breaking change; turning a bare array into an object is.
Next step
Check your understanding
12 quick questions