REST APIs: The Restaurant Menu

REST APIs: The Restaurant Menu in Java: Imagine a Restaurant. 1. The Waiter (The Controller): They take your order and bring it to the kitchen. 2.

Concept Explanation

Imagine a Restaurant.

  1. The Waiter (The Controller): They take your order and bring it to the kitchen.
  2. The Menu (The API Endpoints): A list of things you can ask for (e.g., "List of Burgers", "Add a new Pizza").
  3. 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

  1. The Path Variable: Write a controller method that takes two variables in the URL: /category/{catName}/product/{prodId}. Print them both.
  2. 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).
  3. The Status Code: Research ResponseEntity. How can you use it to return a 404 status code if a user is not found?