Skip to lesson

Validation in the service layer for business rules

A shop must refuse a second product with the same SKU and an order for more units than it has. Annotations on the request cannot know either, because only the data can.

Format checks at the edge, business rules in the service

A business rule is a rule that needs the application's current data to decide, such as "the SKU must not exist yet" or "there must be enough stock". Input validation, by contrast, checks only the request itself.

Two kinds of rules protect the shop. Format rules look at the request alone; data rules need the database. The example shows the format rules on the record and a controller with no if statements.

A request passes three places in order. First the controller, with @Valid on the request record: format rules such as the SKU pattern and a price above zero, answered with 400 when broken. Then the service: data rules such as the category exists and the SKU is free, answered with 404, 422 or 409.

Example 1 · CreateProductRequest.java, ProductController.java (shoplite-api)

Runs in: the shoplite-api Spring Boot project

CreateProductRequest.javaJava
// src/main/java/com/shoplite/product/CreateProductRequest.javapackage com.shoplite.product;
import java.math.BigDecimal;
import com.shoplite.common.validation.Sku;
import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.Digits;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.Positive;import jakarta.validation.constraints.PositiveOrZero;import jakarta.validation.constraints.Size;
/** Body of POST /api/v1/products. stock and isActive are optional (defaults 0 and true). */public record CreateProductRequest(        @NotNull(message = "is required")        @Sku        String sku,
        @NotNull(message = "is required")        @Size(min = 2, max = 120, message = "must be {min}-{max} characters")        String name,
        @NotNull(message = "is required")        @Positive(message = "must be a positive id")        Long categoryId,
        @NotNull(message = "is required")        @DecimalMin(value = "0.00", inclusive = false, message = "must be greater than 0")        @Digits(integer = 8, fraction = 2, message = "must have at most 8 digits before the point and 2 after")        BigDecimal price,
        @PositiveOrZero(message = "must be 0 or more")        Integer stock,
        Boolean isActive) {
    public CreateProductRequest {        sku = sku == null ? null : sku.strip();     // trimmed before the checks run        name = name == null ? null : name.strip();    }}
// src/main/java/com/shoplite/product/ProductController.javapackage com.shoplite.product;
import java.net.URI;
import com.shoplite.common.PageResponse;
import jakarta.validation.Valid;import jakarta.validation.constraints.Positive;
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.PatchMapping;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/v1/products")public class ProductController {
    private final ProductService productService;
    public ProductController(ProductService productService) {        this.productService = productService;    }
    @GetMapping    public PageResponse<ProductResponse> list(@Valid ProductSearchParams params) {        return productService.list(params);    }
    @GetMapping("/{id}")    public ProductResponse get(@PathVariable @Positive(message = "must be a positive id") long id) {        return productService.findById(id);    }
    @PostMapping    public ResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest request) {        ProductResponse created = productService.create(request);        URI location = ServletUriComponentsBuilder.fromCurrentRequest()                .path("/{id}").buildAndExpand(created.id()).toUri();        return ResponseEntity.created(location).body(created);    }
    @PutMapping("/{id}")    public ProductResponse replace(@PathVariable @Positive(message = "must be a positive id") long id,                                   @Valid @RequestBody ReplaceProductRequest request) {        return productService.replace(id, request);    }
    @PatchMapping("/{id}")    public ProductResponse patch(@PathVariable @Positive(message = "must be a positive id") long id,                                 @Valid @RequestBody PatchProductRequest request) {        return productService.patch(id, request);    }
    @DeleteMapping("/{id}")    public ResponseEntity<Void> delete(@PathVariable @Positive(message = "must be a positive id") long id) {        productService.delete(id);        return ResponseEntity.noContent().build();    }}
Sample output
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "ACC-KB100", "name": "Zebronics Wireless Keyboard", "categoryId": 4, "price": 999.00, "stock": 30}'
HTTP/1.1 201
Location: http://localhost:8080/api/v1/products/16
Content-Type: application/json

{"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}

$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "kb 1", "name": "K", "categoryId": 4, "price": -5.00}'
HTTP/1.1 400
Content-Type: application/json

{"timestamp":"2026-10-16T05:30:30.912Z","status":400,"error":"Bad Request","path":"/api/v1/products"}

