Spring Boot – REST Example

09 Dec, 2021
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. 
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"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">    <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
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();}
package com.example.demo.service;import java.util.HashSet;import org.springframework.stereotype.Service;import com.example.demo.modal.Book;  @Servicepublic 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
To save the data
http://localhost:8080/findbyid/2Find Book by id
Find Book by id
http://localhost:8080/findallFind all books
Find all books
http://localhost:8080/deleteDelete all books
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;  @RestControllerpublic 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;  @SpringBootApplicationpublic class ExApplication {      public static void main(String[] args) {        SpringApplication.run(ExApplication.class, args);    }  }
Testing APIs in Postman
Java-Spring-Boot
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java