DEV Community

Cover image for REST API Using Spring Boot - Level 2
Souvik
Souvik

Posted on

REST API Using Spring Boot - Level 2

This is a continuation of REST API Using Spring Boot - Level 1. In this tutorial, we will see how we can use a Java class as our temporary storage to send and receive actual user data to and from our REST API. Let's get started.

Create Custom Data Type (User)

To store the data, we need some class that will store it but before that we need to actually define the data type(class). Considering, every user record having 3 properties: id, name and age, we define the User class as below:

public class User {  
    private long id;  
    private String name;  
    private int age;  

    public User(long id, String name, int age) {  
        this.id = id;  
        this.name = name;  
        this.age = age;  
    }  

    public long getId() {  
        return id;  
    }  

    public void setId(long 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;  
    }  
}
Enter fullscreen mode Exit fullscreen mode

Create Respository

Now that our custom data type(User) is defined, we need define the class that will store the user records. We create the class called UserRepository which will store our user records. This class will store user data and provide all the methods to perform various CRUD operations on the data. Since, there will be multiple user records, we use a List to store the user records and define the various methods for it. The implementation for the UserRepository is:

@Component
public class UserRepository {  

    private List<User> users;  

    public UserRepository() {  
        users = new ArrayList<>();  
        users.add(new User(432, "John Doe", 31));  
        users.add(new User(692, "Maria Beth", 27));  
        users.add(new User(453, "Jeena Stone", 30));  
    }  

    public List<User> getAllUsers() {  
        return users;  
    }  

    public User getUser(Integer userId) {  
        User user = null;  
        for (User currentUser : users) {  
            if (Objects.equals(currentUser.getId(), userId)) {  
                user = currentUser;  
                break;  
            }  
        }  
        return user;  
    }  

    public User createUser(User newUser) {  
        users.add(newUser);  
        return newUser;  
    }  

    public User updateUser(Integer userId, User updatedUser) {  
        User user = getUser(userId);  
        if (user != null) {  
            if (updatedUser.getId() != null) user.setId(updatedUser.getId());  
            if (updatedUser.getName() != null) user.setName(updatedUser.getName());  
            if (updatedUser.getAge() != null) user.setAge(updatedUser.getAge());  
        }  
        return user;  
    }  

    public User deleteUser(Integer userId) {  
        User user = getUser(userId);  
        if (user != null)  
            users.remove(user);  
        return user;  
    }  
}
Enter fullscreen mode Exit fullscreen mode

So, now we have defined the data type(User class), the storage class(UserRepository class) which contains data as well as provide method for CRUD operations on the data.

Define Controller

Now that we have defined the CRUD methods, we can readily access the CRUD method via an object of the UserRepository class from the controller. The easiest way to do so is to autowire an object of the UserRepository class in the controller and access all the CRUD methods. Doing so, our code for the controller file would be:

@RestController  
public class MyController {  

    @Autowired  
    private UserRepository userRepository;  
    @GetMapping("/")  
    public String home() {  
        return "Welcome to REST API tutorial using Spring Boot";  
    }  

    @GetMapping("/users")  
    public List<User> getAllUsers() {  
        return userRepository.getAllUsers();  
    }  

    @GetMapping("/users/{userId}")  
    public User getUser(@PathVariable Integer userId) {  
        return userRepository.getUser(userId);  
    }  

    @PostMapping("/users")  
    public User createUser(@RequestBody User user) {  
        return userRepository.createUser(user);  
    }  

    @PatchMapping("/users/{userId}")  
    public User updateUser(@PathVariable Integer userId, @RequestBody User user) {  
        return userRepository.updateUser(userId, user);  
    }  

    @DeleteMapping("/users/{userId}")  
    public User deleteUser(@PathVariable Integer userId) {  
        return userRepository.deleteUser(userId);  
    }  
}
Enter fullscreen mode Exit fullscreen mode

In the above implementation. we can see that we have used a new annotation @RequestBody. What is the use of it? Whenever we send any data via the request body, we can't access it directly. @RequestBody annotation allows us to access that data. With that, we come to an end of the tutorial for creating REST API using Spring Boot.

So, to summarize, the application, we define our data type User, then we create UserRepository to store and retrieve user records, then we autowire an object of this UserRepository class in our controller and via this object we will be able to access all the CRUD methods. Here is the pictorial representation of the process.

Image description

If you're wondering why we created a separate class to store our data when we could have easily just stored the list in the controller itself. And yes, we could have stored but its a better approach to let a class handle one single functionality. Suppose, in the future, if we wanted to change the implementation of the respository then we have to rewrite the controller. So, you see, it may seem a bit extra to create separate class but its always best to follow a modular approach.

Summary

This brings us to the end of our article. In this article, we have learned how to implement a REST API using Spring Boot. We were able to store data using our repository and learnt various annotations related to REST API.

If you enjoyed reading this article, a ike would be appreciated :)

Top comments (0)