The Wayback Machine - https://web.archive.org/web/20240930190544/https://www.geeksforgeeks.org/spring-boot-rest-example/
Open In App

Spring Boot – REST Example

Last Updated : 09 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We all know in today’s world, most web app follows the client-server architecture. The app itself is the client or frontend part under the hood it needs to call the server or the backend to get or save the data this communication happens using HTTP protocol the same protocol is the power of the web.  On the server, we expose the bunch of services that are accessible via the HTTP protocol. The client can then directly call the services by sending the HTTP request. 

Now, this is where REST comes into the picture.  Rest stands for Representation State Transfer it is basically a convention to building these HTTP services. So we use a simple HTTP protocol principle to provide support to CREATE, READ, UPDATE & DELETE data. We refer to these operations all together called CRUD operations. In short, It is a set of rules that developers follow when they create their API. One of these rules states that you should be able to get a piece of data (called a resource) when you link to a specific URL. Let’s implement an RSET application and understand the REST approach by creating an example where we simply return the Book data in the form of JSON. 

Rest with Example

Set up the spring project:

So first we will set up the spring project in STS(Spring tool suite) IDE. Whose instructions have been given below

  • Click File -> New -> Project -> Select Spring Starter Project  -> Click Next.
  • A New Dialog box will open where you will provide the project-related information like project name, Java version, Maven version, and so on.
  • After that select required maven dependencies like Spring Web,  Spring Boot DevTools (Provides fast application restarts, LiveReload, and configurations for enhanced development experience.)
  • Click Finish.

Project Structure:

pom.xml:

XML




<?xml version="1.0" encoding="UTF-8"?>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>ex</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>ex</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
          
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
  
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  
</project>


Note: No need to add anything to the application.properties because we didn’t use a database. 

POJO (Plain old java object ) class:

Java




package com.example.demo.modal;
  
public class Book {
  
    private long id;
    private String name;
    private String title;
  
    public Book() {
        super();
    }
    public Book(long id, String name, String title) {
        super();
        this.id = id;
        this.name = name;
        this.title = title;
    }
  
    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 String getTitle() {
        return title;
    }
  
    public void setTitle(String title) {
        this.title = title;
    }
  
}


Service interface and Service implementation class

Here we have created an interface called BookService which contains all the service methods that our application is going to provide to the user. And BookServiceImpl class that implements the BookService interface. 

Java




package com.example.demo.service;
  
import java.util.HashSet;
import com.example.demo.modal.Book;
  
public interface BookService {
     HashSet<Book> findAllBook();
     Book findBookByID(long id);
     void addBook(Book b);
     void deleteAllData();
}


Java




package com.example.demo.service;
import java.util.HashSet;
import org.springframework.stereotype.Service;
import com.example.demo.modal.Book;
  
@Service
public class BookServiceImpl implements BookService {
  
    HashSet<Book> bookList = new HashSet<Book>();
    @Override
    public HashSet<Book> findAllBook() {
        if (bookList.isEmpty())
            return null;
        else
            return bookList;
    }
    @Override
    public Book findBookByID(long id) {
        Book book = bookList.stream().filter(b -> b.getId() == id).findAny().orElse(null);
        return book;
    }
    @Override
    public void addBook(Book b) {
        bookList.add(b);
    }
    @Override
    public void deleteAllData() {
        bookList.clear();
    }
}


Rest Controller: 

Here is the ExController class where we are exposing all the APIs which we have created. 

API’s list

  • http://localhost:8080/
    • To save the data
  • http://localhost:8080/findbyid/2
    • Find Book by id
  • http://localhost:8080/findall
    • Find all books
  • http://localhost:8080/delete
    • Delete all books

Java




package com.example.demo.controller;
  
import java.util.ArrayList;
import java.util.HashSet;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
  
import com.example.demo.modal.Book;
  
import com.example.demo.service.BookServiceImpl;
  
