Spring Boot RESTful Web Services

Spring Boot RESTful Web Services

In this article, I am going to discuss Spring Boot RESTful Web Services with Examples. Please read our previous article where we discussed Spring Boot Logging using Logback.

Spring Boot RESTful Web Services

Spring boot can be used to develop RESTful web services. REST stands for Representational State Transfer. This is a software architectural style, most primarily used on the web, for networked applications. It uses simple HTTP to make calls between machines, rather than complex mechanics such as CORBA, RPC, or Soap.

How to Develop Spring Boot RESTful Web Services?

To develop RESTful web services using Spring Boot, follow these steps:

Step 1: Create a new project using Spring Initializr in VS Code.

Step 2: Navigate to the pom.xml file and add a dependency for spring-boot-starter-web.

How to Develop Spring Boot RESTful Web Services?

Step 3: Create a new sample class, called Fruit.java in src/main/com/dotnet/restful directory.

Step 4: Add the following lines of Java code into the newly created Fruit.java file:

How to Develop Spring Boot RESTful Web Services?

We have created two variables, id, and name, with their setters and getters. A constructor is also created. This class is a POJO class. POJO stands for Plain Old Java Object. This class will be used to store data that is displayed on a webpage.

Step 5: Create a new sample class, called FruitServiceController.java in src/main/com/dotnet/restful directory.

Step 6: Import the following packages into the class:

Spring Boot RESTful Web Services

We have imported the following packages:

  • On lines 4 and 5, the HashMap and Map packages are imported. These packages will be used to make a hash map of products (shown below)
  • From lines 8 to 14, we imported HTTP and RESTful classes

Step 7: Create and populate the hashmap which contains the products:

Spring Boot RESTful Web Services

Step 8: Create a method that will execute when a product is to be deleted, updated, or created:

Spring Boot RESTful Web Services

Step 9: Create a method that will display the products:

Spring Boot RESTful Web Services

Step 10: Install Postman application from https://www.postman.com/downloads/. This application shall be used to display the products.

Install Postman application

Step 11: Execute the application. The following output should be visible:

Spring Boot RESTful Web Services with Examples

Step 12: Open POSTMAN and enter the URL http://localhost:8080/products into the address bar. Ensure that the GET option is selected.

Spring Boot RESTful Web Services with Examples

Step 13: Once clicking on send, wait for the data to be received. This should be instantaneous because the server is being hosted on localhost (on the same computer). Ensure that the data entered in Step 7 is properly reflected in the output.

Spring Boot RESTful Web Services with Examples

Step 14: POST a new fruit to the map via Postman. This can be done by typing into the body section in Postman. Remember to set the operation to POST. Also, change the format of the request from “Text” to “JSON”. Then, click the send button.

Spring Boot RESTful Web Services with Examples

Once send button is clicked, the following output should be shown. This indicates that the POST operation is successful.

Spring Boot RESTful Web Services with Examples

Step 15: Update a record using Postman. Modify the URL to show the ID of the fruit that needs to be modified. Then, change the operation to PUT. Finally, enter a new name and click on send.

Spring Boot RESTful Web Services with Examples

The following output indicates that the update was successful:

Spring Boot RESTful Web Services with Examples

Step 16: Delete a fruit using Postman. Modify the URL to show the ID of the fruit that needs to be deleted. Then, change the operation to DELETE. Ensure that the request does not have a body and then click on send.

Spring Boot RESTful Web Services with Examples

The following output indicates that the fruit was deleted:

Spring Boot RESTful Web Services with Examples

Step 17: Stop the application by entering ctrl-c into the VS Code terminal. After this, the postman shall no longer be able to make requests to the application.

Spring Boot RESTful Web Services with Examples

Congratulations! You now know how to develop a RESTful API in Spring Boot.

The Complete Example Code

The complete code is as follows:

Fruits.java – The POJO Class
package com.dotnet.restful;

public class Fruits {
    private String id;
    private String name;
 
    public String getId()               {return id;}
    public void setId(String id)        {this.id = id;}
    public String getName()             {return name;}
    public void setName(String name)    {this.name = name;}

    public Fruits (String nid, String nname)
    {
        id = nid;
        name = nname;
    }
 }
FruitServiceController.java – The RESTful Controller
package com.dotnet.restful;

//Map Classes
import java.util.HashMap;
import java.util.Map;

//Required web classes
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FruitServiceController {
   private static Map<String, Fruits> productRepo = new HashMap<>();
   static {
      Fruits apple = new Fruits("1","Apple");
      productRepo.put(apple.getId(), apple);

      Fruits banana = new Fruits("2","Banana");
      productRepo.put(banana.getId(), banana);

      Fruits chiku = new Fruits("3","Chiku");
      productRepo.put(chiku.getId(), chiku);

      Fruits dragon = new Fruits("4","Dragon Fruit");
      productRepo.put(dragon.getId(), dragon);
   }
   
   @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
   public ResponseEntity<Object> delete(@PathVariable("id") String id)
   {
      if (!productRepo.containsKey(id)) throw new FruitNotFoundException();

      productRepo.remove(id);
      return new ResponseEntity<>("Fruit is deleted!", HttpStatus.OK);
   }
   
   @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
   public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Fruits product)
   { 
      if (!productRepo.containsKey(id)) throw new FruitNotFoundException();

      productRepo.remove(id);
      product.setId(id);
      productRepo.put(id, product);
      return new ResponseEntity<>("Fruit is updated!", HttpStatus.OK);
   }
   
   @RequestMapping(value = "/products", method = RequestMethod.POST)
   public ResponseEntity<Object> createProduct(@RequestBody Fruits product) {
      productRepo.put(product.getId(), product);
      return new ResponseEntity<>("Fruit is created!", HttpStatus.CREATED);
   }
   
   @RequestMapping(value = "/products")
   public ResponseEntity<Object> getProduct() {
      return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
   }
}
RestfulApplication.java – The class which contains the main() function:
package com.dotnet.restful;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RestfulApplication {
 public static void main(String[] args) {
  SpringApplication.run(RestfulApplication.class, args);
 }
}

In the next article, I am going to discuss Spring Boot Exception Handling. Here, in this article, I try to explain Spring Boot RESTful Web Services with Examples. I hope you enjoy this Spring Boot RESTful Web Services article.

Leave a Reply

Your email address will not be published. Required fields are marked *