Module 2: Request Bodies & JSON (The Order Form)
📚 Module 2: Request Bodies & JSON
Focus: Moving from “Searching” to “Submitting.”
When a user wants to create a new Product, they don’t just send an ID in the URL. They send a whole packet of information (Name, Price, Description). We call this a Request Body.
🏗️ Step 1: The Request Body (The “Order Form”)
To accept complex data, we use the @RequestBody annotation.
🧩 The Analogy: The Paper Order Form
- A customer doesn’t just shout “Product!”
- They fill out a Form with their name, address, and credit card number.
- They hand this form to the Waiter (The Controller).
In Code:
@PostMapping
public Product createProduct(@RequestBody Product newProduct) {
// Spring converts the JSON into this Java object automatically!
return productRepository.save(newProduct);
}🏗️ Step 2: JSON (The “Digital Ink”)
The “Form” is written in JSON (JavaScript Object Notation). It’s a simple text format that looks like a Java object.
🧩 The Analogy: The Shipping Label
- Name: “Blue Shoes”
- Price: 49.99
- In JSON, it looks like this:
{
"name": "Blue Shoes",
"price": 49.99
}🏗️ Step 3: Response Entities (The “Feedback”)
When you finish an order, you don’t just walk away. You give the customer a Receipt and a Status.
- 200 OK: “Here is your data.”
- 201 Created: “I successfully built your new item.”
- 404 Not Found: “I couldn’t find what you asked for.”
- 500 Error: “The kitchen is on fire!”
In Code:
@GetMapping("/{id}")
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
return productRepository.findById(id)
.map(product -> ResponseEntity.ok(product)) // Return 200
.orElse(ResponseEntity.notFound().build()); // Return 404
}🥅 Module 2 Review
- @RequestBody: Accepting a whole object from a user.
- JSON: The text format for sharing data.
- ResponseEntity: Controlling the “Status Code” of your answer.
- Automatic Conversion: Spring (using a tool called Jackson) turns JSON text into Java Objects instantly.