Module 1: REST Controllers (The Waiter)
📚 Module 1: REST Controllers
Focus: Moving from “Calculations” to “Communication.”
A REST Controller is the front door of your application. It’s where external users (websites, apps) send requests to get data.
🏗️ Step 1: The Controller (The “Waiter”)
In standard Spring Web, we use the @RestController annotation to mark a class as a “Waiter.”
🧩 The Analogy: The Fine Dining Waiter
- The Greeting: The user sends a request to a specific URL (The Table).
- The Order: The Controller takes the request and decides which “Chef” (Service) should handle it.
- The Delivery: The Controller takes the data from the Chef and hands it back to the user in a format they understand (JSON).
In Code:
@RestController
@RequestMapping("/api/products") // The "Section" of the restaurant
public class ProductController {
@GetMapping // The "Greeting" (READ)
public List<String> getAllProducts() {
return List.of("Laptop", "Mouse", "Keyboard");
}
}🏗️ Step 2: Mapping (The “Address System”)
How does the internet know which method to call? We use Mapping Annotations.
🧩 The Analogy: The Mall Map
- @GetMapping: “I want to LOOK at something.” (Read).
- @PostMapping: “I want to ADD something new.” (Create).
- @PutMapping: “I want to FIX/REPLACE something.” (Update).
- @DeleteMapping: “I want to REMOVE something.” (Delete).
🏗️ Step 3: Path Variables (The “Target”)
Sometimes you want to look at one specific item. We use {id} in the URL.
🧩 The Analogy: The Specific Seat
- URL:
/api/products/5 - “Give me the product sitting in seat number 5.”
In Code:
@GetMapping("/{id}")
public String getProductById(@PathVariable Long id) {
return "Product Details for ID: " + id;
}🥅 Module 1 Review
- @RestController: The class that handles web requests.
- @RequestMapping: The base address for the controller.
- HTTP Verbs: GET, POST, PUT, DELETE.
- @PathVariable: Getting specific IDs from the URL.