DEV Community

Cover image for REST API's for CRUD Operation Using Spring Boot
Samala Sumanth
Samala Sumanth

Posted on

REST API's for CRUD Operation Using Spring Boot

In this article, Under 10 Steps we shall look at how to create a simple RESTful api with spring boot by taking an example of USER.

Required Pre-requisites ๐Ÿ—ฃ:

  • Java installed on the machine ๐Ÿ‘จโ€๐Ÿ’ป.
  • Postman to test the API's.
  • Willing to learn ๐Ÿ˜‰

Its time to jump into the code ๐Ÿš€

STEP 1: Create a base project from https://start.spring.io/. Give a project name and description. Add the 3 required dependencies: Spring Web, Spring Data JPA and MySQL driver.! Finally click on generate which will download a zip file. Extract and open in your preferred IDE like IntelliJ, eclipse or NetBeans.

In my case the application name is crud

Spring Initialiser

STEP 2: Lets create some boilerplate by creating three folders in crud/src/main/java/com/example/crud/CrudApplication.java which are 1. controller 2. model 3. repository 4. service. Typically your folder structure should look like below.

File directory

STEP 3: Create a Database and a users table with user_id ( primary Key ), first_name and email in your mysql
execut the following code which does the job for you in mysql terminal

CREATE TABLE `user_schema`.`users` (
  `user_id` INT NOT NULL AUTO_INCREMENT,
  `first_name` VARCHAR(45) NULL,
  `email` VARCHAR(45) NULL,
  UNIQUE INDEX `user_id_UNIQUE` (`user_id` ASC),
  PRIMARY KEY (`user_id`));
Enter fullscreen mode Exit fullscreen mode

and add the following code in crud/src/main/resources/application.properties

spring.datasource.url = jdbc:mysql://127.0.0.1:3306/user_schema
#username and password of mysql 
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

Enter fullscreen mode Exit fullscreen mode

STEP 4: Let's do the magic by writing some code in these Folders. Create a file named User.java in model folder and add the following code.

package com.example.crud.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private Long id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="email")
    private String email;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
} 
Enter fullscreen mode Exit fullscreen mode

STEP 5: Now create another file in repository package named UserRepository.java where it's class is extended from JPARepository to enable query execution abilities like create(), update(), get() and delete() methods. finally add the following code

package com.example.crud.repository;


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.crud.model.User;

// @Repository tells the spring boot that it wrapped with User Table with sql execution queries.
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
Enter fullscreen mode Exit fullscreen mode

STEP 6: Now Inside your service folder create a file named UserService.java. In this service layer we typically handle the business logic ๐Ÿค–.

package com.example.crud.service;
import com.example.crud.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.crud.repository.UserRepository;
import java.util.List;

@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    public User createUser(User user){
        return userRepository.save(user);
    }

    public List<User> getUsers(){
        return userRepository.findAll();
    }

    public void deleteUser(Long userId){
        userRepository.deleteById(userId);
    }

    public User updateUser(Long userId, User userDetails){
        User user = userRepository.findById(userId).get();
        user.setFirstName(userDetails.getFirstName());
        user.setEmail(userDetails.getEmail());
        return userRepository.save(user);
    }
}

Enter fullscreen mode Exit fullscreen mode

STEP 7: Now inside the controller folder, create a file named UserController.java. This is the first and foremost layer when a request hits the server. This is right place to do validate the params or authorising the API or adding some middleware validations. But right now we only focus on writing the basic structure of the controller.
Finally add the following code.

package com.example.crud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.crud.model.User;
import com.example.crud.service.UserService;

// spring will understand that the methods in this class will follow rest convention
@RestController
@RequestMapping("/api")
public class UserController {
    // spring will create a bean when we do a autowiring
    @Autowired
    UserService userService;

    // invoking the spring-boot that this is end point /users
    // to create USER
    @RequestMapping(value="/users", method=RequestMethod.POST)
    public User createUser(@RequestBody User usr) {
        return userService.createUser(usr);
    }

    // to get all the list of Users
    @RequestMapping(value="/users", method=RequestMethod.GET)
    public List<User> readUsers() {
        return userService.getUsers();
    }

    // to update the values of USER
    @RequestMapping(value="/users/{userId}", method=RequestMethod.PUT)
    public User readUsers(@PathVariable(value = "userId") Long id, @RequestBody User empDetails) {
        return userService.updateUser(id, empDetails);
    }

    // to delete the record from the DB
    @RequestMapping(value="/users/{userId}", method=RequestMethod.DELETE)
    public void deleteUsers(@PathVariable(value = "userId") Long id) {
        userService.deleteUser(id);
    }

}

Enter fullscreen mode Exit fullscreen mode

Finally your repository directory should look like:

File Directory

Hurray !!!!! Thats it !! ๐Ÿค˜๐Ÿค˜ Now you can start ๐ŸŽ the application on port number 8080 (of course the default port)

Spring Application

Step 8: Test ๐Ÿ‘ป your API using postman

Post Man Create
Post Man get Users
Post Man Update User

Please find the postman collection link here: https://www.getpostman.com/collections/763c722809426a268aac

PS: You can find the github repository here https://github.com/SamalaSumanth0262/Spring-Boot-CRUD . Do follow me on https://github.com/SamalaSumanth0262 ๐Ÿ™‹โ€โ™‚๏ธ or https://twitter.com/sumanth0262 ๐Ÿ™‹โ€โ™‚๏ธ

Hey Peeps, This is my first blog ๐ŸŽฏ on JAVA with spring boot. Please do leave any kind of improvements or suggestions. More than happy to hear๐Ÿ™‡โ€โ™‚๏ธ.. Cheers !!! ๐Ÿป๐Ÿป

Top comments (4)

Collapse
 
kevinrawal profile image
kevinrawal

Nice tutorial ๐Ÿ™Œ

Collapse
 
nikhildevarasetty profile image
Nikhil Devarasetty

Good work man, keep doing the same๐Ÿ’ฏ

Collapse
 
arlemi profile image
Arlemi

Great tutorial. ๐Ÿ‘

Collapse
 
kapishusa profile image
Kapish new

Great work man, kudos to your efforts ๐Ÿ™

If possible can you add some creative use cases of this? Would be awesome ๐Ÿ˜Ž

Thanks once again, continue the great learning ๐Ÿ‘