Skip to content

Lab 12: POST Order as JSON

Description

Now that there's a place to store orders and a way to find them, we can now focus on creating them via POST.

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.

  1. Create a new class CoffeeOrderRequest in the com.tedmyoung.coffeekiosk.adapter.in.api package.

  2. Add the following instance variables, and for each, create a getter & setter:

    • String customerName
    • String size
    • String kind
    • String creamer
  3. Create a no-arg constructor, and a constructor that takes all the arguments.

  4. Copy the CoffeeOrderPostTest.java test class to the com.tedmyoung.coffeekiosk.adapter.in.api package under the /src/test/java directory.

  5. 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.

  1. Create a new method that has the following signature:

    public ResponseEntity createCoffeeOrder(@RequestBody CoffeeOrderRequest coffeeOrderRequest)
    
  2. Create a CoffeeOrder and add a CoffeeItem from the information given in the CoffeeOrderRequest.

  3. Save the CoffeeOrder in the CoffeeOrderRepository and hold onto the returned order, which will have the id set on it.

  4. Return a created response like this:

    return ResponseEntity.created(URI.create("/api/coffee/orders/" + savedCoffeeOrder.getId())).build();
    
  5. 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.