Session 2.1: Spring Boot - Rest API - [Pre Lab]
Create a new Spring Boot project (com.esi.week2), you can refer to last week's materials for that.
This week, we have one entity:
- product
To keep our code organized, we need a package for each created entity.
- com.esi.week2
- com.esi.week2.products
1. To create a new package, right-click on the main package (week2
in this example), then, choose "new folder", and give it the name products
.
We need to create 2 new classes within the products package, as follows:
products └── Product └── ProductController
2. We start by creating the Product class, right click on the products
package. Then, create a new file, and give it the name Product.java, which will open after pressing enter:
package com.esi.week2.products; public class Product { // Add the following attributes to the product class private String id; private String name; private String description; private BigDecimal price; // Some of these annotations will appear with a red line under indicating an error. // Hover over each one of them and if you choose "quick fix", it will suggest you to "import the required package". }
3. Generate an empty constructor, generate a constructor using all fields, and generate getters and setters for all attributes of the class. The easiest way to do that is by:
- rightclick within the class -> Java code generator -> Generate Empty Constructor
- rightclick -> Java code generator -> Generate Constructor Using All Fields
- rightclick -> Java code generator -> Generate Getters and Setters
4. Now, we create our second class ProductController the same way we created the Product class.
5. ProductController will be our controller, so we need to add the @RestController
annotation. We also need to define an ArrayList of products to use in our example today since we still do not have a database to store and retrieve our data. Modify the ProductController to look as follows and import the required packages.
package com.esi.week2.products; import org.springframework.web.bind.annotation.RestController; @RestController public class ProductController { private List<Product> products = new ArrayList<>(Arrays.asList( new Product("01", "Heavy vehicle", "Can be used for heavy work", BigDecimal.valueOf(1200)), new Product("02", "Medium vehicle", "Can be used for medium work", BigDecimal.valueOf(1800)), new Product("03", "Light vehicle", "Can be used for light work", BigDecimal.valueOf(2200)) )); }
ProductController will provide five different request handlers (functions) to deal with the five different HTTP requests we have: (1) fetch all products, (2) fetch a product based on its id, (3) create a product, (4) update a product based on its id, and (5) delete a product based on its id.
Method | URI | Action |
GET | products | Fetch all products |
GET | products/:id | Fetch a product based on its id |
POST | products | Create a new product |
PUT | products/:id | Update a product based on its id |
DELETE | products/:id | Delete a product based on its id |
6. Copy the code within the two horizontal lines to your controller, we will uncomment each of these handlers and test how they work using Postman.
package com.esi.week2.products; import org.springframework.web.bind.annotation.RestController; @RestController public class ProductController { private List<Product> products = new ArrayList<>(Arrays.asList( new Product("01", "Heavy vehicle", "Can be used for heavy work", BigDecimal.valueOf(1200)), new Product("02", "Medium vehicle", "Can be used for medium work", BigDecimal.valueOf(1800)), new Product("03", "Light vehicle", "Can be used for light work", BigDecimal.valueOf(2200)) )); ------------------------------------------------------------------------- /* @GetMapping("/products") public List<Product> getAllProducts(){ return products; } */ // For a simple description of Java Lambda expressions https://www.w3schools.com/java/java_lambda.asp /* @GetMapping("/products/{id}") public Product getProduct(@PathVariable String id){ return products.stream().filter(p->p.getId().equals(id)).findFirst().get(); } // Here we use products, an ArrayList, as a source for a stream, and then perform a filter-map // on the stream to obtain the first element that has the same passed id, then, returns it. */ /* @PostMapping("/products") public void addProduct(@RequestBody Product product){ products.add(product); } /* @PutMapping("/products/{id}") public void updateProduct(@RequestBody Product product, @PathVariable String id){ for (int i = 0; i < products.size(); i++){ Product p = products.get(i); if (p.getId().equals(id)){ products.set(i, product); return;}} } */ //size() is a method implemented by all members of Collection (lists, sets, stacks,...). It returns // the number of elements the collection contains. /* @DeleteMapping("/products/{id}") public void deleteProduct(@PathVariable String id){ products.removeIf(p->p.getId().equals(id)); } */ ------------------------------------------------------------------------- }