Building a RESTful API with Spring Boot: A Quick Start Guide
Building a RESTful API with Spring Boot: A Quick Start Guide
Are you looking to create robust, scalable APIs with minimal hassle? Spring Boot is your go-to framework for building production-ready applications with Java. In this article, I’ll walk you through creating a simple RESTful API using Spring Boot, perfect for developers who want to dive into modern backend development. Let’s get started!
Why Spring Boot?
Spring Boot simplifies the complexities of traditional Spring applications by offering:
What We’ll Build
We’ll create a basic REST API for managing a list of books. It will support CRUD operations (Create, Read, Update, Delete) and use an in-memory database for simplicity.
Step 1: Set Up Your Project
Step 2: Define the Entity
Create a Book entity to represent the data model.
java
package com.example.bookapi.model;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Book {
@Id
private Long id;
private String title;
private String author;
private double price;
// Default constructor
public Book() {}
// Parameterized constructor
public Book(Long id, String title quasi, String author, double price) {
this.id = id;
this.title = title;
this.author = author;
this.price = price;
}
// Getters and setters
public Long getId() { return id; }
public void setId(Long 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 double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
}
Step 3: Create the Repository
Spring Data JPA makes database operations a breeze. Define a repository interface for the Book entity.
java
package com.example.bookapi.repository;
import com.example.bookapi.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}
Step 4: Build the Controller
Create a REST controller to handle HTTP requests.
java
package com.example.bookapi.controller;
import com.example.bookapi.model.Book;
import com.example.bookapi.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/books")
public class BookController {
@Autowired
private BookRepository bookRepository;
// Get all books
@GetMapping
public List<Book> getAllBooks() {
return bookRepository.findAll();
}
// Get a book by ID
@GetMapping("/{id}")
public ResponseEntity<Book> getBookById(@PathVariable Long id) {
Optional<Book> book = bookRepository.findById(id);
return book.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
// Create a book
@PostMapping
public Book createBook(@RequestBody Book book) {
return bookRepository.save(book);
}
// Update a book
@PutMapping("/{id}")
public ResponseEntity<Book> updateBook(@PathVariable Long id, @RequestBody Book bookDetails) {
Optional<Book> book = bookRepository.findById(id);
if (book.isPresent()) {
Book updatedBook = book.get();
updatedBook.setTitle(bookDetails.getTitle());
updatedBook.setAuthor(bookDetails.getAuthor());
updatedBook.setPrice(bookDetails.getPrice());
bookRepository.save(updatedBook);
return ResponseEntity.ok(updatedBook);
}
return ResponseEntity.notFound().build();
}
// Delete a book
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteBook(@PathVariable Long id) {
if (bookRepository.existsById(id)) {
bookRepository.deleteById(id);
return ResponseEntity.ok().build();
}
return ResponseEntity.notFound().build();
}
}
Step 5: Configure Application Properties
Add the following to src/main/resources/application.properties to configure the H2 in-memory database:
properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
The H2 console can be accessed at http://localhost:8080/h2-console for debugging.
Step 6: Run and Test the Application
Step 7: Enhance Your Application
To make your API production-ready, consider adding:
#SpringBoot #Java #RESTAPI #BackendDevelopment #Tech
Thank you
Ekanadhreddy