What this code does

  • The record holds every format rule; @Valid in the controller enforces them. The controller has no if statements: it maps HTTP to a service call and back.
  • The SKU is @NotNull plus @Sku (the custom validator from the last lesson), and name is @NotNull plus @Size(min = 2) after trimming, so each broken field gets exactly one message.
  • The bad request never reaches ProductService; nothing here knows about categories or existing SKUs.

Input validation answers "is this request well-formed?": the SKU matches its pattern, the price is above zero, the list has 1 to 20 items. A business rule answers "is it allowed now?" and needs data: does category 42 exist, is MOB-RN13 already taken, are 9 iPhones in stock? Format errors are found by @Valid before any code runs and are 400s; data rules run in the service, which owns the data and the transaction, and give 404, 409 or 422.

A quick test for any rule: could you check it with the request alone, on a computer with no database? If yes, it is input validation; if no, it is a business rule.

Predict the output

Format rule or business rule?

Read the rule and the request, then pick the kind of rule.

Round 1 of 4

Rule: the price must be above zero.
Request: {"price": -5.00}

Rules that need data: unique SKU, category exists, enough stock

404, 422 and 409 are the ShopLite statuses for data rules: 404 when the URL's resource is missing, 422 when the request refers to other data that is wrong (an unknown category), and 409 when it clashes with current state (a taken SKU).

Three data rules show up in ShopLite: the category must exist, the SKU must be unique, and stock must cover an order. The example puts them in the service, where the data lives.

Example 2 · ProductService.create and CategoryService.requireExistingName (parts of the files)

Runs in: the shoplite-api Spring Boot project

Java
// src/main/java/com/shoplite/product/ProductService.java (part)    public ProductResponse create(CreateProductRequest request) {        String categoryName = categoryService.requireExistingName(request.categoryId());        checkSkuIsFree(request.sku(), null);                                                // 409        Product product = new Product(null, request.sku(), request.name(), request.categoryId(),                request.price(), request.stock() == null ? 0 : request.stock(),                request.isActive() == null || request.isActive());        return ProductResponse.from(saveChecked(product), categoryName);    }
    private void checkSkuIsFree(String sku, Long ownId) {        if (productRepository.existsBySkuAndIdNot(sku, ownId)) {            throw duplicateSku(sku);        }    }
    private Product saveChecked(Product product) {        try {            return productRepository.save(product);        } catch (DuplicateSkuException e) {            throw duplicateSku(product.sku());        }    }
    private static ConflictException duplicateSku(String sku) {        return new ConflictException("A product with SKU %s already exists.".formatted(sku));    }
// src/main/java/com/shoplite/category/CategoryService.java (part)    /** For other features: the name of an existing category, or 422 when the id is unknown. */    public String requireExistingName(long categoryId) {        return categoryRepository.findById(categoryId)                .map(Category::name)                .orElseThrow(() -> new BusinessRuleException("Category %d does not exist.".formatted(categoryId)));    }
Sample output
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "MOB-RN13", "name": "Zebronics Wireless Keyboard", "categoryId": 4, "price": 999.00, "stock": 30}'
HTTP/1.1 409
Content-Type: application/json

{"timestamp":"2026-10-16T05:30:31.147Z","status":409,"error":"Conflict","path":"/api/v1/products"}

$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "ACC-KB200", "name": "Zebronics Wireless Keyboard", "categoryId": 42, "price": 999.00, "stock": 30}'
HTTP/1.1 422
Content-Type: application/json

{"timestamp":"2026-10-16T05:30:31.491Z","status":422,"error":"Unprocessable Content","path":"/api/v1/products"}

What this code does

  • create receives a request that already passed every format rule, so it only checks data: the category (422) and the SKU (409).
  • saveChecked catches the repository's DuplicateSkuException, the final guard for two requests that pass the early check together, and turns it into the same 409.
  • The error bodies are still Spring Boot's default shape; the statuses already follow the contract.

Each rule lives in the service of the feature that owns the data. ProductService asks CategoryService.requireExistingName(id), not the category repository, so the category feature keeps control of its own data. A missing category gives 422 rule-broken, a taken SKU 409 already-exists, and too little stock 409 out-of-stock with productId, available and requested. ProductService.reserveStock is ready for orders in the ShopLite REST API module.

