Starting with Spring Boot Rest

Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. In this post we will create simple RESTful web services using Spring Boot.

For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into the pom.xml file.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId></dependency>

<?xml version=”1.0" encoding=”UTF-8"?>

<project xmlns=”http://maven.apache.org/POM/4.0.0"

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.7.3</version>

<relativePath /> <! — lookup parent from repository →

</parent>

<groupId>com.abhishek.spring.boot</groupId>

<artifactId>SpringBootHandsOn</artifactId>

<version>0.0.1-SNAPSHOT</version>

<name>SpringBootHandsOn</name>

<description>Spring Boot Demo Project</description>

<properties>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web-services</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<scope>runtime</scope>

<optional>true</optional>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>

Before we go ahead to build a RESTful web service, it is important that we have knowledge of the following annotations −

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 EmployeeController {
}

Request Mapping

The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET.

@RequestMapping(value="/employees")
public ResponseEntity<Object> getEmployees() { }

Request Body

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

public ResponseEntity<Object> createEmployee(@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 −

@GetMapping("/getEmpNo/{empNo}")
public Employee getEmployee(@PathVariable("empNo") String empNo) {
System.out.println("Data Fetched Successfully");return employeeDao.getEmployee(empNo);
}

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> getEmployee(
@RequestParam(value = "name", required = false, defaultValue = "honey") String name) {
}

Lets go back to create a simple Employee Spring boot project using various Http request methods.

Note : Here we are using custom java classes to have data using collection we are not using spring-boot-starter-jpa

Here we have a simple model class

package com.abhishek.spring.boot.model;

import org.springframework.stereotype.Component;

@Component

public class User {

private int id;

private String firstName;

private String lastName;

private String email;

private String country;

public User() {

}

public User(int id, String firstName, String lastName, String email, String country) {

super();

this.id = id;

this.firstName = firstName;

this.lastName = lastName;

this.email = email;

this.country = country;

}

public int getId() {

return id;

}

public String getFirstName() {

return firstName;

}

public String getLastName() {

return lastName;

}

public String getEmail() {

return email;

}

public String getCountry() {

return country;

}

public void setId(int id) {

this.id = id;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

public void setEmail(String email) {

this.email = email;

}

public void setCountry(String country) {

this.country = country;

}

@Override

public String toString() {

return “User [id=” + id + “, firstName=” + firstName + “, lastName=” + lastName + “, email=” + email

+ “, country=” + country + “]”;

}

}

Here we have simple java class to have business logic

package com.abhishek.spring.boot.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Repository;

import com.abhishek.spring.boot.model.User;

@Repository
public class UserDao {

private static final List<User> userList = new ArrayList<User>();

static {
createUser();
}

private static void createUser() {

User user1 = new User(1, “Heidi”, “Pitts”, “heidi.com”, “Costa Rica”);
User user2 = new User(2, “Daphne”, “Workman”, “daphne.com”, “UK”);
User user3 = new User(3, “Jemima”, “Duffy”, “jemima.com”, “Colombia”);
User user4 = new User(4, “Roary”, “Berg”, “roary.com”, “US”);
User user5 = new User(5, “Byron”, “Benjamin”, “byron.com”, “Germany”);
User user6 = new User(6, “Hermann”, “Pardon”, “hermann.com”, “Poland”);
User user7 = new User(7, “Rossie”, “Giovannini”, “rossie.com”, “Russia”);
User user8 = new User(8, “Killian”, “Brotherheed”, “killian.com”, “Indonesia”);
User user9 = new User(9, “Marga”, “Tice”, “marga.com”, “Spain”);
User user10 = new User(10, “Khalil”, “Edelheit”, “khalil.com”, “China”);
User user11 = new User(11, “Rebecka”, “Bavage”, “rebecka.com”, “Azerbaijan”);
User user12 = new User(12, “Athene”, “Errigo”, “athene.com”, “Canada”);
User user13 = new User(13, “Jarrod”, “Sterling”, “jarrod.com”, “Sweden”);
User user14 = new User(14, “Robinet”, “Furmonger”, “robinet.com”, “Portugal”);
User user15 = new User(15, “Abhishek”, “Singh”, “abhishek.com”, “Tanzania”);
User user16 = new User(16, “Filia”, “Withrington”, “filia.com”, “Bulgaria”);
User user17 = new User(17, “Padget”, “Cornish”, “padget.com”, “Belarus”);
User user18 = new User(18, “Olivie”, “Isabell”, “olivie.com”, “Greece”);
User user19 = new User(19, “John”, “Partlett”, “john.com”, “Argentina”);
User user20 = new User(20, “Tabbie”, “Cartan”, “tabbie.com”, “Singapore”);

userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);
userList.add(user6);
userList.add(user7);
userList.add(user8);
userList.add(user9);
userList.add(user10);
userList.add(user11);
userList.add(user12);
userList.add(user13);
userList.add(user14);
userList.add(user15);
userList.add(user16);
userList.add(user17);
userList.add(user18);
userList.add(user19);
userList.add(user20);
}

public User getUser(int id) {
return userList.get(id);
}

public User addUser(User user) {
userList.add(user);
return user;
}

public User updateUser(User user) {
userList.set(user.getId(), user);
return user;
}

public void deleteUser(int id) {
userList.remove(id);
}

public List<User> getAllUsers() {
Collection<User> c = userList.stream().collect(Collectors.toList());
List<User> list = new ArrayList<User>();
list.addAll(c);
return list;
}
}

And now we have a rest controller to expose api to the end users

package com.abhishek.spring.boot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.abhishek.spring.boot.dao.UserDao;
import com.abhishek.spring.boot.model.User;

@RestController
@RequestMapping(“/user”)
public class UserController {

@Autowired
private UserDao userDao;

@GetMapping(“/getAllUsers”)
public List<User> getUsers() {
List<User> list = userDao.getAllUsers();
System.out.println(“All Users Fetched Successfully”);
return list;
}

@GetMapping(“/getUser/{userId}”)
public User getUser(@PathVariable(“userId”) int id) {
System.out.println(“User Fetched Successfully”);
return userDao.getUser(id);
}

@PostMapping(“/saveUser”)
public User addUser(@RequestBody User user) {
System.out.println(“Creating User: “ + user.getId());
return userDao.addUser(user);
}

@PutMapping(“/UpdateUser”)
public User updateUser(@RequestBody User user) {
System.out.println(“(Updating User: “ + user.getId());
return userDao.updateUser(user);
}

@DeleteMapping(“/DeleteUser/{userId}”)
public void deleteUser(@PathVariable(“userId”) int id) {
System.out.println(“Deleting User: “ + id);
System.out.println(“User Deleted Successfully”);
userDao.deleteUser(id);
}

}

Thanks for reading…Keep Learning

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store