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¶
-
Create a new class named
MealOrderApiController
-
Add the
@RestController
annotation above theclass
definition, so it will look something like:@RestController public class MealOrderApiController { }
-
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¶
-
Run the application by opening up the Project window, right-clicking on the file
MealKioskApplication
and choosingRun 'MealKioskApplication'
, or, open up theMealKioskApplication
file and use the Run Context shortcut:Ctrl-Shift-R
(macOS) orCtrl-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.
-
Make a request by opening this URL in your browser:
http://localhost:8080/api/mealorder?burger=cheese
-
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.
-
Add the following code inside the
mealOrder
method in theMealOrderApiController
classMealBuilder mealBuilder = new MealBuilder(); mealBuilder.addBurgerString(burgerOrderText); MealOrder mealOrder = mealBuilder.build(); return "Your order: " + mealOrder;
-
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