Create REST APIs Using Spring Boot: Step-by-Step Guide

Spring Boot is a framework which is used for creating robust and scalable REST APIs. Let’s start the process of creating a REST API using Spring Boot with clear and organized steps. So let’s start

Create Rest APIs using Spring Boot

Create REST APIs using Spring Boot step-by-step

  • Step 1: Set Up your Spring Boot Application

    Use Spring Initializer or an IDE like IntelliJ or Eclipse to create a new Spring Boot project and Add the following dependencies

    • Spring Web: For building web applications and REST APIs.
    • Spring Data JPA: For interacting with the database.
    • MySQL Driver (or your preferred database driver).
  • create spring boot project using Spring Initializer
  • Step 2: Configure the application.properties File

    1. Open the application.properties file and configure your database settings. For example:

    2. Replace your_database_name, your_username, and your_password with your database details.

    
     # Server configuration
     server.port = 8081
                        
     # Database configuration
     spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
     spring.datasource.name=your_database_name
     spring.datasource.username=your_username
     spring.datasource.password=your_password
     spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
                        
     # JPA configuration
      spring.jpa.hibernate.ddl-auto=update
                      

    1. server.port=8081

    • This configures the port on which your Spring Boot application will run.
    • By default, Spring Boot runs on port 8080. Here, it’s changed to 8081. This is helpful when you have multiple applications running on the same machine and need to avoid port conflicts.

    2. spring.application.name= DemoProject

    • This sets the name of your Spring Boot application.
    • It’s useful for identifying your application when running multiple Spring Boot applications or microservices. In your case, the application is named “ProjectName.”

    3. spring.datasource.url= jdbc:mysql://localhost:3306/your_database_name

    • This specifies the JDBC URL of the MySQL database your application will connect to.
    • jdbc:mysql://: The protocol for connecting to MySQL.
    • localhost: The database server is running on the local machine.
    • 3306: The default port for MySQL.
    • your_database_name: The name of the database. (my database name is Demo)

    4. spring.datasource.name= Demo

    • This sets the name of the data source.
    • It’s an identifier for the data source within your application, typically matching the database name.

    5. spring.datasource.username= Admin

    • This sets the username for connecting to the database.
    • The application will use “Admin” to authenticate against the MySQL database.

    6. spring.datasource.password= password

    • This sets the username for connecting to the database.
    • The password corresponding to the “Admin” username. Be cautious when sharing this information as it contains sensitive data.

    7. spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver

    • This specifies the driver class name for MySQL.
    • com.mysql.cj.jdbc.Driver is the driver class for MySQL Connector/J 8.0.

    8. spring.jpa.hibernate.ddl-auto= update

    • This configures the behaviour of Hibernate for schema management.
    • update: Hibernate will automatically update the database schema to match the entity mappings. Other options include create, create-drop, validate, and none.

    Step 3: Create an Entity Class

    Define an entity class to map the database table. For example, Emp

    
    package com.demo.entity;
    
    import jakarta.persistence.Entity;
    import jakarta.persistence.Id;
    
    @Entity
    public class Emp {
    
        @Id
        private String name;
        private int age;
        private int salary;
    
        public Emp() {
        }
    
        public Emp(String name, int age, int salary) {
            this.name = name;
            this.age = age;
            this.salary = salary;
        }
    
        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 int getSalary() {
            return salary;
        }
    
        public void setSalary(int salary) {
            this.salary = salary;
        }
    }
    
    

    Step – 4: Create Repository Interface

    Create Repository Interface for Emp class which communicate with the database or emp table and handle all the operations using JPA methods or custom queries

    
    package com.demo.repo;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    import com.demo.entity.Emp;
    
    @Repository
    public interface EmpRepo extends JpaRepository<Emp, String> {
    
    }
    
    

    Step 5: Create a Service

    Create a service class to define the business logic and interact with the repository. For example:

    
    package com.demo.service;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.demo.entity.Emp;
    import com.demo.repo.EmpRepo;
    
    @Service
    public class EmpService {
    	
        @Autowired
        private EmpRepo empRepo;
    		
        public List<Emp> getEmp() {
            return empRepo.findAll();
        }
    }
    
    

    Step – 6 : Create a controller class to define the REST API endpoint. For example:

    
    package com.demo.controller;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.demo.entity.Emp;
    import com.demo.service.EmpService;
    
    @RestController
    public class EmpController {
    	
        @Autowired
        private EmpService empService;
    	
        @GetMapping("/getEmp")
        public List<Emp> getEmp() {
            return empService.getEmp();
        }
    }
    
    

    Step 7: Run the Application

    1. Start your Spring Boot application.

    2. Spring Boot will automatically create the Emp table in your database (based on the entity class).

    emp table in database

    Insert some sample data into the Emp table manually using a database client (e.g., MySQL Workbench) or a database console:

    INSERT INTO emp (name, age, salary) VALUES (‘David’, 23, 2000);
    
        INSERT INTO employee ( name, age, salary) VALUES (‘John’, 22, 3000);
    
        INSERT INTO employee ( name, age, salary) VALUES (‘Smith, 21, 5000);
    emp table in database with data

    Step – 8 : Test the api using Postman

    this is the last step to test your api using postman you can enter you url and test the api

    1. Open Postman (or any API testing tool).

    2. Send a GET request to the endpoint: http://localhost:8080/getEmp

    API testing using postman

    Project Structure

    Create proper packages and classes for industry standard you can follow following structure

    Spring boot project structure

Youtube Video –

Github Repository –

https://github.com/amangupta7024/React-SpringBoot

Explore our more articals

How to create Rest-APIs using Spring Boot

Spring Boot is a framework which is used for creating robust and scalable REST APIs. Let’s start the process of creating a REST API using Spring Boot with clear and organized steps.

Create REST-APIs using Spring Boot step-by-step guide

Create a REST-API using Spring Boot with clear and organized way. following are the steps for creating rest api in spring boot

Step 1: Set Up your Spring Boot Application
Step 2: Configure the application.properties File
Step 3: Create an Entity Class
Step 4: Create Repository Interface for Emp class
Step 5: Create a Service
Step 6 : Create a controller class to define the REST API endpoint
Step 7: Run the Application
Step – 8 :  Test the api using postman