Skip to main content

REST Api

Creating a REST API in Java can be achieved using frameworks like Spring Boot, which simplifies development and setup. Below is a detailed guide to building a REST API for managing books using Spring Boot.

restVsSoap

Prerequisites:

    Java Development Kit (JDK): Ensure JDK 11 or higher is installed.

    Maven: Build tool for managing dependencies and building the project.

    Spring Boot: A popular framework for creating RESTful services.

Steps to Create a REST API

1. Setup a Spring Boot Project

You can create a Spring Boot project using:

    Spring Initializr

    Your IDE (e.g., IntelliJ IDEA or Eclipse)

Include the following dependencies:

    Spring Web: For building REST APIs.

    Spring Boot DevTools (Optional): For live reload during development.

Maven Dependency Configuration (pom.xml)

    <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> 

  </dependency> 

</dependencies>

2. Code Example: A Simple REST API

Directory Structure

css:

src/main/java/com/example/bookapi

Book Entity

java

package com.example.bookapi.model; public class Book { private int id; private String title; private String author; // Constructors public Book() {} public Book(int id, String title, String author) { this.id = id; this.title = title; this.author = author; } // Getters 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; } }

BookController

java code:

package com.example.bookapi.controller; import com.example.bookapi.model.Book; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/books") public class BookController { private final List<Book> books = new ArrayList<>(); public BookController() { books.add(new Book(1, "1984", "George Orwell")); books.add(new Book(2, "To Kill a Mockingbird", "Harper Lee")); books.add(new Book(3, "The Great Gatsby", "F. Scott Fitzgerald")); } // Get all books @GetMapping public List<Book> getBooks() { return books; } // Get a book by ID @GetMapping("/{id}") public Book getBook(@PathVariable int id) { return books.stream() .filter(book -> book.getId() == id) .findFirst() .orElseThrow(() -> new RuntimeException("Book not found")); } // Add a new book @PostMapping public Book addBook(@RequestBody Book book) { book.setId(books.size() + 1); books.add(book); return book; } // Update a book @PutMapping("/{id}") public Book updateBook(@PathVariable int id, @RequestBody Book updatedBook) { Book book = books.stream() .filter(b -> b.getId() == id) .findFirst() .orElseThrow(() -> new RuntimeException("Book not found")); book.setTitle(updatedBook.getTitle()); book.setAuthor(updatedBook.getAuthor()); return book; } // Delete a book @DeleteMapping("/{id}") public String deleteBook(@PathVariable int id) { books.removeIf(book -> book.getId() == id); return "Book deleted successfully"; } }

Main Application:
java code:
package com.example.bookapi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BookApiApplication { public static void main(String[] args) { SpringApplication.run(BookApiApplication.class, args); } }
How to Run the Application:
    
1.Build and Run
    Navigate to the project directory.
    Use Maven to run the application:
    bash mvn spring-boot:run
2.Access the API The API will be available at http://localhost:8080/books.

Testing the API

1.Get all books

  • Endpoint: GET /books

  • Example response:
    json
    [ {"id": 1, "title": "1984", "author": "George Orwell"}, {"id": 2, "title": "To Kill a Mockingbird", "author": "Harper Lee"} ]
  • 2.Get a specific book
    • Endpoint: GET /books/1
    • Response:
      json {"id": 1, "title": "1984", "author": "George Orwell"}
    similarly you can perform other api tesing.

    Enhancements

    1. Database Integration: Use a database (e.g., MySQL, PostgreSQL) instead of in-memory storage.
    2. Validation: Add validation for inputs using @Valid.
    3. Error Handling: Add custom exceptions for better error messages.
    4. Authentication: Secure the API using OAuth or JWT.

    Let me know if you'd like help with any specific enhancement

Comments

Popular posts from this blog

equals method of object class in java

  In Java, the equals method is a fundamental method inherited by all classes from the Object class.           Here’s an explanation of the equals method: Purpose: The equals method is used to compare two objects to determine if they are logically equivalent. By default, the implementation in the Object class checks if the two object references point to the same memory location (i.e., if they are the same instance). Signature : public boolean equals(Object obj) Explanation: Method Override: Classes can override the equals method to provide their own definition of object equality based on their specific needs. When overriding, the method should adhere to certain principles to ensure consistency and correctness of equality comparisons. Default Behavior (from Object class): The default implementation in the Object class checks if the two object references ( this and obj ) refer to the exact same object in memory using the == operator: public boo...

What is static keyword in java

 Static variable: If we want to share the value of any field or variable inside all the instances of class then we should declare that variable as static. In above diagram we see that e1 and e2 are two objects of class Employee. they share the static variable companyName.  Static variables are also called as Class Variables because its copy gets shared between all the objects of same class.   Static variable gets space in method area at the time of class loading.   We can access static variables using object reference but it is designed to access using class name and dot operator.   Example:   Employee employee=new Employee(); object creation  System.out.println(“Company name:”+Employee.CompanyName): ok System.out.println(“Company name:”+employee.CompanyName): Ok  staticmethod

What is real use of interface: mostly asked interview question

Actually in real project development interfaces are use to write business logic code . Also Interfaces in java are powerful tools that allow you to define a contract for what a class can do, without specifying how it does it. it means we can give method declaration in interface and what that method does actually that responsibility is given to the class which is going to implement that class. They are used for several real-world purposes like enabling polymorphism , creating loosely coupled systems , and defining common behaviors across different classes . Real-World Use of Interfaces Let's look at some practical scenarios where interfaces are commonly used: 1. Multiple Inheritance (via Interfaces):  Java doesn't support multiple inheritance with classes, but it allows multiple inheritance with interfaces. This allows a class to implement multiple interfaces, enabling it to inherit behaviors from more than one source. 2. Polymorphism: Interfaces allow you to treat different o...