Building RESTful Web services with Spring Boot

    Building RESTful Web services  with Spring Boot



What is Spring Boot?

Spring Boot provides a good platform for Java developers to develop a stand-alone and production-grade spring application that you can just run
You can get started with minimum configurations without the need for an entire Spring configuration setup.


Spring Boot offers the following advantages to its developers 
Easy to understand and develop spring applications
Increases productivity
Reduces the development time



Spring Boot is designed with the following goals 
To avoid complex XML configuration in Spring
To develop a production ready Spring applications in an easier way
To reduce the development time and run the application independently
Offer an easier way of getting started with the application



How Does it Work?


Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database.
The entry point of the spring boot application is the classcontains @SpringBootApplication annotation and the main method.
 Spring Boot automatically scans all the components included in the project by using @ComponentScan annotation.


Beans & Dependency Injection

Every Java-based application has a few objects that work together to present what the end-user sees as a working application. 
When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. 
Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent.


In Spring Boot, we can use Spring Framework to define our beans and their dependency injection. The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation.

If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation. All component class files are automatically registered with Spring Beans

What is REST Architecture ?

REST stands for REpresentational State Transfer. 
REST is web standards based architecture and uses HTTP Protocol. 
It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods.

In REST architecture, a REST Server simply provides access to resources and REST client accesses and modifies the resources. 
Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource like text, JSON, XML. JSON is the most popular one.


Following four HTTP methods are commonly used in REST based architecture.

  • GET − Provides a read only access to a resource.
  • POST − Used to create a new resource.
  • DELETE − Used to remove a resource.
  • PUT − Used to update a existing resource or create a new resource

REST Web Services

RESTful Web Services are basically REST Architecture based Web Services. 
In REST Architecture everything is a resource. 
RESTful web services are light weight, highly scalable and maintainable and are very commonly used to create APIs for web-based applications.

Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. 
This chapter will explain in detail about building RESTful web services using Spring Boot.

Rest Controller

The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and custom response. Its syntax is shown below 

@RestController
public class ProductServiceController { 

}

Request Body

The @RequestBody annotation is used to define the request body content type.

public ResponseEntity<Object> createProduct(@RequestBody Product product) {

}

Path Variable


The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {} as shown below .

public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) {

}

Request Parameter

The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a required parameter. We can also set default value for request parameters as shown here



public ResponseEntity<Object> getProduct(
   @RequestParam(value = "name", required = false, defaultValue = "honey") String name) {
}


Simple REST services


DemoApplication.java

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

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


Product.java



public class Product {
   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;
   }
}


ProductServiceController.java


import java.util.HashMap;
import java.util.Map;

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;

import com.tutorialspoint.demo.model.Product;

@RestController
public class ProductServiceController {
   private static Map<String, Product> productRepo = new HashMap<>();
   static {
      Product honey = new Product();
      honey.setId("1");
      honey.setName("Honey");
      productRepo.put(honey.getId(), honey);
      
      Product almond = new Product();
      almond.setId("2");
      almond.setName("Almond");
      productRepo.put(almond.getId(), almond);
   }
   
   @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
   public ResponseEntity<Object> delete(@PathVariable("id") String id) { 
      productRepo.remove(id);
      return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
   }
   
   @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
   public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { 
      productRepo.remove(id);
      product.setId(id);
      productRepo.put(id, product);
      return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
   }
   
   @RequestMapping(value = "/products", method = RequestMethod.POST)
   public ResponseEntity<Object> createProduct(@RequestBody Product product) {
      productRepo.put(product.getId(), product);
      return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
   }
   
   @RequestMapping(value = "/products")
   public ResponseEntity<Object> getProduct() {
      return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
   }
}

You can create an executable JAR file, and run the spring boot application by using the below Maven or Gradle commands .

Now hit the URL shown below in POSTMAN application and see the output.

 GET API URL is: http://localhost:8080/products


 POST API URL is: http://localhost:8080/products



PUT API URL is: http://localhost:8080/products/3


DELETE API URL is: http://localhost:8080/products/3

Comments

Popular posts from this blog

A Start To Learn Mongo DB

Intro To ReactJS

Building a React CRUD application using MERN stack