Spring Boot has completely transformed Java backend development, making it incredibly easy to build production-ready applications. In this guide, we'll show you how to create a simple RESTful API using Spring Boot. Perfect for beginners, this tutorial will give you hands-on experience with Spring Boot and REST APIs.

What You'll Learn

  • Setting up a Spring Boot project quickly.
  • Creating REST endpoints for your API.
  • Handling HTTP requests and responses like a pro.
  • Using an in-memory database (H2) with Spring Data JPA.
  • Performing basic CRUD operations (Create, Read, Update, Delete).

What You'll Need

  • Java 11 or higher installed on your machine.
  • Basic understanding of Java and REST APIs.
  • An IDE like IntelliJ IDEA or Eclipse.
  • Maven or Gradle for dependency management.

Step 1: Kickstart Your Spring Boot Project

The quickest way to get started is with Spring Initializr. Here’s what you need to do:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Choose the latest stable version (e.g., 3.0.x)
  • Dependencies:
    • Spring Web
    • Spring Data JPA
    • H2 Database

Generate the project, unzip it, and open it in your favorite IDE. You’ll have a basic Spring Boot project ready to go!


Step 2: Define Your Data Model

Let’s create a simple Book entity with attributes: id, title, author, and isbn.

package com.example.demo.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String author;
    private String isbn;

    // Constructors
    public Book() {}

    public Book(String title, String author, String isbn) {
        this.title = title;
        this.author = author;
        this.isbn = isbn;
    }

    // Getters and Setters
    // ... (omitted for brevity)
}

This class is our data model that represents a book in our API. The @Entity annotation tells Spring that this class represents a table in the database.


Step 3: Create the Repository Interface

Spring Data JPA makes database interactions a breeze. By creating a repository interface, you can easily perform database operations.

package com.example.demo.repository;

import com.example.demo.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository extends JpaRepository {
}

The BookRepository interface extends JpaRepository, providing methods for common database operations like save(), findById(), findAll(), and deleteById().


Step 4: Build the REST Controller

Now, let’s build a controller to handle HTTP requests for our Book entity.

package com.example.demo.controller;

import com.example.demo.model.Book;
import com.example.demo.repository.BookRepository;
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 {

    private final BookRepository bookRepository;

    public BookController(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    // Get all books
    @GetMapping
    public List getAllBooks() {
        return bookRepository.findAll();
    }

    // Get book by id
    @GetMapping("/{id}")
    public ResponseEntity getBookById(@PathVariable Long id) {
        Optional book = bookRepository.findById(id);
        return book.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    // Create a new book
    @PostMapping
    public Book createBook(@RequestBody Book book) {
        return bookRepository.save(book);
    }

    // Update a book
    @PutMapping("/{id}")
    public ResponseEntity updateBook(@PathVariable Long id, @RequestBody Book bookDetails) {
        Optional optionalBook = bookRepository.findById(id);
        if (optionalBook.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        Book book = optionalBook.get();
        book.setTitle(bookDetails.getTitle());
        book.setAuthor(bookDetails.getAuthor());
        book.setIsbn(bookDetails.getIsbn());

        Book updatedBook = bookRepository.save(book);
        return ResponseEntity.ok(updatedBook);
    }

    // Delete a book
    @DeleteMapping("/{id}")
    public ResponseEntity deleteBook(@PathVariable Long id) {
        if (!bookRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        bookRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}

This controller handles the following:

  • GET /api/books: Get all books.
  • GET /api/books/{id}: Get a book by ID.
  • POST /api/books: Create a new book.
  • PUT /api/books/{id}: Update a book.
  • DELETE /api/books/{id}: Delete a book.

Step 5: Configure Application Properties

To enable the H2 console and configure the datasource, add the following to src/main/resources/application.properties:

spring.h2.console.enabled=true
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.jpa.hibernate.ddl-auto=update

These settings configure Spring Boot to use an in-memory H2 database, which is perfect for development and testing.


Step 6: Run and Test Your Application

Run your Spring Boot application by executing the main class (DemoApplication.java).

You can test your API using tools like Postman or curl.

Example Requests:

  • Create a book:
curl -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Spring Boot Guide","author":"John Doe","isbn":"1234567890"}'
  • Get all books:
curl http://localhost:8080/api/books
  • Get a book by ID:
curl http://localhost:8080/api/books/1
  • Update a book:
curl -X PUT http://localhost:8080/api/books/1 \
-H "Content-Type: application/json" \
-d '{"title":"Updated Title","author":"Jane Doe","isbn":"0987654321"}'
  • Delete a book:
curl -X DELETE http://localhost:8080/api/books/1

Conclusion

You did it! You’ve successfully built a RESTful API using Spring Boot with full CRUD capabilities. This is a great foundation that you can extend with more advanced features like validation, exception handling, and security.

Spring Boot’s simplicity and extensive ecosystem make it an excellent choice for backend development. Keep experimenting, and happy coding! 🚀


Next Steps

  • Explore Spring Boot’s validation features.
  • Implement custom exception handling.
  • Add security with Spring Security.
  • Connect to a real database like PostgreSQL or MySQL.

If you found this guide helpful, please share it with your friends.


Posted on May 31, 2025