Building a RESTful Web Service using Spring Boot
Table of Contents
Introduction
RESTful stands for Representational State Transfer, but it is also called REST.
RESTful is an architectural style where the application defines a resource that identifies through URI (Uniform Resource Identifier). Therefore, it uses to enable interaction between the client application and RESTful application which is work by sending HTTP requests. Including GET, POST, PUT, and DELETE requests to URI to which the resource is mapped.
The Figure 1 illustrates the interaction between the client and the RESTful application.
Let’s say the resources defined by RESTful application are for data management. Therefore, the client application can perform CRUD (CREATE-READ-UPDATE-DELETE) to manage the data by sending HTTP requests to the RESTful application.
For the Figure 1 example, the client application sent a /createUser
request to add a new user account. Therefore, the /createUser
request uses the POST method which includes BodyRequest
, which carries the data of a new user account. When the data received by the RESTful application, it will send an HTTP response back to the client application. And to tell if the data is successfully added to the database.
What you need
- It is necessary to have a bit of knowledge in HTML and CSS. (Refer to the HTML, CSS, and Javascript Tutorial)
- Java fundamental (Refer to the Java Tutorial)
- Eclipse or Spring Tool Suite (STS) (Refer to the Spring Quick Start Tutorial)
Spring RESTful configuration in Spring Tool Suite (STS)
Let’s create a new project for a RESTful application. The configuration is the same as the spring MVC application. However, this time we don’t need a Thymeleaf since we only focus on web services. Which can also operate without the user interface, and works through HTTP requests.
For the Spring MVC tutorial, you can go to this post: http://lgeratech.com/2020/05/build-spring-mvc-application-using-spring-boot-framework/
If you don’t have any idea what is STS, you can refer to this link for Eclipse STS setup: http://lgeratech.com/2020/05/spring-framework-quick-start/#Eclipse_setup
Or if you don’t have eclipse yet, you can download STS directly to this link: https://spring.io/tools
For the project creation, I will call the project WebRESTfulService
, and select project dependencies. Including Spring Boot DevTools
, Spring Web
:
RESTful Application Walkthrough
This tutorial will show you how to build a RESTful application. And we are going to use the previous example, which is in the Spring MVC application. But, this time we don’t need to use the user interface or VIEW since we are only focusing on HTTP requests or RESTful. And we will create HTTP requests for user management, which handles CRUD (CREATE-READ-UPDATE-DELETE) processes.
Additionally, the RESTful application that we are going to create in this tutorial will not cover connectivity to the database. However, we will discuss that topic in the next tutorial which is the spring JDBC tutorial.
Create User Request
For the user creation, we are going to create an HTTP request using POST method to handle the user creation function.
The POST is a type of method request that accepts the data enclosure using the request body of the HTTP request. The request body can be written in JSON (JavaScript Object Notation) or XML format. However, the most common format in web applications is the JSON format. Later we will use JSON format to add user.
Retrieve Users Request
We are going to create an HTTP request using GET method to handle the user list retrieval.
GET method is one of the most common methods used in RESTful applications. However, unlike the POST method, this method doesn’t have a request body to enclose data. But, you can use the HTTP parameter to include data to the request. Furthermore, this method only design for reading data or resources. Meaning, this method should not allow any modification in the data or resources.
Update User Request
We will use PUT method to create a HTTP request that handles data modification.
The PUT method is a similar POST method, it does modification in the resource using enclosed data in the request body. However, the PUT method is commonly used for updating data rather than for creating new data. Don’t confuse about these two methods. Only remember that the POST is for creating new resources, and PUT is for updating any resources.
Delete User Request
For the final request, we will create HTTP request to delete user data, and we will use DELETE method to handle that request.
The DELETE method uses to delete resources or data in the RESTful application. And unlike POST and PUT methods, this method doesn’t allow the request body to delete data. However, instead of using body requests, it uses a URL parameter to send a reference to the application which use to delete specific data.
User Model
Let’s start our RESTful application by creating a model. Add new class and name it as User
, And then place it in com.lgeratech.demo.models
package.
In the User.java
, add fields for id
, name
, age
, and gender
. And then encapsulate fields with getter
and setter
. Therefore, the code should same as below:
package com.lgeratech.demo.models;
public class User {
private Integer id;
private String name;
private Integer age;
private String gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
The user model is same as the model in the previous tutorial. However, we added new field id which uses for data reference or to make data unique.
User Controller
The controller class contains all of the HTTP requests of the RESTful application, for more info about the Controller you can refer to this post: http://lgeratech.com/2020/05/build-spring-mvc-application-using-spring-boot-framework/#Introduction
Create another file name as UserController.java
for the controller of our application. and then add new package com.lgeratech.demo.controllers
to place all controllers if there is any. And then copy and paste the code below into the UserController.java
file:
package com.lgeratech.demo.controllers;
import java.util.ArrayList;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import com.lgeratech.demo.models.User;
@RestController
public class UserController {
ArrayList<User> users = new ArrayList<User>();
@PostMapping(value = "/createUser")
public ResponseEntity<String> createUser(@RequestBody User user){
int userId = users.size() > 0 ? users.get(users.size() - 1).getId() + 1 : 1;
user.setId(userId);
users.add(user);
return new ResponseEntity<String>("User has been added succesfully", HttpStatus.OK);
}
@GetMapping(value = "/retrieveUsers")
public ResponseEntity<ArrayList<User>> retrieveUserList(){
return new ResponseEntity<ArrayList<User>>(users, HttpStatus.OK);
}
@PutMapping(value = "/updateUser")
public ResponseEntity<String> updateUser(@RequestBody User user){
for (int i = 0; i < users.size(); i++) {
if(users.get(i).getId() == user.getId()) {
users.set(i, user);
break;
}
}
return new ResponseEntity<String>("User has been updated succesfully", HttpStatus.OK);
}
@DeleteMapping(value = "/deleteUser/{id}")
public ResponseEntity<String> deleteUser(@PathVariable Integer id){
users.removeIf(user -> user.getId() == id);
return new ResponseEntity<String>("User has been deleted succesfully", HttpStatus.OK);
}
}
In the spring MVC tutorial, we use @Controller annotation instead of @RestController annotation. Therefore, the @Controller is used for spring MVC application which is return view as a response. While @RestController designs for RESTful application, and it specializes version of @Controller that uses @ResponseBody as a default return. Therefore, if the client sent a request to RESTful application, it will return a Response body, which is can be objects, pure text, etc..
As the previous section mentioned earlier that our application didn’t connected to the database. However, as of now, we will use ArrayList class for the local storage of our application:
ArrayList<User> users = new ArrayList<User>();
createUser
method
In the createUser method, we use @PostMapping
annotation to define a mapping request value which is /createUser
to handle the create user function. And we use @RequestBody
annotation to directly parse the HTTP request body into the user model:
@PostMapping(value = "/createUser")
public ResponseEntity<String> createUser(@RequestBody User user){
int userId = users.size() > 0 ? users.get(users.size() - 1).getId() + 1 : 1;
user.setId(userId);
users.add(user);
return new ResponseEntity<String>("User has been added succesfully", HttpStatus.OK);
}
The userId
variable generates an id field for new user data. It checks the user list if there are existing data. Therefore, if the condition is true, the variable will get the last user and get the id, and then plus 1 to produce a unique id. As a result, the unique id will be set to the new user data, and we will use the id to get the specific user data:
int userId = users.size() > 0 ? users.get(users.size() - 1).getId() + 1 : 1;
user.setId(userId);
And we use add()
method in ArrayList
to add the new user to the user list:
users.add(user);
After adding data in the list, the method will return a response using ResponseEntity
which contains String to tell when the request is success:
return new ResponseEntity<String>("User has been added succesfully", HttpStatus.OK);
ResponseEntity
represents as HTTP response that can use to include response body, status, and header as a return value.
Additionally, there is alternative way of defining request mapping is through @RequestMapping
. However, we use @PostMapping
annotation instead to act as a shortcut for @RequestMapping(value = "/createUser", method = RequestMethod.POST)
.
retrieveUsers
method
To get the list of users, we added a method that defines HTTP GET mapping which is /retrieveUsers
. And to return the whole list, we commonly use ResponseEntity
to include the user list in the HTTP response body:
return new ResponseEntity<ArrayList<User>>(users, HttpStatus.OK);
updateUser
method
For the updateUser
request, we added @PutMapping
to define a request mapping which is /updateUser
for user update function. And to update a specific user, we added a for loop statement that will check the id of each user in the user list. When one of the user in the list gets the exact id of the user in the request body. Therefore, the user will replace the old state with the new state which is specified in the request body:
for (int i = 0; i < users.size(); i++) {
if(users.get(i).getId() == user.getId()) {
users.set(i, user);
break;
}
}
deleteUser
method
For the final request, we added @DeleteMapping
annotation to handle the /deleteUser
mapping which is for the user delete function. And we used the removeIf()
method in the ArrayList
class to check if the parameter id matches one of the user ids in the list. And if one of the users meet the condition, therefore, it will remove in the list:
users.removeIf(user -> user.getId() == id);
Launch the application
If you know how to execute the application please skip this section.
You can now launch the application, using your eclipse, STS or using Cmd, in eclipse click the green icon , then look for the WebRESTfulService
, and then right click and click the (Re)start
. In Cmd go to your project location then run this script ./mvnw spring-boot:run
.
Test the Application
There are two common ways to test HTTP requests of a RESTful application. Firstly, if you want to test using client application you can install Postman Interceptor in chrome web store extensions. Secondly, if you want to test the HTTP request in cmd, you can install curl. However, this section will not cover the installation of those tools. Therefore, this section will only cover the HTTP requests execution using the Postman application.
POST Request Execution
When the Postman is already open, select the POST
method in the drop-down list at the left side of the request URL bar. And enter localhost:8080/createUser
in the request URL bar:
In the Body tab, select raw radio button, and then select JSON(application/json)
in the drop-down list. The final configuration will be look like this:
As you can see above image, there is a JSON object in the body request. Therefore, it is for the user object which includes when the POST request is sent to the RESTful application:
{
"name":"leo",
"age":24,
"gender":"Male"
}
Copy and paste the JSON object and then click send to execute the request. After sending a POST request, you will receive a response body which is written in pure text: User has been added succesfully
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is commonly used in web application, and it is easy to understand and read by a simple person.
GET Request Execution
You can get the user list by executing GET request, change the method to GET in drop-down list. And enter the mapping request localhost:8080/retrieveUsers
in the request URL bar, and then click the send button to execute the request:
PUT Request Execution
For the put request, change the method to PUT in the drop-down list. And enter the mapping request localhost:8080/updateUser in the request URL bar. Make sure that in the body tab the raw and JSON(application/json) are selected. And before you click send you must include the request body and specifies the id of the user you want to update:
To check the data if successfully updated, you can re-execute the GET request which is localhost:8080/retrieveUsers
.
DELETE Request Execution
For the delete request, do the same thing, change the method to DELETE, and enter the URL localhost:8080/deleteUser/2
. For the example request URL, we use parameter 2 for the user id, you can change it if you want to delete a different user. And then click send.
To check the data if successfully deleted, you can re-execute the GET request which is localhost:8080/retrieveUsers
.
Conclusion
Congratulation! You have done the RESTful application using spring boot, in the next tutorial we are going to learn how to connect the RESTful application to the database. And the topic includes JDBC configuration and other annotations.
Additionally, RESTful applications are most commonly used as API or web services, and often you will encounter this app on the back-end side of the full-stack applications. Click the link for more information about the full-stack application:
You can use the URL to clone the project source code: https://github.com/LeoBernabe/WebRESTfulService1.0.git
Hairstyles
Its like you learn my mind! You appear to grasp a lot about this, like you wrote the e book in it or something. I believe that you just could do with some to power the message house a bit, but instead of that, that is great blog. A fantastic read. I’ll certainly be back.
supreme clothing
Youre so cool! I dont suppose Ive read something like this before. So good to find somebody with some unique ideas on this subject. realy thank you for beginning this up. this website is one thing that’s wanted on the internet, somebody with a bit of originality. helpful job for bringing one thing new to the web!