An early check gives a fast, clear answer, but it is not the final word for uniqueness: two requests can pass the check at the same moment. The final guard is in the storage itself, as the race section shows.

Throwing meaningful exceptions from the service

A meaningful exception names what went wrong in business terms, such as ResourceNotFoundException or OutOfStockException. Its message is one safe sentence for the client, never a table name or SQL.

The service must tell the controller why a rule failed. It throws a named exception with a safe message, and Spring maps it to a status. The example shows the ShopLite exception classes.

Example 3 · The ShopLite exceptions in com.shoplite.common

Runs in: the shoplite-api Spring Boot project

ResourceNotFoundException.javaJava
// src/main/java/com/shoplite/common/ResourceNotFoundException.javapackage com.shoplite.common;
import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ResponseStatus;
/** The resource named in the URL does not exist (404). */@ResponseStatus(HttpStatus.NOT_FOUND)public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {        super(message);    }}
// src/main/java/com/shoplite/common/ConflictException.javapackage com.shoplite.common;
import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ResponseStatus;
/** The request clashes with the current data: a duplicate, not enough stock, an item still in use (409). */@ResponseStatus(HttpStatus.CONFLICT)public class ConflictException extends RuntimeException {
    public ConflictException(String message) {        super(message);    }}
// src/main/java/com/shoplite/common/BusinessRuleException.javapackage com.shoplite.common;
import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ResponseStatus;
/** Every field is valid, but the request refers to data that breaks a rule, such as an unknown category (422). */@ResponseStatus(HttpStatus.UNPROCESSABLE_CONTENT)public class BusinessRuleException extends RuntimeException {
    public BusinessRuleException(String message) {        super(message);    }}
package com.shoplite.common;
/** An order asks for more units than are in stock (409, with the numbers the client needs). */public class OutOfStockException extends ConflictException {
    private final long productId;    private final int available;    private final int requested;
    public OutOfStockException(long productId, String productName, int available, int requested) {        super("Only %d units of %s are in stock; %d were requested."                .formatted(available, productName, requested));        this.productId = productId;        this.available = available;        this.requested = requested;    }
    public long getProductId() {        return productId;    }
    public int getAvailable() {        return available;    }
    public int getRequested() {        return requested;    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404
Content-Type: application/json

{"timestamp":"2026-10-16T05:30:35.862Z","status":404,"error":"Not Found","path":"/api/v1/products/99"}

$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "MOB-RN13", "name": "Zebronics Wireless Keyboard", "categoryId": 4, "price": 999.00, "stock": 30}'
HTTP/1.1 409
Content-Type: application/json

{"timestamp":"2026-10-16T05:30:31.147Z","status":409,"error":"Conflict","path":"/api/v1/products"}

$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "ACC-KB200", "name": "Zebronics Wireless Keyboard", "categoryId": 42, "price": 999.00, "stock": 30}'
HTTP/1.1 422
Content-Type: application/json

{"timestamp":"2026-10-16T05:30:31.491Z","status":422,"error":"Unprocessable Content","path":"/api/v1/products"}

What this code does

  • @ResponseStatus tells Spring which status to send when the exception leaves a controller: 404, 409 or 422 (UNPROCESSABLE_CONTENT is the current name of 422 in Spring Framework 7).
  • OutOfStockException extends ConflictException, so it is also a 409, and carries the three numbers the contract puts in the error body.
  • Messages are full, safe sentences, such as "Product 99 was not found." Spring Boot hides them in the default body for now; the Exception handling module shows them as detail. The Layered architecture module called the 404 class NotFoundException. It is renamed ResourceNotFoundException here so the name matches the contract's "Resource not found" kind; rename yours the same way (your IDE's Refactor → Rename updates every use).

Example 4 · src/test/java/com/shoplite/product/ProductServiceTest.java

Runs in: the shoplite-api Spring Boot project

