Lab 12: POST Order as JSON
Now that there's a place to store orders and a way to find them, we can now focus on creating them via POST.
- Learn how to accept an incoming POST request
- Understand how Spring converts incoming media type to objects
a. Incoming Request DTO¶
This step creates a DTO representing the incoming JSON for placing a coffee order.
Create a new class
Add the following instance variables, and for each, create a getter & setter:
Create a no-arg constructor, and a constructor that takes all the arguments.
Copy the CoffeeOrderPostTest.java test class to the
com.tedmyoung.coffeekiosk.adapter.in.apipackage under the
Run test, which should fail with a 404 (Not Found) as there's no endpoint for POST (yet).
b. POST Mapping¶
Now add a method to the
CoffeeOrderController to handle the POST.
Create a new method that has the following signature:
public ResponseEntity createCoffeeOrder(@RequestBody CoffeeOrderRequest coffeeOrderRequest)
CoffeeOrderand add a
CoffeeItemfrom the information given in the
CoffeeOrderRepositoryand hold onto the returned order, which will have the
idset on it.
createdresponse like this:
return ResponseEntity.created(URI.create("/api/coffee/orders/" + savedCoffeeOrder.getId())).build();
Run the test. If you've done everything correctly, the test should now pass.
c. Try POSTing¶
Using a tool like
curl, Postman, or similar, POST a creation request to the
Don't forget to set the
Content-Type headers to
The JSON to send would look like:
The POST request will return a
Location: header containing the URI that you can
GET to see the created order.