@RestController
public class BookController {
  
    @Autowired
    BookServiceImpl bookServiceImpl;
  
    @PostMapping("/")
    public void addBook(@RequestBody Book book) {
        bookServiceImpl.addBook(book);
    }
  
    @GetMapping("/findall")
    public HashSet<Book> getAllBook() {
        return bookServiceImpl.findAllBook();
    }
  
    @GetMapping("/findbyid/{id}")
    public Book geBookById(@PathVariable long id) {
        return bookServiceImpl.findBookByID(id);
    }
  
    @DeleteMapping("/delete")
    public void deleteBook() {
        bookServiceImpl.deleteAllData();
    }
  
}


ExApplication.java

To run the application.

Java




package com.example.demo;
  
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
  
@SpringBootApplication
public class ExApplication {
  
    public static void main(String[] args) {
        SpringApplication.run(ExApplication.class, args);
    }
  
}


Testing APIs in Postman



Previous Article
Next Article

Similar Reads

Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
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 developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Boot – Handling Background Tasks with Spring Boot
Efficiently handling background tasks with Spring Boot is important for providing a smooth user experience and optimizing resource utilization. Background tasks refer to operations that are performed asynchronously or in the background, allowing the main application to continue processing other requests. In a Spring Boot application, background tas
5 min read
Spring Boot – Using Spring Boot with Apache Camel
Apache Camel and Spring Boot are two powerful frameworks that can be seamlessly integrated to build robust, scalable, and efficient applications. Apache Camel is an open-source integration framework that provides an extensive range of components and connectors, enabling developers to integrate different systems, APIs, and applications. It simplifie
5 min read
Spring Boot – Setting Up a Spring Boot Project with Gradle
Spring Boot is a Java framework designed to simplify the development of stand-alone, production-ready Spring applications with minimal setup and configuration. It simplifies the setup and development of new Spring applications, reducing boilerplate code. In this article, we will guide you through setting up a Spring Boot project using Gradle, a wid
4 min read
Migrate Application From Spring Boot 2 to Spring Boot 3
With the release of Spring Boot 3, significant changes and improvements have been introduced, particularly around Jakarta EE compliance, Java 17 support, and GraalVM native images. If you are using Spring Boot 2 and are considering migrating to Spring Boot 3, this article will walk you through the necessary steps, considerations, and potential pitf
5 min read
Spring Boot - Customizing Spring Boot Starter
Spring Boot Starters are specialized project types designed to encapsulate and distribute common functionality, simplifying the setup of Spring Boot applications. Official starters, like spring-boot-starter-web and spring-boot-starter-data-jpa, bundle dependencies, configurations, and pre-built beans for specific use cases. Creating a custom Spring
6 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 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 to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems
6 min read
JSON using Jackson in REST API Implementation with Spring Boot
Whenever we are implementing a REST API with Spring (Spring Boot), we would have come across the requirement to exclude NULLs in the JSON Response of the API. Also, there might be a requirement to externalize turning ON/OFF this feature: Exclude NULLS in the JSON Response, thereby allowing the consumer of the API to customize as per the need. In th
3 min read
Spring Boot - REST API Documentation using OpenAPI
For any application, API documentation is essential for both users and developers. How to use an API, what will be the request body, and what will the API's response be? API documentation is the answer to all of these questions, springdoc-openapi is a Java library that automates the generation of the API documentation in both JSON/YAML and HTML for
4 min read
Spring Boot - Rest Template
RestTemplate is a powerful synchronous client for handling HTTP communication in Spring Boot applications. It internally uses an HTTP client library i.e. java.net.HttpURLConnection, simplifying the process of making RESTful requests to external services and APIs, including convenience, along with integration, and flexibility for various HTTP commun
7 min read
Spring Boot – REST API Documentation using Swagger
REST stands for Representational State Transfer. REST is an architectural design pattern that defines constraints that are used in web service development. Swagger is a framework in which we can test our REST APIs for different HTTP requests i.e. : GETPOSTPUTDELETEIn this article, we will be discussing using Swagger for documenting APIs in Spring B
4 min read
How to Make REST Calls using FeignClient in Spring Boot?
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. FeignClient also known as Spring Cloud OpenFeign is a Declarative REST Client in Spring Boot Web Application.
13 min read
How to Call REST Services with WebClient in Spring Boot?
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring WebClient is a non-blocking and reactive web client to perform HTTP requests. It is also the replaceme
11 min read
Spring Boot - How to set a Request Timeout for a REST API
In Microservice architecture, there are multiple microservices available for an application. For the application to work properly necessary services need to communicate with each other. There can be communication of messaging type or REST calls. How does REST API Work?In REST Calls the process is synchronous, which means suppose a service SERV1 is
7 min read
Spring Boot: Cannot access REST Controller on localhost (404)
The Spring Boot framework is one of the most famous in web application development, It can provide a lot of features to make development easy like dependency management, Spring Security, Spring Autoconfiguration, and other features provided by the Spring Framework. In this article, we will learn how a 404 error occurs while accessing the REST Contr
4 min read
Spring Boot - Versioning a REST API
API Versioning is a defined process of making or managing changes to an API. These changes can be made transparently without interrupting the clients. When users have permission to decide whether they can conveniently upgrade to the latest version of API and clearly state the changes made is known as a Good API Versioning Strategy. When to Version
3 min read
Best Practices while Making Rest APIs in Spring Boot Application
API, or Application Programming Interface, is a communication gateway between frontend and backend code. A robust API is crucial for ensuring uninterrupted functionality. In this article, we will discuss how to achieve robustness in our REST API within the Spring Boot application. Rules : Use JSON as the Standard Message FormatError HandlingPaginat
7 min read
Easiest Way to Create REST API using Spring Boot
Spring Boot is a powerful framework that makes it easy to create RESTful APIs. In this article, we will go through a step-by-step guide on how to create a RESTful API in Spring Boot with MySQL and JPA. We will start by creating a new Spring Boot project and configuring it for our needs. For developers eager to deepen their knowledge and expertise i
11 min read
How to Generate Spring Boot REST Client with Swagger?
Spring Boot is a powerful framework for building Java applications, particularly RESTful web services. When developing the REST APIs, it can be crucial to provide documentation that is both user-friendly and interactive. Swagger is an open-source that simplifies this by generating the API documentation automatically. In this article, we will create
6 min read
Spring Boot – Building REST APIs with HATEOAS
In this article, we will explore how to build RESTful APIs using the Spring Boot with HATEOAS (Hypermedia as the Engine of Application State). HATEOAS is the key component of the REST application architecture, where each resource not only provides the data but also includes links to other actions that can be performed on the resource. This approach
5 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read
How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that it tries to connect every concept in the language to the real world with the help
3 min read
How to Create and Setup Spring Boot Project in Spring Tool Suite?
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 developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
How to Run Your First Spring Boot Application in Spring Tool Suite?
Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt
3 min read
How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?
For the sample project, below mentioned tools got used Java 8Eclipse IDE for developmentHibernate ORM, Spring framework with Spring Data JPAMySQL database, MySQL Connector Java as JDBC driver.Example Project Using Spring Boot, MySQL, Spring Data JPA, and Maven Project Structure: As this is getting prepared as a maven project, all dependencies are s
4 min read
Java Spring Boot Microservices – Integration of Eureka and Spring Cloud Gateway
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
5 min read
What's New in Spring 6 and Spring Boot 3?
Spring and Spring Boot are two of the most popular Java frameworks used by developers worldwide. The Spring team is continuously working on improving and enhancing the frameworks with each new major release. Spring 6 and Spring Boot 3 are expected to bring in significant new features and changes that will further boost development with these techno
5 min read
Article Tags :
Practice Tags :