Java
package com.shoplite.product;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;import java.util.List;import java.util.Optional;
import com.shoplite.category.Category;import com.shoplite.category.CategoryRepository;import com.shoplite.category.CategoryService;import com.shoplite.common.BusinessRuleException;import com.shoplite.common.ConflictException;import com.shoplite.common.OutOfStockException;import com.shoplite.common.ResourceNotFoundException;
import org.junit.jupiter.api.Test;
class ProductServiceTest {
    /** Two categories are enough for these rules: 2 Mobiles, 4 Accessories. */    static class FakeCategoryRepository implements CategoryRepository {        private final List<Category> categories = List.of(                new Category(2L, "Mobiles", 1L), new Category(4L, "Accessories", 1L));
        public List<Category> findAll() { return categories; }        public Optional<Category> findById(long id) {            return categories.stream().filter(c -> c.id() == id).findFirst();        }        public Optional<Category> findByNameIgnoreCase(String name) { return Optional.empty(); }        public boolean existsByParentId(long parentId) { return false; }        public Category save(Category category) { return category; }        public boolean deleteById(long id) { return false; }    }
    private final ProductService service = new ProductService(            new InMemoryProductRepository(), new CategoryService(new FakeCategoryRepository()));
    private static CreateProductRequest keyboard(String sku, long categoryId) {        return new CreateProductRequest(sku, "Zebronics Wireless Keyboard", categoryId,                new BigDecimal("999.00"), 30, null);    }
    @Test    void createsAProductWithDefaults() {        ProductResponse created = service.create(keyboard("ACC-KB100", 4));        assertThat(created.id()).isEqualTo(16);        assertThat(created.categoryName()).isEqualTo("Accessories");        assertThat(created.isActive()).isTrue();    }
    @Test    void rejectsAnUnknownCategoryWith422() {        assertThatThrownBy(() -> service.create(keyboard("ACC-KB100", 42)))                .isInstanceOf(BusinessRuleException.class)                .hasMessage("Category 42 does not exist.");    }
    @Test    void rejectsADuplicateSkuWith409() {        assertThatThrownBy(() -> service.create(keyboard("MOB-RN13", 4)))                .isInstanceOf(ConflictException.class)                .hasMessage("A product with SKU MOB-RN13 already exists.");    }
    @Test    void checksTheCategoryBeforeTheSku() {        // Both rules are broken; the 422 rule runs first, as the API contract says        assertThatThrownBy(() -> service.create(keyboard("MOB-RN13", 42)))                .isInstanceOf(BusinessRuleException.class);    }
    @Test    void replacingAMissingProductIs404BeforeAnyOtherRule() {        var request = new ReplaceProductRequest("MOB-RN13", "Keyboard", 42L, new BigDecimal("999.00"), 1, true);        assertThatThrownBy(() -> service.replace(99, request))                .isInstanceOf(ResourceNotFoundException.class)                .hasMessage("Product 99 was not found.");    }
    @Test    void reservingTooManyUnitsReportsTheNumbers() {        assertThatThrownBy(() -> service.reserveStock(3, 9))                .isInstanceOfSatisfying(OutOfStockException.class, e -> {                    assertThat(e).hasMessage("Only 8 units of iPhone 15 128GB are in stock; 9 were requested.");                    assertThat(e.getAvailable()).isEqualTo(8);                    assertThat(e.getRequested()).isEqualTo(9);                });    }
    @Test    void reservingReducesStockAndInactiveProductsCannotBeOrdered() {        service.reserveStock(3, 8);        assertThat(service.findById(3).stock()).isZero();        assertThatThrownBy(() -> service.reserveStock(15, 1))                .isInstanceOf(BusinessRuleException.class)                .hasMessage("Product 15 is not active.");    }}
Sample output (shortened)
$ mvn test -Dtest=ProductServiceTest
...
[INFO] Running com.shoplite.product.ProductServiceTest
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.669 s -- in com.shoplite.product.ProductServiceTest
...
[INFO] BUILD SUCCESS

What this code does

