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 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/ 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` (
  `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/

spring.datasource.url = jdbc:mysql://
#username and password of mysql 
spring.datasource.password=root = 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 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;

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

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String firstName;

    private String email;

    public Long getId() {
        return id;

    public void setId(Long 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) { = email;
Enter fullscreen mode Exit fullscreen mode

STEP 5: Now create another file in repository package named 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.stereotype.Repository;

import com.example.crud.model.User;

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

STEP 6: Now Inside your service folder create a file named 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;

public class UserService {

    UserRepository userRepository;

    public User createUser(User user){

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

    public void deleteUser(Long userId){

    public User updateUser(Long userId, User userDetails){
        User user = userRepository.findById(userId).get();

Enter fullscreen mode Exit fullscreen mode

STEP 7: Now inside the controller folder, create a file named 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
public class UserController {
    // spring will create a bean when we do a autowiring
    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) {


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:

PS: You can find the github repository here . Do follow me on πŸ™‹β€β™‚οΈ or πŸ™‹β€β™‚οΈ

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)

kevinrawal profile image

Nice tutorial πŸ™Œ

arlemi profile image

Great tutorial. πŸ‘

nikhildevarasetty profile image
Nikhil Devarasetty

Good work man, keep doing the sameπŸ’―

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 πŸ‘