RESTful Web Services with Spring Framework

Monil Joshi
6 min readApr 2, 2019

In this blog series, we will see how to write Restful web services using spring boot. Please go through the following posts to understand what is API, RestApi, and postman basics which will be helpful to build the restful web services.

Prerequisites:

  1. Basic knowledge of HTTP requests.
  2. JDK installed on your machine.

If you do not have JDK installed on your machine go here and download JDK as per your operating system. Once you installed java as per guidelines go to terminal and hit command to check java version on your system.

$Java -version

You will get the Java version with other details.

java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)

Once that done, set the Java home path. Go to Java home folder. In Mac, java home is located at this location.

/Users/user_name/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home

Go to terminal hit command.

$vim .bash_profile//In bash_profile file paste below code.export JAVA_HOME = (/Users/monilj/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home)export PATH=$JAVA_HOME/bin:$M2_HOME/bin:$PATHpress Esc then :wq to save changes.
Note: If changes is not reflecting hit command
$source .bash_profile

Now download Spring Tool suits.

Spring tool suite is a development environment which is used to develop and run Rest services with spring and spring boot. Spring tool suits (STS) is an Eclipse-based development environment which is customized to developing spring application. It provides ready to use the environment to implement, debug, run and deploy your spring application. It is a cross-platform tool

You can download it from here which suits your OS. Go to Downloads and double click on the .dmg file. Drag and drop to the application.

Let’s create a spring boot project using Spring Tool suits.

  1. Open Spring Tool suits app. Select directory for a workspace where all your work will be saved and Launch.
  2. Go to File => New => Spring Starter Project
  3. Keep service URL as is https://start.spring.io
  4. Give some name to project. Keep other things as is and click on Next.
  5. On the next window we can add dependencies we required. These dependencies get added to pom.xml and maven will download it while building the project. For this time we need only Search for web dependencies. If you mouse hovers it you will get whole info about dependency. What that dependency is for, what it does and all.
  6. Type web in a dependency search box, check whatever required web dependencies and click on Finish.

Our project has a java folder directory structure. In src/main/java we have created our package. Inside that, we have our spring boot application. In src/main/resources folder we have “application.properties” file. We use this file to configure database access details. Pom.xml is a file where we add all our required dependencies. Two important maven dependencies we have

  1. spring-boot-starter-web: This dependency starts building web services.
  2. spring-boot-starter-test: This dependency starts testing out web services.

Important Note: We can run this project using any other IDE as well like NetBeans, IntelliJ.

There is an alternate method to create a new spring project. We can create the same project as we create above using Spring Initializer. Here are the steps to do that.

Go to https://start.spring.io/. Here we have Spring Initializer. It is a very quick way to create a spring boot application. We have to select a few options such as

  • Project with maven gradle: Select one option as per your requirement whether you want to create a project with maven or gradle.
  • Language: Java Kotlin Groovy Select one of language you want to write
  • Spring boot version: 2.13 Select spring boot version you want to use.
  • Click on More Options. Give project name, package name, and an artifact.
  • Select packaging as per requirement Jar War.
  • Select Java version.
  • Rest of the things keep it as it is.
  • Dependencies: We do have some suggestion as hint text. for eg
  1. Web: If we add this will support restful web services.
  2. Security: If we need security for our application.
  3. JPA: If we need Java Persistent API etc

For this project, we add only Web decency.

  • Click on Generate Project.

Once we click on generate the project. It will download a zip file which we can unzip and open in any IDE. You can try IntelliJ idea as well. It has the same project structure as we create a project using Spring Tool Spring. If Spring Tool Suite is not available then you can use Spring boot initializer.

Let’s create Rest controller class. After creating a spring boot application, to run it as a Restful application we have to create a rest controller, add some methods that accept HTTP requests and send some information.Under src/main/java/com.example.demo package creates one more package for controllers named as com.example.demo.controllers. If you create a package in IntelliJ it will create a controllers package under com.example.demo hierarchy. But in Spring tool suite (STS) it will create a different package. Under controller package, create a new class UserController.java. When the spring application starts, this class receives HTTP requests.

We need to add some annotations to receives HTTP requests.

  1. @RestController: This controller will register this class as Rest controller class and class will be able to receive HTTP requests.
  2. @RequestMapping: When we send some HTTP request, it sends through certain URL and that URL contains the path. Our controller will be responsible for the operations that have to do with the user. For example, getting user detail, update user detail. We will make request mapping for user controller to start with the user. @RequestMapping(“users”)
  3. When we send Http methods to define in the user controller, we will send it to http://localhost:8080.
  4. As it is running on apache tomcat 8080 we will provide the same port no.
  5. Then provide request mapping and appropriate method.
  6. Let’s start with the GET method. We will create a method which gets user information. This method should accept id which we will use to query a database and return JSON payload with user details. As it is a get method wrap this method into annotation @GetMapping

Create some more methods to handle HTTP POST, PUT and DELETE request in the same class later we see how to implement each method separately.

Create a method to handle the HTTP POST request. To bind this create user method to the HTTP POSTrequest we will use @PostMapping annotation.

Create a method to handle the HTTP PUT request. To bind this update user method to the HTTP PUT request we will use @PutMapping annotation.

Create a method to handle the HTTP DELETE request. To bind this delete user method to the HTTP DELETE request we will use @DeleteMapping annotation. Here is the complete code:

@RestController
@RequestMapping("users") // http://localhost:8080/users
public class UserController {
@GetMapping
public String getUser()
{
return "get users information method got called";
}
@PostMapping
public String createUser(){
return "create a user was called";
}
@PutMapping
public String updateUser(){
return "update user method got called";
}
@DeleteMapping
public String deleteUser(){
return "delete user method got called";
}
}

Now our application is ready to run. But as we are running it as the first time we need to create a run configuration.

From the Menu bar select “Run” then “Run Configuration”. One window will get open. From left pane select ‘spring boot app’ and Click on “‘New launch configuration” on left top corner of the same pop-up window. Provide

Give some random name for the configuration.

Name for configuration: sample-app-ws.

Select our project from drop down. Select Main Type: Click on search. We will get a list of matching items. Click on Apply and Run. It will start apache tomcat, deploy our application and we will able to send HTTP request to it. To cross verify this go to Http client postman. To trigger the getUser() we need to send HTTP GET request to the path that starts with User. Copy Url and use port 8080 as our tomcat is running on 8080 and path which we have defined for rest controller i.e RequestMapping is users.

GET http://localhost:8080/users

After hitting above request we should get a plain text which we are sending in getUser().

Response in postman: get users information method got called

You can try calling other HTTP requests. According to an HTTP request, we make the respective method will get a call and we should get the same response mentioned in the method.

Now everything is working fine. We have created methods for each CRUD (Create, read, update, delete) operations and used spring annotation to bind each of this method to appropriate HTTP method.

--

--

Monil Joshi

I am having an 8+ years of experience in software testing. Working with Web, Mobile and API technologies. Visit my GIT https://github.com/monilj