Creating REST Service with Spring Boot

Creating CRUD REST Service with Spring Boot

This guide will help you create  REST service using Spring Boot. In a modern day, if yo, want to create a rest api in java ,  Spring Boot is the answer . Spring Boot Applications are super easy to configure and start .If you are a beginner to Spring Boot i would recommend

you first understand and learn about Spring MVC.We are going to  show how to create a simple Spring Boot Application and write rest service using that.

Tools you will need:-

  • Maven 3 – Build Tool
  • Eclipse – Our Fav IDE
  • JDK 1.8
  • Spring Boot

What is REST ?:-

REST is an architectural style for designing distributed systems. It is not a standard but a set of constraints, such as being stateless, having a client/server relationship, and a uniform interface. REST is not strictly related to HTTP, but it is most commonly associated with it.

Following are the Set Of Constraints a REST Service must have:-

  1. Server:- Which delivers a service
  2. Client:- Entity which consumes the service
  3. Service is Always Stateless

What Do We Create ?:-

In order to create rest services, we are declaring some endpoints for spring Rest.A Simple rest service with following Endpoints .

Type End Point Description
POST /Users save or add a user
GET /Users get list of all users

Every Rest endpoint needs a type associated with that. In this Rest Service with Spring Boot we are using POST and GET, there are other Http types as well such as PUT, DELETE, CONNECT, OPTIONS, HEAD.

Why Do we need these different types?

They are basically known as request methods which are treated as an indicator to our server and  perform some specific set of Actions. Click Here and Understand More about this.

Whooh!  Let’s Create Our First Rest Service With Spring Boot !!

Create Rest Service With Spring Boot  is Super easy. Let’s Open this Url in your Browser Click  Here

It will Open Something Like in image shown below, enter the dependency as Web, package name as com.frugalis , enter any name of your choice in the name field and then click on Generate Project.We are creating a dummy application and store Users in a list and return list.

Project Structure:-

SampleRestApplication.Java:- 

The main method contains run() method which executes and start the spring boot.We don’t need any external tomcat as spring boot has its embedded tomcat. Once we run this Java class embedded tomcat is started.

We have used @ComponentScan(basePackages=”com.frugalis”), this annotation tells spring to scan spring beans from the specified package and load into memory.

package com.frugalis.SampleRest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages="com.frugalis")
public class SampleRestApplication {

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

Create Bean:-

create a bean named User.java, we are going to do all user related operations here.We are overriding equals and hashcode method to check equality.One of the books that i follow for creating and Understanding Spring boot is below at its latest edition.

User.java:-

package com.frugalis.beans;

public class User {

	String name;
	String age;
	int userId;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((age == null) ? 0 : age.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (age == null) {
			if (other.age != null)
				return false;
		} else if (!age.equals(other.age))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	
	
}

Writing Our Service:-

We are going to create a service class and implement our logic in the service class. We are going to create a list and store user input in the User object.We are storing and retrieving from a list and return data on the basis of requested data.Let’s write a UserService interface.

UserService.java:-

package com.frugalis.service;

import com.frugalis.beans.User;


public interface UserService {

	public User saveUser(User inUser);
	public Object[] getAllUsers();
	
}

UserServiceImpl.java:-

package com.frugalis.serviceImpl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;

import com.frugalis.beans.User;
import com.frugalis.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	public static List<User> userStoragLe = new ArrayList<User>();

	@Override
	public User saveUser(User inUser) {
		int index = userStoragLe.size();

		if (!userStoragLe.contains(inUser)) {
			inUser.setUserId(index + 1);
			userStoragLe.add(inUser);
			return inUser;
		}

		return inUser;
	}

	@Override
	public Object[] getAllUsers() {

		return userStoragLe.toArray();
	}

}

HelloWorldController :-

We are writing a controller which is having an annotation.@RestController.We are returning Objects from our controller methods which get automatically converted to JSON format.We are using.@PostMapping and @GetMapping to handle POST and GET requests for url /Users respectively.

package com.frugalis.controller;

import org.springframework.beans.factory.annotation.Autowired;
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.frugalis.beans.User;
import com.frugalis.service.UserService;

@RestController
public class HelloController {

	@Autowired
	UserService userService;
	
	@PostMapping("/users")
	public User save(@RequestBody User u) {
		return userService.saveUser(u);
	}
 
	@GetMapping("/users")
	public Object[] getAll() {
		return userService.getAllUsers();
 
	}
}

POST  (/users)

GET (/users)

Rest Service SpringBoot

Download Code