Creating a simple REST API with spring boot
1. Initializing the project
There are several ways to initialize a spring boot project. We are going to initialize it by visiting the start.spring.io. Now select the options according to your preferences and then fill in the project metadata fields. We are going to leave it as it is. Now click on the "ADD DEPENDENCIES" tab and select the "SPRING WEB" module, we are not going to select any other dependency as we like to keep it simple.
Now hit the "GENERATE" button to download your project, after that extract it to a directory of your choosing.
That's it, this is all you have to do to get ready for the production REST spring boot project. You can run it by opening the project in IntelliJ or any other IDE you like and running the project.
We still have some work to do because this project doesn't do anything we have to add some code to create some REST endpoint that we can access.
2. API we will be building
We are going to build a REST API which deals with the users' data. The user will have minimal information that every user has irrespective of their designation or organization. Our application will be capable of performing the following tasks:
- Get the list of all users along with their information.
- Find a specific user by his/her id and return the information.
- Update the user
- Delete a user
3. Creating the model class
Now that we know what kind of data we will be dealing with, it's time to create a model class for the users. Under src/main/java/com/example/demo
(folder name after the java folder could be different in your case, based on project metadata you entered during the initialization phase) create a java file and name it Users.java
.
In this java file add the following code which represents a user for our application.
package com.example.demo;
public class User {
private int id;
private String name;
private int age;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
The user has four private fields that represent the information of a user in the real world. The fields are "name", "age", "email", and "id".
Then create the "Getter" & "Setter" for these fields so that they can be accessed by the other java classes.
4. Creating service class
Now that we have a model class to work with next we will create a service class where we will implement the business logic for dealing with the user.
In the same directory create a new java file and name it UserService.java
. This is where all the code for processing the user data will be written.
package com.example.demo;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserService {
List<User> users = new ArrayList<>();
public User findById(int id) {
User user = new User();
for(User u : users){
if(u.getId() == id){
user = u;
}
}
return user;
}
public List<User> findAll() {
return users;
}
public User add(User user) {
users.add(user);
return user;
}
public void delete(int id) {
users.removeIf(user -> user.getId() == id);
}
public void update(User updatedUser) {
for(int i = 0; i<users.size(); i++) {
if (users.get(i).getId() == updatedUser.getId()) {
users.set(i, updatedUser);
return;
}
}
}
}
The @Service
tells the spring boot to use this class at the service layer.
List<User> users = new ArrayList<>();
creates a list of users in which we can store the users and retrieve them. We did this because as of now we are not using any database in our spring boot app for simplicity's sake.
And we have the following different methods:
findById()
returns a user by their id.findAll()
returns a list of all the available users.add()
adds the given user to the list.delete()
removes a user from a list by id.update()
updates the info of the given user.
5. Adding the controller
Now we will add a controller to our app by creating a java file in the same directory and name it UserController.java
. This java file contains the code to handle the requests of the client and control the flow of the application. All the requests are intercepted by the controller class.
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUser(@PathVariable int id){
return userService.findById(id);
}
@GetMapping("/allUsers")
public List<User> getUsers(){
return userService.findAll();
}
@PostMapping("/save")
public User addUser(@RequestBody User user){
return userService.add(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable int id){
userService.delete(id);
}
@PutMapping("/update")
public void updateUser(@RequestBody User updatedUser){
userService.update(updatedUser);
}
}
The @RestController
tells the spring boot to designate this class as a RestController so that it performs the serialization of objects automatically.
@RequestMapping("/user")
is used to make sure that this controller only intercepts the requests from the URL which have /user
after the base URL in it, in our case all the requests from localhost:8080/user
will be handled by this controller.
@Autowired
is used to inject UserService in our controller.
@GetMapping
tells the method below it to intercept the GET requests with the URL mentioned in the parenthesis after the annotation.
@PostMapping
is used to handle the POST requests with the mentioned URL.
@PutMapping
is used to handle the PUT requests with the corresponding URL.
@DeleteMapping
is used to handle DELETE requests.
@PathVariable
is used to extract the variables from the request URL and map it to the mentioned datatype. For example, @PathVariable int id
will extract the id from the URL and convert it to the int
before storing it to the id
variable.
@RequestBody
is used to extract the data from the request body and map it to the mentioned datatype. @RequestBody User user
will extract the data from the request body and convert it to the type User
and will assign it to the variable user
.
That's it, now we have a working REST API to handle the user data. Now you can test the application using Postman or any other API client.
Note: We have to add some users to the list every time we run this app before performing any other operations because we did not use any database and the list will be empty in the beginning.
6. Testing the app
Now it is time to test our app
6.1. Adding a user
To add users to the list make a POST request to the localhost:8080/user/save
with the following body
{
"id": 1,
"name": "user",
"age": 43,
"email": "user@gmail.com"
}
this will add a user to the list. Now add some more users to the list.
6.2. Getting all the users
To get a list of all the users make a GET request to the localhost:8080/user/allUsers
This should give the following result
[
{
"id": 2,
"name": "user2",
"age": 54,
"email": "user2@gmail.com"
},
{
"id": 1,
"name": "user",
"age": 43,
"email": "user@gmail.com"
}
]
6.3. Updating a user
Now let''s update a user with the id=1. Make an UPDATE request to the localhost:8080/user/update
with the following request body:
{
"id": 1,
"name": "Updateduser",
"age": 43,
"email": "Updateduser@gmail.com"
}
6.4. Get a single user by id
To get the updated user by id make a GET request to the localhost:8080/user/1
{
"id": 1,
"name": "Updateduser",
"age": 43,
"email": "Updateduser@gmail.com"
}
6.5. Deleting a user by id
To delete a user with id=2 make a DELETE request to the localhost:8080/user/2
Now make a GET request to check if the user is deleted or not to the localhost:8080/user/allUsers
[
{
"id": 1,
"name": "Updateduser",
"age": 43,
"email": "Updateduser@gmail.com"
}
]
7. Conclusion
In this tutorial, we saw how easy and straightforward it is to create a REST API using spring boot.