Rest API in Java
RESTful APIs have become the backbone of web services, connecting different applications and allowing data exchange. Java, being a versatile language, provides excellent frameworks to build REST APIs. Among them, Spring Boot stands out due to its ease of use, scalability, and integration capabilities. In this blog, I have guide you through the process of building a REST API using Spring Boot. Learn how to create and manage Rest API in Java. Master the principles of RESTful services and enhance your programming skills for modern web applications.
What is REST?
REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on a stateless, client-server, cacheable communications protocol — typically HTTP. REST APIs allow developers to interact with resources, which are typically represented by URIs.
Setting Up Your Java Project
Before we dive into the code, make sure you have the following:
- JDK 17 or above.
- Spring Boot (we’ll use Spring Initializr to set up the project).
- An IDE like IntelliJ IDEA, Eclipse, or Visual Studio Code.
Step 1: Create a Spring Boot Project
- Navigate to Spring Initializr.
- Select the following:
- Project: Maven
- Language: Java
- Spring Boot Version: 3.0.0 (or latest)
- Dependencies: Spring Web, Spring Boot DevTools
- Click Generate, unzip the downloaded file, and import it into your IDE.
Step 2: Define Your Data Model
- Define model class book which will have properties like id, title, author, and isbn.
package com.example.library.model; public class Book { private Long id; private String title; private String author; private String isbn; // Constructors, Getters, Setters } |
Step 3: Create a Service Layer
The service layer handles the business logic. In a real-world application, it might interact with a database. For simplicity, we’ll use an in-memory list to store our books.
package com.example.library.service; import com.example.library.model.Book; import java.util.ArrayList; import java.util.List; @Service public class BookService { private List<Book> books = new ArrayList<>(); public List<Book> getAllBooks() { return books; } public Book getBookById(Long id) { return books.stream() .filter(book -> book.getId().equals(id)) .findFirst() .orElse(null); } public Book addBook(Book book) { books.add(book); return book; } public void deleteBook(Long id) { books.removeIf(book -> book.getId().equals(id)); } } |
Step 4: Build the REST Controller
The controller is where we define the API endpoints. Using the Spring Web dependency, Spring Boot allows you to map these to HTTP methods like GET, POST, PUT, and DELETE.
package com.example.library.controller; import com.example.library.model.Book; import com.example.library.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(“/api/books”) public class BookController { @Autowired private BookService bookService; @GetMapping public List<Book> getAllBooks() { return bookService.getAllBooks(); } @GetMapping(“/{id}”) public Book getBookById(@PathVariable Long id) { return bookService.getBookById(id); } @PostMapping public Book addBook(@RequestBody Book book) { return bookService.addBook(book); } @DeleteMapping(“/{id}”) public void deleteBook(@PathVariable Long id) { bookService.deleteBook(id);
} } |
Step 5: Test Your API
To test API follow the endpoints as given below
Spring Boot has a built-in Tomcat server, so you can test your API as soon as you run the application. To start it, run the main method in your project’s Application class.
- GET request to /api/books will return all books.
- GET request to /api/books/{id} will return a book with a specific id.
- POST request to /api/books will add a new book.
- DELETE request to /api/books/{id} will delete a book with the given id.
Step 6: We can use the Postman app or cURL
To add Book to the database open the Postman app and add an object in the form of JSON
{
“title”: ”Fundamental of JAVA”,
“author”: ”VK”,
“isbn”:”978-93-89024-06-7”
}
Set url to http://localhost:8080/api/books and hit post request. It will add the book to ArrayList
Conclusion
I have created a simple library service with endpoints to create, read, and delete books. This foundational knowledge can be expanded to include features like database connectivity using JPA, security, and validation.
Note: Do watch our latest video: Click Here
Author:-
Shital Chauhan
Call the Trainer and Book your free demo class for Java now!!!
© Copyright 2020 | SevenMentor Pvt Ltd.