Featured blog image
Spring Boot 6 min read

How to Build a Spring Boot REST API with Java

Author

Krishna pariyar

Backend development

REST API ( Representational State Transfer Application Programming Interface) is a set of rules and conventions for building and interacting with web services. It allows different software systems to communicate over the web using standard protocals and methods like HTTP. 

Spring Boot makes it easy to create robust and scalable REST APIs using Java. In this guide, we’ll walk through the steps to build a simple REST API using Spring Boot, covering everything from project setup to deploying the API.

Prerequisites

Before we begin, ensure you have the following installed:

  • Java Development Kit (JDK) 17+

  • Maven or Gradle

  • Spring Boot CLI (optional)

  • An IDE (IntelliJ IDEA, Eclipse, or VS Code)

Step 1: Create a Spring Boot Project

you can setup a Spring Boot project using 

 

  • Then generate code
  • Open your IDE
  • Click File -->  Click Import Project from File System --> Then import folder

Step 2: Connecting Spring Boot to the Database

Modify src/main/resources/application.properties to configure your application. For example, if using H2 Database:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/demoDb
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql: true

Step 3: Creating a Model Class

Create a simple Java class representing a resource in src/main/java/com/example/demo/model/Product.java:

package com.example.demo.model;
import jakarta.persistence.*;

@Entity
public class Product {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;
  private double price;
  //Constructor
  public Product(Long id, String name, double price) {
    super();
    this.id = id;
    this.name = name;
    this.price = price;
  }

  //getter and setter
  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 double getPrice() {
    return price;
  }
  public void setPrice(double price) {
    this.price = price;
  }
}

Step 4: Create a Repository

Create an interface extending JpaRepository to handle database operations in src/main/java/com/example/demo/repository/ProductRepository.java:

package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Product;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}

Step 5: Create a Service Layer

Create a service to manage business logic in src/main/java/com/example/demo/service/ProductService.java:

package com.example.demo.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.model.Product;
import com.example.demo.repository.ProductRepository;

@Service
public class ProductService {
  @Autowired
  private ProductRepository productRepository;
  public List<Product> getAllProducts() {
     return productRepository.findAll();
  }
  public Optional<Product> getProductById(Long id) {
     return productRepository.findById(id);
  }
  public Product saveProduct(Product product) {
     return productRepository.save(product);
  }
  public void deleteProduct(Long id) {
     productRepository.deleteById(id);
  }
}

Step 6: Create a REST Controller

Create a RESTful controller to expose API endpoints in src/main/java/com/example/demo/controller/ProductController.java:

package com.example.demo.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.demo.model.Product;
import com.example.demo.service.ProductService;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;
    
    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }
    @GetMapping("/{id}")
    public Optional<Product> getProductById(@PathVariable Long id) {
        return productService.getProductById(id);
    }
    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productService.saveProduct(product);
    }
    @DeleteMapping("/{id}")
    public void deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
    }
}

Step 7: Run XAMPP Control Panel

Start MySQL service

Step 8: Run the Application

Run your Spring Boot application 
The API will be available at http://localhost:8080/api/products.

Step 9: Test the API

You can use Postman or cURL to test the API endpoints.

  • Get all products:
    curl -XGET http://localhost:8080/api/products

 

  • Create a product:
    curl -X POST http://localhost:8080/api/products -H "Content-Type: application/json" -d '{"name": "Laptop", "price": 1200.0}'

 

  • Delete a product:
    curl -X DELETE http://localhost:8080/api/products/1

NOTE : You can use lombok for better boilerplates

Comments (1)

Please checkout our latest blogs article you may definately meet your need ✌️

Share Your Thoughts

Your thoughts inspire us.

250/250