rest api springboot

Simple Way to Create REST API + Spring Boot Application (Step by Step Guide)

RESTFul Services are the most familiar way in a web application to communicate over cross-platform and with External applications in a feasible way. RESTFul Services are the easiest way to develop, build, and are easy to handle.

Spring Boot supports REST API with all kinds of features with the inbuilt mechanism. Spring Boot makes RESTFul Services an even easiest way to handle.

The below program explains you clearly to use REST API with Spring Boot Application.

Pre requisite to Create RESTFul Services with Spring Boot :

  1. Create Maven Dependency
  2. Create Model Class
  3. Create Controller Class
  4. Create DAO Class
  5. Create Main Class

1. First of all, we need to set up the Maven dependencies.

POM.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

		<!-- tag::actuator[] -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<!-- end::actuator[] -->

		<!-- tag::tests[] -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- end::tests[] -->
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

2. Create the Model Classes

Item.java

package com.example.model;

import java.util.Date;

public class Item {
private Integer itemId;
private String itemName;
private Date itemDate;
public Integer getItemId() {
	return itemId;
}
public void setItemId(int itemId) {
	this.itemId = itemId;
}
public String getItemName() {
	return itemName;
}
public void setItemName(String itemName) {
	this.itemName = itemName;
}
public Date getItemDate() {
	return itemDate;
}
public void setItemDate(Date itemDate) {
	this.itemDate = itemDate;
}

public  Item(Integer itemId, String itemName, Date itemDate) {
	this.itemId = itemId;
	this.itemName = itemName;
	this.itemDate = itemDate;
}


public String toString() {
	return "itemId : "+itemId+",itemName: "+itemName+",itemDate : "+itemDate;
}

}

The above class will hold the values of 3 attributes. These attribute values will be provided as services over HTTP Requests.

3. Create DAO classes to process the incoming request

Items.java

The above class will receive the request and process it, here we have two operations, addItem() and getItems().

package com.example.dao;
import java.util.ArrayList;
import java.util.List;


public class Items {

	private List<String> itemList = new ArrayList<String>();
	List<String> listData = new ArrayList<String>();
	
	public List<String> getItems(){
		
		return itemList;
	}
	
	public void addItem(String item){
		itemList.add(item.toString());
	}
	

}

4. Create the Controller Class

HelloController.java

package com.example.springboot;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.dao.Items;
import com.example.model.Item;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class HelloController {

	
	private Items itemsList = new Items();
	
	
	@PostMapping(path = "/add",consumes = "application/json",produces = "application/json")
	public ResponseEntity<Object> addItem(@RequestBody Item item){
		Logging.info("Items Add Method");
		itemsList.addItem(item.getItemName());
		Logging.info("Items Added");
		String status = "{\"Status\":\"Success\"}";
		return ResponseEntity.ok().body(status);
	}
	
	@PostMapping(path = "/fetch",consumes = "application/json",produces = "application/json")
	public ResponseEntity<String> fetchItem() throws JsonProcessingException{
		Logging.info("Fetching Item");
		ObjectMapper om = new ObjectMapper();
		return ResponseEntity.ok().body(om.writeValueAsString(itemsList.getItems()));
	}

}

The above class is the heart of the RestFul Services, the above class is defined with @RestController, and the Spring Container considers this class as RESTFUL services class and it will look for the methods whenever the external rest services are received.

We had created the method, one method to add an item and another method to fetch the added items. Since we didn’t use the DB Connection, we have used List and intermediatory holding place.

5. Create Main Class :

package com.example.springboot;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

	 private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
	
	public static void main(String[] args) {
		LOGGER.info("Spring Boot Application is Running Successfully");
		LOGGER.error("THIS IS ERROR BLOCK.....");
		SpringApplication.run(Application.class, args);
		
	}

}

The above class is annotated with @SpringBootApplication and the main method invoke the run() method and boot the spring boot application.

Output :

add rest_api spring boot
fetch rest api spring boot

Conclusion :

As mentioned above integrating the RestFul services with Spring Boot is the easiest one than you have ever thought. and RestFul Services are the main feasible features making the Spring Boot unique with auto-configuration methods.

Related Posts

Leave a Reply

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