Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
Open In App
Next Article:
Easiest Way to Create REST API using Spring Boot
Next article icon

Easiest Way to Create REST API using Spring Boot

Last Updated : 13 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Spring Boot is a powerful framework that makes it easy to create RESTful APIs. Creating a REST API using Spring Boot is one of the fastest and simplest ways to develop scalable and production-ready web services. Spring Boot simplifies REST API development by providing built-in features such as automatic configurations, embedded servers, and minimal boilerplate code. In this article, we will learn the easiest way to create a RESTful API with Spring Boot, covering essential aspects such as dependencies, controllers, services, and database integration.

Step-by-Step Implementation to Create REST API using Spring Boot

Below are the steps to implement REST API in Spring Boot with MySQL and JPA.

Step 1: Setup Development Environment

Before we begin, we need to set up our development environment. We will need to install the following software:

  • Java Development Kit (JDK)
  • Intellij (or any other preferred IDE like Eclipse)
  • MySQL Server

Step 2: Create a Spring Boot Project

The first step is to create a new Spring Boot project using the Spring Initializr. Open any web browser and go to Spring Initializr

file

Set the following options:

  • Project: Maven Project/Gradle according to your need
  • Language: Java
  • Spring Boot: 3.x.x (or the latest version)
  • Group: com.example
  • Artifact: spring boot API/any desired info of your own choice
  • Packaging: Jar
  • Java: 17 or later

Click on the “Add Dependencies” button and add the following dependencies:

  • Spring Web
  • Spring Data JPA
  • MySQL Driver

Select these dependencies and click on the Generate button. Extract the downloaded project ZIP file to your preferred location.

Step 3: Add Dependencies

To create a REST API with Spring Boot, include the following dependencies in pom.xml:

<dependencies>

<!-- Spring Boot Web Starter for REST APIs -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>


<!-- Spring Boot Starter Data JPA for Database Access -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>


<!-- H2 Database (For Testing) or MySQL (For Production) -->

<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>runtime</scope>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>

</dependency>

</dependencies>

Step 4: Configure Database in application.properties

For MySQL configuration, add the following to src/main/resources/application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring.datasource.username=root

spring.datasource.password=yourpassword

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


spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect

spring.jpa.hibernate.ddl-auto=update

Step 5: Create Entity Class

Next, we need to create an entity class to represent our data model. In this example, we will create a “Product” entity class.

  • Right-click on the “com.example” package and create a package called entity inside it.
  • Enter “Product” as the class name in the “entity” package and click on the “Finish” button.
  • In the “Product” class, add the following code:
Java
package com.example.entity; import javax.persistence.*;  @Entity @Table(name = "product") public class Product {      @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     private Long id;      @Column(nullable = false)     private String name;      @Column(nullable = false)     private double price;      @Column(nullable = false)     private int quantity;      // Constructors, getters and setters, and other methods...      // Getters     public Long getId() {         return id;     }      public String getName() {         return name;     }      public double getPrice() {         return price;     }      public int getQuantity() {         return quantity;     }      // Setters     public void setId(Long id) {         this.id = id;     }      public void setName(String name) {         this.name = name;     }      public void setPrice(double price) {         this.price = price;     }      public void setQuantity(int quantity) {         this.quantity = quantity;     } } 

The @Entity annotation specifies that this class is an entity and should be mapped to a database table. The @Table annotation specifies the name of the database table that will store instances of this entity. The @Id annotation specifies the primary key of the entity, while the @GeneratedValue annotation specifies that the primary key should be generated automatically.

Step 6: Create Repository Interface

Now, we need to create a repository interface to handle database operations for the “Product” entity. In the “ProductRepository” interface, add the following code:

Java
package com.example.springbootapi.repository;  import com.example.springbootapi.entity.Product; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;  /**  * Repository interface for Product entity.  */ @Repository public interface ProductRepository extends JpaRepository<Product, Long> { } 

The @Repository annotation specifies that this interface is a repository, and Spring will create an instance of it automatically. The JpaRepository interface provides a set of methods for performing CRUD (Create, Read, Update, Delete) operations on the “Product” entity.

Step 7: Create a Service Class

Next, we need to create a service class to handle the business logic for our REST API. In the “ProductService” class, add the following code:

Java
package com.example.springbootapi.service;  import com.example.springbootapi.entity.Product; import com.example.springbootapi.repository.ProductRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;  import java.util.List; import java.util.Optional;  /**  * Service class for managing Product entities.  */ @Service public class ProductService {      private final ProductRepository productRepository;      @Autowired     public ProductService(ProductRepository productRepository) {         this.productRepository = productRepository;     }      /**      * Save a product.      *      * @param product the entity to save      * @return the persisted entity      */     public Product saveProduct(Product product) {         return productRepository.save(product);     }      /**      * Get all the products.      *      * @return the list of entities      */     public List<Product> getAllProducts() {         return productRepository.findAll();     }      /**      * Get one product by ID.      *      * @param id the ID of the entity      * @return the entity      */     public Optional<Product> getProductById(Long id) {         return productRepository.findById(id);     }      /**      * Update a product.      *      * @param id the ID of the entity      * @param updatedProduct the updated entity      * @return the updated entity      */     public Product updateProduct(Long id, Product updatedProduct) {         Optional<Product> existingProduct = productRepository.findById(id);         if (existingProduct.isPresent()) {             Product product = existingProduct.get();             product.setName(updatedProduct.getName());             product.setPrice(updatedProduct.getPrice());             product.setQuantity(updatedProduct.getQuantity());             return productRepository.save(product);         } else {             throw new RuntimeException("Product not found");         }     }      /**      * Delete the product by ID.      *      * @param id the ID of the entity      */     public void deleteProduct(Long id) {         productRepository.deleteById(id);     } } 

For saving a product in the database we will use the following code:

// Save Product
@PostMapping
public ResponseEntity<Product> saveProduct(@RequestBody Product product) {
Product newProduct = productRepository.save(product);
return ResponseEntity.ok(newProduct);
}

For getting all products from the database we will use the following code:

// Get all products
@GetMapping
public ResponseEntity<List<Product>> fetchAllProducts() {
return ResponseEntity.ok(productRepository.findAll());
}

For getting a single product from the database we will use the following code:

// Get a product by ID
@GetMapping("/{id}")
public ResponseEntity<Product> fetchProductById(@PathVariable Long id) {
return productRepository.findById(id)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}

For updating a single product from the database, we will use the following code:

// Update a product
@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product updatedProduct) {
Product existingProduct = productRepository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("Product with ID " + id + " not found"));

