Real World Example

Why Every Real API Validates

  • Paytm / PhonePe: amount must be positive with at most 2 decimals, UPI ID must match a pattern, before any money moves.
  • IRCTC: passenger age range, name length, journey date in the future.
  • Flipkart seller portal: product title length, price limits, valid category and SKU.
  • The frontend validates for a nice user experience; the backend validates for safety, because anyone can call the API with curl.

ShopEase: Validated Create Product

public record CreateProductRequest(
        @NotNull @ValidSku String sku,
        @NotBlank @Size(max = 120) String name,
        @Size(max = 2000) String description,
        @NotNull @DecimalMin("0.01") @Digits(integer = 8, fraction = 2) BigDecimal price,
        @PositiveOrZero int stock,
        @NotBlank String category) {}

@PostMapping
public ResponseEntity<ProductResponse> create(@Valid @RequestBody CreateProductRequest request) {
    ProductResponse saved = service.create(request);
    return ResponseEntity.created(URI.create("/api/products/" + saved.id())).body(saved);
}

Example

A valid request:

curl -i -X POST localhost:8080/api/products -H "Content-Type: application/json" -d '{"sku":"ELE-1001","name":"Wireless Mouse","description":"2.4 GHz, silent clicks","price":799.00,"stock":120,"category":"Electronics"}'

Example output

HTTP/1.1 201 Created
Location: /api/products/1
Content-Type: application/json

{"id":1,"sku":"ELE-1001","name":"Wireless Mouse","description":"2.4 GHz, silent clicks","price":799.00,"stock":120,"category":"Electronics","inStock":true}

Example

An invalid one: every problem is reported in one response, so the user can fix them all at once:

curl -X POST localhost:8080/api/products -H "Content-Type: application/json" -d '{"sku":"mouse","name":"Wireless Mouse","price":799.999,"stock":-3,"category":"Electronics"}'

Example output

{"type":"about:blank","title":"Validation failed","status":400,"detail":"Request has invalid fields","instance":"/api/products","errors":{"sku":"must look like ABC-1234","price":"numeric value out of bounds (<8 digits>.<2 digits> expected)","stock":"must be greater than or equal to 0"}}