@RestController
@RestController — REST API
@RestController
@RequestMapping("/api/products")
@Tag(name = "Products", description = "Product management")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping
public ResponseEntity<List<Product>> getAll() {
return ResponseEntity.ok(productService.getAll());
}
@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 product = productService.create(request);
return ResponseEntity.status(201).body(product);
}
@PutMapping("/{id}")
public ResponseEntity<Product> update(
@PathVariable Long id,
@Valid @RequestBody UpdateProductRequest request) {
return ResponseEntity.ok(productService.update(id, request));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
productService.delete(id);
return ResponseEntity.noContent().build();
}
}
ResponseEntity Usage
| Method | Status | Use Case |
|---|---|---|
ResponseEntity.ok() |
200 | Successful GET/PUT/PATCH |
ResponseEntity.status(201) |
201 | Successful POST |
ResponseEntity.noContent() |
204 | Successful DELETE |
ResponseEntity.notFound() |
404 | Resource not found |
ResponseEntity.badRequest() |
400 | Invalid input |
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 @RestController Annotation 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 @RestController Annotation in a backend system. Consider scalability, error handling, and production readiness.
Solution
// @RestController Annotation implementation
// Key aspects: validation, error handling, logging, testing
public class RestControllerAnnotation {
// Production-ready implementation
}Identify and handle edge cases for @RestController Annotation. 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, idempotencyWrite a testing strategy for @RestController Annotation. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. What does @RestController add beyond @Controller?
2. What class wraps the HTTP response in REST APIs?
3. What is the primary purpose of @RestController Annotation?
4. What is a common mistake when implementing @RestController Annotation?
Flashcards
Question
@RestController adds what?
Click to reveal answer
Answer
@ResponseBody — methods return data, not view names
Question
ResponseEntity purpose?
Click to reveal answer
Answer
Wraps response body, status code, and headers
Question
What is @RestController Annotation?
Click to reveal answer
Answer
@RestController Annotation is a key concept in backend development.
Question
When to use @RestController Annotation?
Click to reveal answer
Answer
Use @RestController Annotation when building production systems that require reliability, scalability, and maintainability.
Question
@RestController Annotation 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.All methods return data (JSON), not view names
- 3.ResponseEntity wraps status, headers, and body
- 4.Use @Valid for request validation
Interview Tips
- •Build REST endpoints with @RestController
- •Know ResponseEntity methods
Cheat Sheet
@RestController
- = @Controller + @ResponseBody (returns JSON)
- ResponseEntity: ok(200), status(201), noContent(204)
- @Valid: Request validation
- @RequestBody: Deserialize JSON to object