Concept Explanation
Imagine a Restaurant.
- The Waiter (The Controller): They take your order and bring it to the kitchen.
- The Menu (The API Endpoints): A list of things you can ask for (e.g., "List of Burgers", "Add a new Pizza").
- The Language (HTTP Methods):
- GET: "Please give me the info."
- POST: "Please create something new."
- PUT: "Please update something existing."
- DELETE: "Please remove this."
Code Structure (The Controller)
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping("/{id}")
public Product getProduct(@PathVariable int id) {
return productService.findById(id);
}
@PostMapping
public void addProduct(@RequestBody Product product) {
productService.save(product);
}
}
Best Practices
- Use Nouns, Not Verbs: Your URL should be
/api/users, not/api/getUsers. The HTTP Method (GET) already tells us what you are doing. - Return Correct Status Codes:
- 200 OK: Everything is great.
- 201 Created: You successfully added something.
- 404 Not Found: You asked for something that doesn't exist.
- 500 Error: The kitchen (server) crashed.
Practice Exercises
- The Path Variable: Write a controller method that takes two variables in the URL:
/category/{catName}/product/{prodId}. Print them both. - The JSON Search: Research
@RequestBody. How does Spring turn a JSON string from a browser into a Java Object? (Hint: The library is called Jackson). - The Status Code: Research
ResponseEntity. How can you use it to return a 404 status code if a user is not found?