existingProduct.setName(updatedProduct.getName());
existingProduct.setPrice(updatedProduct.getPrice());
existingProduct.setQuantity(updatedProduct.getQuantity());

return ResponseEntity.ok(productRepository.save(existingProduct));
}

For deleting a single product from the database, we will use the following code:

// Delete a product
@DeleteMapping("/{id}")
public ResponseEntity<String> deleteProduct(@PathVariable Long id) {
if (!productRepository.existsById(id)) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Product not found");
}

productRepository.deleteById(id);
return ResponseEntity.ok("Product Deleted Successfully");
}

Step 8: Create Controller Class

Next, we need to create a controller class to handle HTTP requests for our REST API. In the “ProductController” class, add the following code:

Java
package com.example.springbootapi.controller;  import com.example.springbootapi.entity.Product; import com.example.springbootapi.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;  import java.util.List; import java.util.Optional;  @RestController @RequestMapping("/api/v1") public class ProductController {      private final ProductService productService;      @Autowired     public ProductController(ProductService productService) {         this.productService = productService;     }      /**      * Create a new product.      *      * @param product the product to create      * @return the ResponseEntity with status 200 (OK) and with body of the new product      */     @PostMapping("/product")     public ResponseEntity<Product> saveProduct(@RequestBody Product product) {         Product newProduct = productService.saveProduct(product);         return ResponseEntity.ok(newProduct);     }      /**      * Get all products.      *      * @return the ResponseEntity with status 200 (OK) and with body of the list of products      */     @GetMapping("/products")     public List<Product> getAllProducts() {         return productService.getAllProducts();     }      /**      * Get a product by ID.      *      * @param id the ID of the product to get      * @return the ResponseEntity with status 200 (OK) and with body of the product, or with status 404 (Not Found) if the product does not exist      */     @GetMapping("/products/{id}")     public ResponseEntity<Product> getProductById(@PathVariable Long id) {         Optional<Product> product = productService.getProductById(id);         return product.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());     }      /**      * Update a product by ID.      *      * @param id the ID of the product to update      * @param product the updated product      * @return the ResponseEntity with status 200 (OK) and with body of the updated product, or with status 404 (Not Found) if the product does not exist      */     @PutMapping("/products/{id}")     public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product product) {         Product updatedProduct = productService.updateProduct(id, product);         return ResponseEntity.ok(updatedProduct);     }      /**      * Delete a product by ID.      *      * @param id the ID of the product to delete      * @return the ResponseEntity with status 200 (OK) and with body of the message "Product deleted successfully"      */     @DeleteMapping("/products/{id}")     public ResponseEntity<String> deleteProduct(@PathVariable Long id) {         productService.deleteProduct(id);         return ResponseEntity.ok("Product deleted successfully");     } } 

The @RestController annotation specifies that this class is a controller for RESTful API requests. The @RequestMapping annotation specifies the base URL for all requests handled by this controller.

Next, we need to add methods to handle HTTP requests. In this example, we will add methods to handle GET, POST, PUT, and DELETE requests.

For Post Request, we will be using the following code:

// Create a new Product @PostMapping("/product") public ResponseEntity<Product> saveProduct(@RequestBody Product product) { Product newProduct = productService.saveProduct(product); return ResponseEntity.ok(newProduct); }

