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

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

Roadmap to become a fullstack developer

 Becoming a Full Stack Developer means gaining proficiency in both frontend and backend development, as well as understanding the tools and practices that tie them together. Below is a roadmap to guide your journey toward becoming a full-stack developer. This roadmap covers the key areas, from foundational knowledge to advanced topics. Roadmap to Becoming a Full Stack Developer 1. Learn the Basics of Web Development 1.1 HTML (Hypertext Markup Language) Learn the basic structure of web pages. Understand the role of elements like <div>, <span>, <a>, <img>, etc. Learn about semantic HTML (<header>, <footer>, <article>, etc.). 1.2 CSS (Cascading Style Sheets) Learn how to style web pages (colors, fonts, spacing, etc.). Master CSS layout techniques like Flexbox and Grid. Understand the importance of Responsive Design (media queries, mobile-first approach). 1.3 JavaScript (JS) Learn the fundamentals: variables, loops, conditionals, functions. Und...

How to convert Enum Contants into String: Inbuilt methods of Enum in java

 In Java, every enum type inherits several built-in methods from the java.lang.Enum class, which is the base class for all enum types. These built-in methods provide functionality such as getting the name of an enum constant, comparing enum constants, and iterating over all constants. Here are the inbuilt methods provided by the Enum class: 1. values() Description : This method returns an array of all the constants of the enum type, in the order they were declared. Syntax : public static T[] values() Example : enum Day {     MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } public class EnumMethodsExample {     public static void main(String[] args) {         Day[] days = Day.values();  // Get all enum constants                  // Loop through the array and print each day         for (Day day : days) {             System.out....