Loading...
Loading...
You are building a backend service for an e-commerce platform. Your task is to design and implement a Spring Boot REST endpoint that manages product inventory. The endpoint must handle creating and retrieving products with proper validation, exception handling, and structured logging.
Given a JSON payload representing a product creation request, simulate what your Spring Boot REST endpoint would return — including proper HTTP status codes, validation error messages, and structured response bodies.
Your solution should model the behavior of:
POST /api/v1/products — Create a new productGET /api/v1/products/{id} — Retrieve a product by IDInput: A JSON string representing either a product creation request or a retrieval query.
For creation, the payload includes:
name (string, required, 2–100 chars)price (number, required, > 0)quantity (integer, required, >= 0)category (string, required, one of: ELECTRONICS, CLOTHING, FOOD)For retrieval, the payload is: {"action": "GET", "id": <number>}
Output: A JSON string representing the HTTP response body and status code in format: {"status": <code>, "body": <object>}
Example 1 — Successful Creation:
Input: {"action": "POST", "name": "Laptop", "price": 999.99, "quantity": 50, "category": "ELECTRONICS"}
Output: {"status": 201, "body": {"id": 1, "name": "Laptop", "price": 999.99, "quantity": 50, "category": "ELECTRONICS"}}
Explanation: All fields are valid. The endpoint creates the product and returns HTTP 201 Created with the persisted product (including generated ID).
Example 2 — Validation Failure:
Input: {"action": "POST", "name": "A", "price": -5.0, "quantity": 10, "category": "ELECTRONICS"}
Output: {"status": 400, "body": {"errors": ["name must be between 2 and 100 characters", "price must be greater than 0"]}}
Explanation: name is too short and price is negative. The @Valid annotation triggers MethodArgumentNotValidException, returning HTTP 400 with descriptive field errors.
Example 3 — Resource Not Found:
Input: {"action": "GET", "id": 999}
Output: {"status": 404, "body": {"error": "Product with id 999 not found"}}
Explanation: No product exists with ID 999. A custom ResourceNotFoundException is thrown and handled by , returning HTTP 404.
- name length: 2 <= name.length <= 100 - price > 0 (must be positive) - quantity >= 0 (non-negative integer) - category must be one of: ELECTRONICS, CLOTHING, FOOD - id > 0 for GET requests - Input is always valid JSON - IDs are auto-incremented starting from 1 - Max products in session: 1000
@ControllerAdvice@NotBlank, @Positive, @Min, @Size, @NotNull) on your DTO and @Valid on your controller parameter.@ControllerAdvice class with @ExceptionHandler methods for MethodArgumentNotValidException, ResourceNotFoundException, and generic Exception.@Slf4j; log at INFO on success, WARN on client errors (4xx), ERROR on server errors (5xx).ApiResponse<T> generic class.{"errors": ["category must be one of: ELECTRONICS, CLOTHING, FOOD"]}.