Lab 12: POST Order as JSON
Now that there's a place to store orders, and a way to find them, we can turn to creating them with a POST request.
- 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.welltestedlearning.coffeekiosk.adapter.in.apipackage under the
Run the 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)
What annotation do you need on this method? These docs might help you: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestmapping
CoffeeOrderand add a
CoffeeItemfrom the information given in the
CoffeeOrderRepositoryand hold onto the returned order, which will have the
idset on it by the Repository.
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.
Once you've completed the above steps, let the instructor know. Do not continue to the next lab.