Skip to content
intermediatePhase ·

@RestController

Use @RestController for building REST APIs.

25m
0 problems
Topic Progress0%

@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

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0/3solved
Implement @RestController Annotation

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
}
@RestController Annotation Edge Cases

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, idempotency
@RestController Annotation Testing Strategy

Write 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 injection

Quiz

1. What does @RestController add beyond @Controller?

Question 1 options

2. What class wraps the HTTP response in REST APIs?

Question 2 options

3. What is the primary purpose of @RestController Annotation?

Question 3 options

4. What is a common mistake when implementing @RestController Annotation?

Question 4 options

Flashcards

Question

@RestController adds what?

Answer

@ResponseBody — methods return data, not view names

Question

ResponseEntity purpose?

Answer

Wraps response body, status code, and headers

Question

What is @RestController Annotation?

Answer

@RestController Annotation is a key concept in backend development.

Question

When to use @RestController Annotation?

Answer

Use @RestController Annotation when building production systems that require reliability, scalability, and maintainability.

Question

@RestController Annotation best practices

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