Skip to content

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.

  1. Create a new class CoffeeOrderRequest in the 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 test class to the package under the /src/test/java directory.

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

  1. 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:

  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 by the Repository.

  4. Return a created response like this:

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

Once you've completed the above steps, let the instructor know. Do not continue to the next lab.