Spring Boot REST API Validation and Large Payload Handling
Request Payload Validation
Section titled “Request Payload Validation”Spring Boot uses Bean Validation (JSR-380 / Jakarta Validation).
Dependency
Section titled “Dependency”spring-boot-starter-validationModel Validation
Section titled “Model Validation”public class Product {
@NotNull private String name;
@Min(1) private double price;}Controller
Section titled “Controller”@PostMapping("/products")public Product createProduct(@Valid @RequestBody Product product) { return productService.save(product);}Common Validation Annotations
Section titled “Common Validation Annotations”| Annotation | Purpose |
|---|---|
@NotNull |
Cannot be null |
@NotBlank |
Cannot be blank |
@Size |
Restricts length |
@Min, @Max |
Numeric range |
@Email |
Valid email format |
Handling Large Request Payloads
Section titled “Handling Large Request Payloads”Increase Multipart Limits
Section titled “Increase Multipart Limits”spring.servlet.multipart.max-file-size=10MBspring.servlet.multipart.max-request-size=10MBHandling File Uploads
Section titled “Handling File Uploads”@PostMapping("/upload")public String uploadFile(@RequestParam MultipartFile file) {
fileService.save(file);
return "File uploaded successfully";}Request content type: multipart/form-data.
Stream Large Content
Section titled “Stream Large Content”Use InputStream instead of loading the entire payload into memory.
Pagination
Section titled “Pagination”Request:
GET /products?page=1&size=20Repository usage:
Page<Product> products = productRepository.findAll(PageRequest.of(0, 10));Add sorting with Sort, either standalone or combined with pagination:
Sort sort = Sort.by("salary").descending();productRepository.findAll(sort);Pageable pageable = PageRequest.of(0, 10, Sort.by("salary").descending());
productRepository.findAll(pageable);Enable Compression
Section titled “Enable Compression”server.compression.enabled=trueKey Takeaways
Section titled “Key Takeaways”@Validcombined with Bean Validation annotations (@NotNull,@Size,@Email, etc.) validates incoming payloads declaratively, without manual if-checks in the controller.- For large payloads, prefer streaming (
InputStream) over loading the full body into memory. Page<T>+PageRequestbound results at the repository layer, complementing the?page=&size=API-level pagination convention.- Enabling response compression (
server.compression.enabled=true) reduces payload size over the wire for large JSON responses.