The Rest is abbreviated as Representational state transfer.
The Representational state transfer (Rest API) is a software architectural approach to create the web service.
The Representational state transfer (Rest API) is used to build the backend API to deal with the datas. The Rest is frequently communicate over HTTP protocol and handle datas in JSON or XML format.
In this tutorial, I'll demonstrate to you how to create a Rest API using spring boot in java, and we will perform CRUD operation as well.
Spring boot project setup
For this tutorial, I'll create a spring boot application using the spring tool suite ide. You can use spring initializr to build the spring boot project as well, Or you can refer How to a create Spring boot application using spring initializr.
We will perform CRUD operation in this tutorial, you can look over the below diagram for complete understanding. Let's start building the Rest API using spring boot.
Open your spring tool suite ide, Snap the File option which is located at the upper left corner, Now choose New then Spring Starter Project as shown in the below image.
Now new Spring boot starter project window will pop up, Here you need to specify your project description. In this tutorial, we will be creating a Rest API to handle the books, so we name our application as HandleBooks.
Type: We will be using the maven build tool for our project, So I have chosen Maven. If you are comfortable with Gradle, then go ahead, This both are just a project build tool.
Packaging: As we are creating rest API, use packaging Jar, In maven there are three different types of packaging such as Jar, War, and POM.
Java Version: Choose the java version which you had installed in your machine. I'll use amazon corretto 11 .
Group: The Group in the maven is used for a unique identity of your project. The best practice is to use your domain name in group id, Our Domain is LearnJavaSills.in, So I have used in.learnjavaskills.
Artifact: The Artifact id in the maven is used to declare the project name. In this example we are creating the Rest API to handle the books so, I have named HandleBooks.(alert-passed)
Enough for basic, Now follow the Next button. New Spring Starter Project Dependencies windows will appear.
Spring Boot Version: Here, you can choose the version of spring boot for your project. The best practice is not to use SNAPSHOT versions.
Available: In the Available section, you can search the various Dependencies for your project. To create a Rest API, we need spring-boot-starter-web Dependencies. So, search the web on the Available, you will find Spring Web under the Web node, select it, and now Spring Web is available in the selected section.(alert-success)
Follow the Finish button. In this step, The spring tool suite IDE will download all the required dependencies of spring boot, and then the project setup will complete.
Once the dependencies are download completed, Open the project explorer and expand the HandleBooks, you will notice the following structure.
Explanation of the pom.xml
Now Open the pom.xml file from the project explorer, you will find this similar code
<?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.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>in.learnjavaskills</groupId>
<artifactId>HandleBooks</artifactId>
<version>1.0</version>
<name>HandleBooks</name>
<description>CRUD Operation on books</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-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The pom.xml of Maven is used for the project build. If you notice closely, then you will find there are many XML tags are present, and the explanation is below.
Parent Tag: The parent tag is used in pom.xml to inherit the properties of the spring boot in our project. Press ctrl or cmd + click on Group Id of the parent, then you will find the pom.xml of the spring boot, which we are using in our project.
Followed by the groupId, artifactId, version, name, and description are the tags we already saw at the time of the creating spring boot application.
dependencies: In the Maven, we can add the third party jar or library in our project by using the dependencies tag. Here, we have already added the spring starter web at the time of creating a spring boot rest API project, so we have got here.
There is some Maven repository to use a third-party library in our project, and one of them is MVN Repository. That's it for the basic of pom.xml
How to run spring boot application
To run the Spring boot application, Open HandleBooksApplication from the project explorer. And you will find the below code.
package in.learnjavaskills.handlebooks;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HandleBooksApplication
{
public static void main(String[] args)
{
SpringApplication.run(HandleBooksApplication.class, args);
}
}
The @SpringBootApplication
annotation in the spring boot is to indicate the entry point of the application. If you miss this annotation in your main method class, then the spring boot will not execute the spring properties.
Running spring boot application using IDE
To run this project, Right-click on empty space of the HandleBooksApplication class, Run as spring boot app. check your console you must get this.
Run Spring boot application using the Maven (pom.xml)
Right-click on the empty space in the pom.xml or on the pom.xml from the project explorer. Now click on Maven build.
The following screen will pop up, and in the goal type spring-boot:run
. Now follow the run button.
Spring boot Rest API coding part
Model
Let's create a Model package and a POJO class for the Books. Go back to the project explorer, right-click on the project i.e, HandleBooks, New then Java class.
Provide the necessary details in this Java class window as shown in the below screen and follow the Finish button.
Create the id, title, author, and price fields in the class of the book and generate getters and setters as well.
To generate getter and setter, Right-click on the empty space in the book class, find the source, then Generate Getters and Setters.
We will also generate the toString method as well and the process of generating the toString() method is the same as getter and setter. Just find Generate toString inside the source.
Books class code
package in.learnjavaskills.handlebooks.model;
public class Books
{
// private fileds
private int id;
private String title;
private String author;
private int price;
// getter and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Books [id=" + id + ", title=" + title + ", author=" + author + ", price=" + price + "]";
}
}
Controller
To Handle the incoming request to our Spring boot rest API, Let us create a controller class with the name of BooksController in the in.learnjavaskills.handlebooks.controller package
In this BooksController class, we will write the method for the crud operation. Let's create four methods for handling the crud operation.
BooksController code
package in.learnjavaskills.handlebooks.controller;
import java.util.ArrayList;
import java.util.List;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import in.learnjavaskills.handlebooks.model.Books;
@RestController
public class BooksController
{
private List booksStorage = new ArrayList<>();
@PostMapping(path = "addBook")
public Books addBook(@RequestBody Books book)
{
booksStorage.add(book);
return book;
}
@GetMapping(path = "fetchAllBooks")
public List fetchAllBooks()
{
return booksStorage;
}
@DeleteMapping(path = "deleteBookById/{id}")
public List deleteBookById(@PathVariable int id)
{
/* Imperative style */
// for(Books book : booksStorage)
// {
// if (book.getId() == id)
// booksStorage.remove(book);
// }
/* Declarative Style */
booksStorage.removeIf(book -> book.getId() == id );
return booksStorage;
}
@PutMapping(path = "UpdateBookById/{id}")
public List updateBookById(@PathVariable int id, @RequestBody Books updateBook)
{
/* Imperative style */
// for(Books book : booksStorage)
// {
// if (book.getId() == id)
// {
// booksStorage.remove(book);
// booksStorage.add(updateBook);
// }
// }
/* Declarative Style */
booksStorage.removeIf(book -> book.getId() == id );
booksStorage.add(updateBook);
return booksStorage;
}
}
Now Our Spring boot rest API is ready But before testing this Spring boot Rest API application, let's understand some annotations which we have used in the BooksController class
The@RestController
annotation in the spring boot framework is used to indicate that the class a controller for rest API.
The
@GetMapping
annotation of HTTP in the spring boot framework for creating a REST API is used, when you want to fetch the data over an HTTP protocol.
The
@PostMapping
annotation is used for sending the data from the client-side over an HTTP protocol.
Use
(alert-passed)@PutMapping
annotation when you want to update the data.
Testing the Spring boot rest API using Postman
To test our rest end point, we will use the Postman app.
What is Postman?
Postman is a software development tool for the developer to test the Rest API. You can download Postman for your machine.
The URLs for the rest end points are as follows:
Rest API Endpoint | Description |
---|---|
localhost:8080/fetchAllBooks |
To fetch all the books available in our system |
localhost:8080/addBook |
Insert the new book into our database. |
localhost:8080/deleteBookById/{book id} |
If you would like to remove some books, you can do so by providing the book ID to this API. |
localhost:8080/UpdateBookById/{book id} |
If you want to update some books, you can do it by using the book ID along with this API. |
How to test Rest API
First run you spring boot rest API, then launch the postman application.Now we will add some books using postman.
Use the Add Book Rest API to add some books to our system.
Step 1: If you want to add the book using the rest API listed below, you must first pick the method type as post, as seen in the image below.
localhost:8080/addBook(code-box)
Step 2: Now find the Body tab, which is located in the below of search bar.
Step 3: Now select the raw radio button as shown in the below image.In the end, select JSON (application/json) from the drop-down..
Step 4: Now past the following code
{
"id":101,
"title": "Harry Potter and the Philosopher's Stone",
"author": "J. K. Rowling",
"price": 100
}
Step 5: Now follow the send button. and scroll down to watch the response from the server.
Let's retrieve some books now by using the fetch all books rest api.
To get the entire book, paste the following URL into postman and press the send button.
localhost:8080/fetchAllBooks(code-box)
Let's attempt updating the book using the update rest API.
Use the following update rest API to update books by ID: For this example, we will update book ID 101. Now repeat the technique we used to add the book, and finally click the send button. Scroll down to see the server's response.
localhost:8080/UpdateBookById/101(code-box)
Using the delete Rest API to remove the book.
Utilize the Delete by ID Rest API, as illustrated below. In the example below, we are deleting book ID 101. You can see an example of how to delete a book using the Postman app in the image below.
localhost:8080/deleteBookById/101(code-box)
Source Code
You can download or clone this Rest API project from (getButton) #text=(gitHub source code link) #icon=(download) #color=(#000000)
Conclusion
Now you have learned how to build rest API using the spring boot in java. Now you are confident in building Rest API, so why not try to build a Rest API by yourself to handle the student data.
If you have enjoyed this tutorial, then please subscribe to the LearnJavaSkills.in and share on social media. The subscription link is available at the top of this blog and as well as on the sidebar.
Let's me know your thought in the comment box.
(getButton) #text=(Next: Monitor your rest API using Actuator) #icon=(link) #color=(#2339bd)