Build a Simple REST API with Java 21 and Spring Boot

πŸš€ Introduction

Spring Boot makes it easy to create production-ready REST APIs with minimal setup. In this guide, we’ll walk you through building a simple REST API with Java 21 and Spring Boot using:

  • Java 21 (LTS)
  • Spring Boot 3+
  • Maven
  • IntelliJ IDEA or any IDE of your choice

Our API will manage a list of books with basic CRUD operations.

πŸ“ Project Structure

Simple REST API with Java 21 and Spring Boot

πŸ—οΈ Step-by-Step Implementation

1. Create the Spring Boot Project

Use Spring Initializr with the following:

  • Project: Maven
  • Language: Java
  • Spring Boot: 3.2+
  • Dependencies: Spring Web, Spring Boot DevTools

2. pom.xml

3. Main Class – BookApiApplication.java

4. Model – Book.java

We’re using Java 21’s record class to keep the model concise and immutable.

5. Service – BookService.java

6. Controller – BookController.java

7. application.properties

πŸ§ͺ Test Your API

Use Postman or curl to interact with the following endpoints:

  • GET /api/books β€” List all books
  • GET /api/books/{id} β€” Get a book by ID
  • POST /api/books β€” Create a new book
  • PUT /api/books/{id} β€” Update book
  • DELETE /api/books/{id} β€” Delete book

βœ… Summary

You’ve just built a simple yet functional REST API with Java 21 and Spring Boot. We used record, REST annotations, and an in-memory service to manage book data.

You can download the complete source code here