REST Controllers
Complete REST Controller
@RestController
@RequestMapping("/api/v1/products")
@RequiredArgsConstructor
public class ProductController {
private final ProductService productService;
@GetMapping
public ResponseEntity<Page<Product>> getAll(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return ResponseEntity.ok(productService.getAll(page, size));
}
@GetMapping("/{id}")
public ResponseEntity<Product> getById(@PathVariable Long id) {
return productService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<Product> create(
@Valid @RequestBody CreateProductRequest request) {
Product created = productService.create(request);
URI location = URI.create("/api/v1/products/" + created.getId());
return ResponseEntity.created(location).body(created);
}
@PutMapping("/{id}")
public ResponseEntity<Product> update(
@PathVariable Long id,
@Valid @RequestBody UpdateProductRequest request) {
return ResponseEntity.ok(productService.update(id, request));
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
productService.delete(id);
}
}
Request Mapping Annotations
| Annotation | HTTP Method | Use Case |
|---|---|---|
@GetMapping |
GET | Read resources |
@PostMapping |
POST | Create resources |
@PutMapping |
PUT | Full update |
@PatchMapping |
PATCH | Partial update |
@DeleteMapping |
DELETE | Delete resources |
@RequestMapping |
Any | Class-level base path |
REST Best Practices
Principles
- Stateless communication
- Client-server separation
- Cacheable responses
- Uniform interface
HTTP Methods
- GET: Read (idempotent, safe)
- POST: Create
- PUT: Full update (idempotent)
- PATCH: Partial update
- DELETE: Remove (idempotent)
Status Codes
- 2xx: Success
- 3xx: Redirection
- 4xx: Client error
- 5xx: Server error
Key Points
- Understanding Spring REST Controllers is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Spring REST Controllers in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Spring REST Controllers implementation
// Key aspects: validation, error handling, logging, testing
public class SpringRESTControllers {
// Production-ready implementation
} Identify and handle edge cases for Spring REST Controllers. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotency Write a testing strategy for Spring REST Controllers. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injection Quiz
1. What does @RestController combine?
2. How do you set the HTTP status to 201 for a POST?
3. What is a common mistake when implementing Spring REST Controllers?
Flashcards
Question
@RestController combines?
Click to reveal answer
Answer
@Controller + @ResponseBody (returns JSON)
Question
How to set HTTP status 201?
Click to reveal answer
Answer
ResponseEntity.status(201) or @ResponseStatus(HttpStatus.CREATED)
Question
Spring REST Controllers best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1. @RestController = @Controller + @ResponseBody
- 2. Use @GetMapping, @PostMapping, etc. for HTTP methods
- 3. ResponseEntity controls status, headers, and body
- 4. @Valid for request validation
Interview Tips
- • Build a complete REST controller
- • Know mapping annotations
Cheat Sheet
REST Controllers
- @RestController = @Controller + @ResponseBody
- Mappings: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping
- ResponseEntity: Wraps status + headers + body
- @Valid: Request validation