The @PostMapping annotation is used to indicate that this class will handle HTTP Post requests and return the response as JSON. It is used to map the /api/v1/products path to this class. @RequestBody is an annotation in Spring Framework used to bind the HTTP request body to a parameter in a controller method. When a client sends an HTTP POST or PUT request, it may include data in the request body. This data is typically in JSON or XML format and contains information about the resource being created or updated.

For Get Request all the products, we will be using the following code:

// Get all Products @GetMapping("/products") public List<Product> getAllProducts() { return productService.getAllProducts(); }

The @GetMapping annotation is used to indicate that this class will handle HTTP Get requests and return the response as JSON. It is used to map the /api/v1/products path to this class. Here the getAllProducts() method fetches all the products and has a path/products.

For Get Request of a single product, we will be using the following code:

// Get a single product @GetMapping("/products/{id}") public ResponseEntity<Product> getProductById(@PathVariable Long id) { Optional<Product> product = productService.getProductById(id); return product.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); }

The @PathVariable annotation is used to extract data from the URL path of an HTTP request. It is used to capture dynamic segments of a URL and map them to a method parameter in a Spring Boot controller. getProductById() method is used to get a product by id and has a path /products/{id}.

For Update Requests, we will be using the following code:

// Update Product @PutMapping("/products/{id}") public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product product) { Product updatedProduct = productService.updateProduct(id, product); return ResponseEntity.ok(updatedProduct); }

In this example, we’ve added a @PutMapping annotation for the updateProduct() method. The @PutMapping annotation is used to map HTTP PUT requests to the /product/{id} endpoint, where {id} is a path variable for the product ID. The @RequestBody annotation is used to bind the request body to the product parameter in the method. When a PUT request is made to /api/v1/product/{id}, the updateProduct() method will be executed with the id parameter set to the product ID from the URL path and the product.

For Delete Requests, we will be using the following code:

// Delete a Product @DeleteMapping("/products/{id}") public ResponseEntity<String> deleteProduct(@PathVariable Long id) { productService.deleteProduct(id); return ResponseEntity.ok("Product deleted successfully"); }

Now, we are completed with the programming side and just remain with the database and then test the endpoints and then we are done.

Now, after this, we will test our API endpoints in postman. The default port for Spring Boot is 8080. You can change the port by using the command inside the application.properties file:

server.port=any port of your choice

In this case, the port is 8080. For our Post Request, the endpoint will be like “http://localhost:8080/api/v1/product” and the output is:

Update The Products


For our Get Request, the endpoint will be like “http://localhost:8080/api/v1/products” and the output is:

Fetch the Products


For our Get by Id Request, the endpoint will be like “http://localhost:8080/api/v1/products/{id}” and the output is:

Fetch a single Product by ID


For our Update Request, the endpoint will be like “http://localhost:8080/api/v1/products/{id}” and the output is:

Update a single product by Id



And finally, for our Delete Request, the endpoint will be like “http://localhost:8080/api/v1/products/{id}" and the output is:

We made our Rest API in Spring Boot.


Next Article
Easiest Way to Create REST API using Spring Boot
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Advance Java
  • Java-Spring
  • Java-Spring-Boot

Similar Reads

    Spring Boot Tutorial
    Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
    10 min read
    Introduction to Spring Boot
    Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC, a commonly used module for building robust web applications. The major drawback of traditional Spring projects is that configuration can be time-consuming and overwhelming for new developers.
    5 min read
    Best Way to Master Spring Boot – A Complete Roadmap
    In the corporate world, they say "Java is immortal!". But Why? Java remains one of the major platforms for developing enterprise applications. Enterprise Applications are used by large companies to make money. Those applications have high-reliability requirements and an enormous codebase. According
    14 min read
    How to Create a Spring Boot Project?
    Spring Boot is built on top of the spring and contains all the features of spring. It is one of the most popular frameworks for building Java-based web applications and microservices. It is a favorite among developers due to its rapid, production-ready environment, which allows developers to focus o
    6 min read
    Spring Boot - Annotations
    Spring Boot Annotations are a form of metadata that provides data about a spring application. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the
    7 min read
    Spring Boot - Architecture
    Spring Boot is built on top of the core Spring framework. It simplifies and automates Spring-based application development by reducing the need for manual configuration. Spring Boot follows a layered architecture, where each layer interacts with other layers in a hierarchical order. The official Spr
    3 min read
    Spring Boot Actuator
    Developing and managing an application are the two most important aspects of the application’s life cycle. It is very important to know what is going on beneath the application. Also, when we push the application into production, managing it gradually becomes critically important. Therefore, it is a
    5 min read
    Spring Boot - Introduction to RESTful Web Services
    RESTful Web Services REST stands for REpresentational State Transfer. It was developed by Roy Thomas Fielding, one of the principal authors of the web protocol HTTP. Consequently, REST was an architectural approach designed to make the optimum use of the HTTP protocol. It uses the concepts and verbs
    5 min read
    How to create a basic application in Java Spring Boot
    Spring Boot is the most popular Java framework that is used for developing RESTful web applications. In this article, we will see how to create a basic Spring Boot application.Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also p
    3 min read
    How to Create a REST API using Java Spring Boot?
    Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences