Lab 12: POST Order as JSON
Description¶
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.
Goals¶
- 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
CoffeeOrderRequestin thecom.welltestedlearning.coffeekiosk.adapter.in.apipackage. -
Add the following instance variables, and for each, create a getter & setter:
String customerNameString sizeString kindString creamer
-
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/src/test/javadirectory. -
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)Annotation?
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
-
Create a
CoffeeOrderand add aCoffeeItemfrom the information given in theCoffeeOrderRequest. -
Save the
CoffeeOrderin theCoffeeOrderRepositoryand hold onto the returned order, which will have theidset on it by the Repository. -
Return a
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 /api/coffee/orders endpoint.
Don't forget to set the Accept and Content-Type headers to application/json.
The JSON to send would look like:
{"customerName":"Post","size":"large","kind":"latte","creamer":"soy milk"}
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.
Once you've completed the above steps, let the instructor know. Do not continue to the next lab.