Skip to content
intermediatePhase ·

REST Controllers in Spring

Build complete REST endpoints with Spring MVC.

40m
0 problems
Topic Progress0%

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

  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 Spring REST Controllers

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
}
Spring REST Controllers Edge Cases

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
Spring REST Controllers Testing Strategy

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?

Question 1 options

2. How do you set the HTTP status to 201 for a POST?

Question 2 options

3. What is the primary purpose of Spring REST Controllers?

Question 3 options

4. What is a common mistake when implementing Spring REST Controllers?

Question 4 options

Flashcards

Question

@RestController combines?

Answer

@Controller + @ResponseBody (returns JSON)

Question

How to set HTTP status 201?

Answer

ResponseEntity.status(201) or @ResponseStatus(HttpStatus.CREATED)

Question

What is Spring REST Controllers?

Answer

Spring REST Controllers is a key concept in backend development.

Question

When to use Spring REST Controllers?

Answer

Use Spring REST Controllers when building production systems that require reliability, scalability, and maintainability.

Question

Spring REST Controllers 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.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