  • Business rules are tested without Spring and without HTTP: a real InMemoryProductRepository and a small fake category repository are passed to the constructors.
  • The tests check the exception type and its message, including the out-of-stock numbers, and that the category rule (422) runs before the SKU rule (409).

Returning null, false or an error code instead makes every caller check and translate it, and one forgotten check means a wrong 200. A thrown exception cannot be ignored by accident, and the HTTP mapping happens in one place, not in each controller.

For now each class carries @ResponseStatus (404, 409 or 422), so Spring sends the right status code. The Exception handling module puts them under one ShopLite base exception and turns them into the contract's ProblemDetail bodies with type, title and detail.

Find the bug

Find the weak exception

Each service method reports a problem badly. Click the line to blame.

A missing product answers 200 with an empty body.

Round 1 of 2

Why these rules do not belong in annotations

A race condition happens when two requests interleave so that both pass a check meant for one, for example two requests for the same new SKU. A final guard in the storage, such as a UNIQUE constraint, stops it.

A @UniqueSku annotation that calls the repository looks tidy but fails under load. The program below runs two requests at once, first with check-then-save, then with one atomic step.

Example 5 · SkuRaceDemo.java: why a "check first" annotation is not enough

SkuRaceDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.concurrent.CountDownLatch;
class ProductStore {
    private final List<String> skuRows = new ArrayList<>();
    synchronized boolean skuExists(String sku) {        return skuRows.contains(sku);    }
    synchronized void insert(String sku) {        skuRows.add(sku);    }
    // Like a UNIQUE constraint in the database: the check and the insert are one step    synchronized boolean insertIfSkuIsFree(String sku) {        if (skuRows.contains(sku)) {            return false;        }        skuRows.add(sku);        return true;    }
    synchronized int rows() {        return skuRows.size();    }}
public class SkuRaceDemo {
    public static void main(String[] args) throws InterruptedException {        System.out.println("Check first, save later (what a @UniqueSku annotation does):");        ProductStore store = new ProductStore();        CountDownLatch bothChecked = new CountDownLatch(2);        List<String> results = Collections.synchronizedList(new ArrayList<>());
        Runnable checkThenSave = () -> {            boolean free = !store.skuExists("ACC-KB100");   // the "validation"            bothChecked.countDown();            try {                bothChecked.await();                          // both requests have passed the check            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }            if (free) {                store.insert("ACC-KB100");                results.add("saved");            }        };        runTwice(checkThenSave);        System.out.println("  results: " + results + ", rows with ACC-KB100: " + store.rows());
        System.out.println("One atomic insert (what the database UNIQUE constraint does):");        ProductStore safeStore = new ProductStore();        List<String> safeResults = Collections.synchronizedList(new ArrayList<>());        Runnable atomicInsert = () -> safeResults.add(                safeStore.insertIfSkuIsFree("ACC-KB100") ? "saved" : "409 duplicate");        runTwice(atomicInsert);        Collections.sort(safeResults, Collections.reverseOrder());        System.out.println("  results: " + safeResults + ", rows with ACC-KB100: " + safeStore.rows());    }
    static void runTwice(Runnable task) throws InterruptedException {        Thread first = new Thread(task, "request-1");        Thread second = new Thread(task, "request-2");        first.start();        second.start();        first.join();        second.join();    }}
Output
Check first, save later (what a @UniqueSku annotation does):
  results: [saved, saved], rows with ACC-KB100: 2
One atomic insert (what the database UNIQUE constraint does):
  results: [saved, 409 duplicate], rows with ACC-KB100: 1

What this code does

