Skip to content

Lab 8 - Spring Boot REST

Taking a REST

The goal of this lab is for you to implement a very simple "RESTful" API using Spring's MVC framework.

Reference Docs

This reference is a useful guide to the different annotations available in Spring Boot for controllers


Run All Tests

Make sure all of your tests pass before getting started.


Create the REST Controller Class

  1. Create a new class named MealOrderApiController

  2. Add the @RestController annotation above the class definition, so it will look something like:

    @RestController
    public class MealOrderApiController {
    }
    
  3. Inside this class, write a method with a @GetMapping annotation, and a "request" parameter that will accept a burger order string:

    @GetMapping("/api/mealorder")
    public String mealOrder(@RequestParam("burger") String burgerOrderText) {
      return "Your order: " + burgerOrderText;
    }
    

Try it Out

  1. Run the application by opening up the Project window, right-clicking on the file MealKioskApplication and choosing Run 'MealKioskApplication', or, open up the MealKioskApplication file and use the Run Context shortcut: Ctrl-Shift-R (macOS) or Ctrl-Shift-F10 (Windows).

    As it starts, you'll see output in the console:

    2017-08-27 09:37:21.351  INFO 11472 --- [  Main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
    2017-08-27 09:37:21.355  INFO 11472 --- [  Main] com.welltestedlearning.mealkiosk.MealKioskApplication  : Started MealKioskApplication in 3.433 seconds (JVM running for 4.064)
    

    Once you see that last line, you'll know the application is ready to try out.

  2. Make a request by opening this URL in your browser:

    http://localhost:8080/api/mealorder?burger=cheese
    
  3. You should see something like

    Your order: cheese
    

    In your browser.


Build a Burger MealOrder

Now you'll use the MealBuilder to build an order with the specified burger options.

  1. Add the following code inside the mealOrder method in the MealOrderApiController class

    MealBuilder mealBuilder = new MealBuilder();
    mealBuilder.addBurgerString(burgerOrderText);
    
    MealOrder mealOrder = mealBuilder.build();
    return "Your order: " + mealOrder;
    
  2. Restart the application and try this URL:

    http://127.0.0.1:8080/api/mealorder?burger=cheese,bacon
    

Spring Docs

The official Spring framework docs can be found here: https://docs.spring.io/spring-framework/docs/current/reference/html

Specific docs for extracting path and query info from the URI are here: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestmapping-uri-templates