  • Two threads play two requests. The CountDownLatch makes both finish the "does the SKU exist?" check before either saves, which is exactly the unlucky timing that happens under real traffic.
  • Check-then-save stores two rows with the same SKU. The atomic insertIfSkuIsFree does the check and the insert as one step, like a UNIQUE constraint, so the second request gets a duplicate answer.
  • Plain Java, no Spring needed. ShopLite's in-memory repository uses synchronized methods for the same reason; with MySQL the UNIQUE constraint on sku is the guard.

A @UniqueSku constraint whose validator calls the repository is the wrong place for four reasons. It races, as the demo shows. It gives the wrong status: a duplicate is a 409 conflict with existing data, not a 400 malformed request. It hides a database call inside "validation", so every unit test of the DTO suddenly needs a database. And an update must ignore the product's own SKU, which the annotation cannot see because it does not know the URL's id.

The service check plus a storage guard solves all four: the service knows the id and throws a 409, and the guard (a UNIQUE constraint in MySQL, a synchronized save in the in-memory repository) stops the rare race.

Order of checks: cheap format checks first, data checks after

The order of checks is the fixed sequence in which a request is tested: parse the body, validate fields, load the URL's resource (404), check rules on other data (422), check state and uniqueness (409), then save.

A request can break several rules at once, so the order decides which error the client sees. ProductService.replace shows the order as three lines, one per status.

Example 6 · ProductService.replace: 404, then 422, then 409 (part of the file)

Runs in: the shoplite-api Spring Boot project

Java
// src/main/java/com/shoplite/product/ProductService.java (part)    public ProductResponse replace(long id, ReplaceProductRequest request) {        load(id);        String categoryName = categoryService.requireExistingName(request.categoryId());   // 422        checkSkuIsFree(request.sku(), id);                                                  // 409        Product product = new Product(id, request.sku(), request.name(), request.categoryId(),                request.price(), request.stock(), request.isActive());        return ProductResponse.from(saveChecked(product), categoryName);    }
    private Product load(long id) {        return productRepository.findById(id)                .orElseThrow(() -> new ResourceNotFoundException("Product %d was not found.".formatted(id)));    }
Sample output
$ curl -i -X PUT http://localhost:8080/api/v1/products/99 -H "Content-Type: application/json" -d '{"sku": "MOB-RN13", "name": "boAt Airdopes 141", "categoryId": 42, "price": 1299.00, "stock": 120, "isActive": true}'
HTTP/1.1 404
Content-Type: application/json

{"timestamp":"2026-10-16T06:31:05.609Z","status":404,"error":"Not Found","path":"/api/v1/products/99"}

$ curl -i -X PUT http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"sku": "MOB-RN13", "name": "boAt Airdopes 141", "categoryId": 42, "price": 1299.00, "stock": 120, "isActive": true}'
HTTP/1.1 422
Content-Type: application/json

{"timestamp":"2026-10-16T06:31:05.944Z","status":422,"error":"Unprocessable Content","path":"/api/v1/products/6"}

$ curl -i -X PUT http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"sku": "MOB-RN13", "name": "boAt Airdopes 141", "categoryId": 4, "price": 1299.00, "stock": 120, "isActive": true}'
HTTP/1.1 409
Content-Type: application/json

{"timestamp":"2026-10-16T06:31:06.391Z","status":409,"error":"Conflict","path":"/api/v1/products/6"}

$ curl -i -X PUT http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"sku": "ACC-AD141", "name": "boAt Airdopes 141", "categoryId": 4, "price": 1199.00, "stock": 110, "isActive": true}'
HTTP/1.1 200
Content-Type: application/json

{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Accessories","price":1199.00,"stock":110,"isActive":true}

$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku": "MOB-RN13", "name": "K", "categoryId": 42, "price": 999.00}'
HTTP/1.1 400
Content-Type: application/json

{"timestamp":"2026-10-16T05:30:32.128Z","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 '{"sku": "MOB-RN13", "name": "Zebronics Wireless Keyboard", "categoryId": 42, "price": 999.00}'
HTTP/1.1 422
Content-Type: application/json

{"timestamp":"2026-10-16T05:30:31.764Z","status":422,"error":"Unprocessable Content","path":"/api/v1/products"}

What this code does

  • The first three PUTs break more and more rules. Product 99 does not exist, so it is 404 even though its category and SKU are also wrong; product 6 exists, so the unknown category gives 422 before the taken SKU gives 409.
  • For POST, a request with a 1-letter name, an unknown category and a taken SKU gets 400: format checks run before any data check. Fix the name and the same request gets 422.

The ShopLite contract fixes the order: parse the body (400 malformed-request), validate fields (400 validation-failed, all at once), load the URL's resource (404), check rules on other data (422), check state and uniqueness (409), then save.

Cheap checks go first because they need no database and reject most bad requests for almost nothing. Then 404 before 422 before 409: "this product does not exist" is more basic than "your category is wrong", which is more basic than "your SKU clashes". A fixed order also makes the API predictable and testable: the same bad request always gets the same answer.

Order of execution

The order of checks

Put the checks in the order the ShopLite contract runs them.

Next step

Check your understanding

12 quick questions