Skip to main content

Web frameworks · Intermediate · 28 min

Build a REST API with Spring Boot 4 and Java 25

By Padding · Updated 18 Nov 2026
Eclipse Temurin JDK 25.0.5 (eclipse-temurin:25-jdk image) · Spring Boot 4.1.2 · Maven 3.10.1 wrapper

You will generate a Spring Boot 4.1 project on Java 25, build a validated book API backed by Spring Data JPA and an in-memory H2 database, return errors as Problem Details, test it with MockMvc and package it as a runnable JAR.

On this page

Spring Boot is the most common way to write web services in Java. It sits on top of the Spring Framework and picks sensible defaults for you: an embedded Tomcat server, JSON with Jackson, a database connection pool, and configuration that switches itself on when the right library is on the classpath. You write the parts that are specific to your application, and Boot wires them together at start-up.

In this tutorial you build a small book API with Spring Boot 4.1 on Java 25. It stores books with Spring Data JPA in H2, an in-memory database that needs no installation, validates what clients send, and answers errors in the standard Problem Details format (RFC 9457) so clients get the same shape for every failure. You test it without opening a port, then package it as a single JAR that runs anywhere Java 25 does.

If you do not have a JDK yet, install Eclipse Temurin 25 as in Hello World in Java. The project uses the Maven wrapper, so you do not need to install Maven.

Step 1 · Check your Java version

Spring Boot 4 runs on Java 17 or later. This project targets Java 25, the current long-term support release, so the compiler must be 25 or newer:

Bash
java -version

Check it worked

The first line names version 25, something like openjdk version "25.0.5" 2026-10-20 LTS. If it shows 21 or older, your PATH or JAVA_HOME points at another JDK; fix that before you go on, or the build stops with an error about the release version.

Step 2 · Generate the project from start.spring.io

Spring Initializr at start.spring.io builds a ready-to-run project for you. Its website has a form, but the same service answers plain HTTP requests, which is quicker to repeat and fits in a script. Create a demo folder and ask for a Maven project with four dependencies:

Bash
mkdir -p ~/spring-books-demo
cd ~/spring-books-demo
curl -fsS https://start.spring.io/starter.zip \
  -d type=maven-project -d language=java \
  -d bootVersion=4.1.2 -d javaVersion=25 \
  -d groupId=com.example -d artifactId=books -d name=books \
  -d packageName=com.example.books \
  -d dependencies=web,validation,data-jpa,h2 \
  -o books.zip
unzip -q books.zip -d books
cd books

The four dependency IDs give you:

  • web: Spring MVC with an embedded Tomcat server. In Boot 4 this starter is called spring-boot-starter-webmvc.
  • validation: Jakarta Bean Validation, so you can put rules such as @NotBlank on fields.
  • data-jpa: Spring Data JPA with Hibernate, to store objects in a relational database.
  • h2: the H2 database, which runs inside your application's process.

If start.spring.io answers with an error about the Boot version, a newer 4.1 patch has replaced 4.1.2 there; change bootVersion to that release. Everything below works the same on any 4.1 patch.

Add two settings to the generated application.properties. The first gives the in-memory database a fixed name. The second turns off "open session in view", which Boot leaves on by default with a warning: it keeps a database session open for the whole web request, which hides slow lazy loading in your views.

Bash
cat >> src/main/resources/application.properties <<'PROPS'
spring.datasource.url=jdbc:h2:mem:books
spring.jpa.open-in-view=false
PROPS

Check it worked

Bash
ls
grep -c "<artifactId>spring-boot-starter-" pom.xml

ls shows HELP.md, mvnw, mvnw.cmd, pom.xml and src. The grep count is 7: the spring-boot-starter-parent that sets the versions, three main starters and a matching test starter for each of them. In Boot 4 test support is split by module, so spring-boot-starter-webmvc-test brings MockMvc and spring-boot-starter-data-jpa-test brings the JPA test slices.

Step 3 · Add the entity and the repository

An entity is a class that JPA maps to a table. Hibernate reads the annotations and, because H2 is an embedded database, Boot lets it create the books table at start-up. Every file in this tutorial goes in src/main/java/com/example/books/, the package start.spring.io created:

Bash
cat > src/main/java/com/example/books/Book.java <<'JAVA'
package com.example.books;

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

@Entity
@Table(name = "books")
public class Book {

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

    @Column(nullable = false, length = 200)
    private String title;

    @Column(nullable = false, length = 120)
    private String author;

    @Column(nullable = false)
    private int publishedYear;

    protected Book() {
    }

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

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public int getPublishedYear() { return publishedYear; }

    public void update(String title, String author, int publishedYear) {
        this.title = title;
        this.author = author;
        this.publishedYear = publishedYear;
    }
}
JAVA

JPA needs a no-argument constructor to build objects from rows; making it protected stops your own code from creating half-filled books. There are no setters: changes go through update, so a book is always changed as a whole. The field is publishedYear, not year, because YEAR is a reserved word in H2 and several other databases.

Now the repository. You write an interface; Spring Data writes the class at start-up:

Bash
cat > src/main/java/com/example/books/BookRepository.java <<'JAVA'
package com.example.books;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthorContainingIgnoreCaseOrderByTitle(String author);
}
JAVA

JpaRepository<Book, Long> gives you save, findById, findAll, delete and more. The extra method is a derived query: Spring Data reads its name and builds the SQL, a case-insensitive LIKE on author sorted by title. A misspelt property name in the method fails at start-up, not at the first request.

Check it worked

Bash
./mvnw -q compile
ls target/classes/com/example/books/

The first run of the wrapper downloads Maven and the project's dependencies, so it takes a few minutes. The listing then shows Book.class, BookRepository.class and BooksApplication.class.

On a prepaid data plan, run this first build on Wi-Fi if you can: the finished JAR alone is about 55 MB, and the first build downloads more than that. Later builds reuse the cache in ~/.m2, so they work offline.

Step 4 · Write the request and response records

Do not send the entity straight to clients. A separate type for each direction lets you change the table without breaking the API, and it stops clients from setting fields such as id. Java records are a good fit: one line declares the fields, the constructor, accessors, equals and toString, and Jackson reads and writes them without extra annotations.

Bash
cat > src/main/java/com/example/books/BookRequest.java <<'JAVA'
package com.example.books;

import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

public record BookRequest(
        @NotBlank @Size(max = 200) String title,
        @NotBlank @Size(max = 120) String author,
        @NotNull @Min(1450) @Max(2100) Integer publishedYear) {
}
JAVA
cat > src/main/java/com/example/books/BookResponse.java <<'JAVA'
package com.example.books;

public record BookResponse(Long id, String title, String author, int publishedYear) {

    static BookResponse from(Book book) {
        return new BookResponse(book.getId(), book.getTitle(), book.getAuthor(), book.getPublishedYear());
    }
}
JAVA

The rules live on the request record, next to the data they check. publishedYear is an Integer, not an int, so that a missing value arrives as null and @NotNull can report it; with an int it would silently become 0. @NotBlank rejects null, empty and whitespace-only text. The @Size limits match the column lengths on the entity, so the database never sees text it cannot store.

Titles in many languages are fine here: Java strings and H2 store full Unicode, so a Yoruba or Amharic title round-trips as sent. @Size counts UTF-16 characters, not bytes.

Check it worked

Bash
./mvnw -q compile
ls target/classes/com/example/books/ | grep -c Book

The build prints nothing, which means it succeeded, and the count is 5: Book, BookRepository, BookRequest, BookResponse and the generated BooksApplication.

Step 5 · Add the controller

The controller maps HTTP requests to Java methods. @RestController means every return value is written to the response body as JSON, and @RequestMapping sets the shared path:

Bash
cat > src/main/java/com/example/books/BookNotFoundException.java <<'JAVA'
package com.example.books;

public class BookNotFoundException extends RuntimeException {

    public BookNotFoundException(Long id) {
        super("No book with id " + id);
    }
}
JAVA
cat > src/main/java/com/example/books/BookController.java <<'JAVA'
package com.example.books;

import java.net.URI;
import java.util.List;

import jakarta.validation.Valid;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@RestController
@RequestMapping("/api/books")
public class BookController {

    private final BookRepository books;

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

    @GetMapping
    public List<BookResponse> list(@RequestParam(required = false) String author) {
        List<Book> found = (author == null || author.isBlank())
                ? books.findAll()
                : books.findByAuthorContainingIgnoreCaseOrderByTitle(author);
        return found.stream().map(BookResponse::from).toList();
    }

    @GetMapping("/{id}")
    public BookResponse get(@PathVariable Long id) {
        return BookResponse.from(find(id));
    }

    @PostMapping
    public ResponseEntity<BookResponse> create(@Valid @RequestBody BookRequest request) {
        Book saved = books.save(new Book(request.title(), request.author(), request.publishedYear()));
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}").buildAndExpand(saved.getId()).toUri();
        return ResponseEntity.created(location).body(BookResponse.from(saved));
    }

    @PutMapping("/{id}")
    public BookResponse update(@PathVariable Long id, @Valid @RequestBody BookRequest request) {
        Book book = find(id);
        book.update(request.title(), request.author(), request.publishedYear());
        return BookResponse.from(books.save(book));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        books.delete(find(id));
        return ResponseEntity.noContent().build();
    }

    private Book find(Long id) {
        return books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
    }
}
JAVA

A few choices worth knowing:

  • The repository arrives through the constructor. Spring sees the single constructor and passes in the bean it created, so there is no @Autowired and the field can be final.
  • @Valid on a @RequestBody runs the rules from BookRequest before the method body. If any rule fails, the method never runs.
  • POST answers 201 Created with a Location header pointing at the new book, built from the current request so it is correct behind any host name.
  • DELETE answers 204 No Content. A missing book throws BookNotFoundException, which you turn into a proper 404 in the next step. Without that step it would surface as a 500.

Check it worked

Bash
./mvnw -q compile
ls target/classes/com/example/books/BookController.class

The build prints nothing and the listing shows BookController.class.

Step 6 · Return errors as Problem Details

RFC 9457 defines a JSON shape for HTTP errors, sent with the content type application/problem+json. It has standard members (type, title, status, detail, instance) and allows extra ones. Spring has a ProblemDetail class for it, and a base class, ResponseEntityExceptionHandler, that already turns Spring MVC's own exceptions (malformed JSON, wrong HTTP method, unsupported content type) into Problem Details.

Write one @RestControllerAdvice that extends that base class. It handles your not-found exception and enriches the validation error with a map of which fields failed:

Bash
cat > src/main/java/com/example/books/ApiErrors.java <<'JAVA'
package com.example.books;

import java.util.Map;
import java.util.TreeMap;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@RestControllerAdvice
public class ApiErrors extends ResponseEntityExceptionHandler {

    @ExceptionHandler(BookNotFoundException.class)
    public ProblemDetail bookNotFound(BookNotFoundException ex) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
        problem.setTitle("Book not found");
        return problem;
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {
        Map<String, String> errors = new TreeMap<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            errors.putIfAbsent(error.getField(), error.getDefaultMessage());
        }
        ProblemDetail problem = ex.getBody();
        problem.setTitle("Invalid book");
        problem.setDetail("One or more fields are invalid.");
        problem.setProperty("errors", errors);
        return handleExceptionInternal(ex, problem, headers, status, request);
    }
}
JAVA

Returning a ProblemDetail from a handler is enough: Spring takes the status from it and sets the application/problem+json content type. setProperty adds a member outside the standard set, here errors. The TreeMap keeps the field names in a stable order, which makes responses and tests predictable. Note what the handler leaves out: no stack trace and no exception class names, which would tell an attacker about your code.

Check it worked

Bash
./mvnw -q compile
ls target/classes/com/example/books/ApiErrors.class

The build prints nothing and ApiErrors.class exists. You see it working in the next step.

Step 7 · Run the API and call it with curl

Start the application in a second terminal, from ~/spring-books-demo/books, and leave it running:

Bash
./mvnw spring-boot:run

The log ends with a line like Started BooksApplication in 2.9 seconds, and Tomcat listens on port 8080. Back in your first terminal, add two books:

Bash
curl -i -X POST http://localhost:8080/api/books \
  -H 'Content-Type: application/json' \
  -d '{"title":"Things Fall Apart","author":"Chinua Achebe","publishedYear":1958}'
curl -s -X POST http://localhost:8080/api/books \
  -H 'Content-Type: application/json' \
  -d '{"title":"Half of a Yellow Sun","author":"Chimamanda Ngozi Adichie","publishedYear":2006}'

Then read, filter, update and delete:

Bash
curl -s http://localhost:8080/api/books
curl -s "http://localhost:8080/api/books?author=adichie"
curl -s -X PUT http://localhost:8080/api/books/1 \
  -H 'Content-Type: application/json' \
  -d '{"title":"Things Fall Apart","author":"Chinua Achebe","publishedYear":1959}'
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://localhost:8080/api/books/2

Now break the rules on purpose: ask for a book that does not exist, and send a book with an empty title and an impossible year:

Bash
curl -s -i http://localhost:8080/api/books/99
curl -s -X POST http://localhost:8080/api/books \
  -H 'Content-Type: application/json' \
  -d '{"title":"","author":"Unknown","publishedYear":3000}'

Check it worked

  • The first POST shows HTTP/1.1 201, a Location: http://localhost:8080/api/books/1 header and the book as JSON with "id":1.
  • The list holds both books; the ?author=adichie filter returns only Half of a Yellow Sun, although the case differs.
  • The PUT returns the book with "publishedYear":1959, and the DELETE prints 204.
  • The missing book answers HTTP/1.1 404 with Content-Type: application/problem+json and a body like {"type":"about:blank","title":"Book not found","status":404,"detail":"No book with id 99","instance":"/api/books/99"}.
  • The invalid book answers with "title":"Invalid book", "status":400 and an errors object naming both fields, such as "publishedYear":"must be less than or equal to 2100" and "title":"must not be blank". Hibernate Validator translates these default messages into the JVM's language, so on a machine set to French or German you see them in that language.

Stop the application with Ctrl+C in the second terminal. The database lives in memory, so the books are gone when it stops.

Step 8 · Test the API with MockMvc

Calling the API by hand proves it works today. A test proves it keeps working. @SpringBootTest starts the whole application context, with the real repository and H2, and @AutoConfigureMockMvc gives you MockMvc, which sends requests through Spring MVC without opening a port:

Bash
cat > src/test/java/com/example/books/BookControllerTests.java <<'JAVA'
package com.example.books;

import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@AutoConfigureMockMvc
class BookControllerTests {

    @Autowired
    MockMvc mvc;

    @Test
    void createsAndReadsABook() throws Exception {
        String json = """
                {"title": "Things Fall Apart", "author": "Chinua Achebe", "publishedYear": 1958}
                """;
        String location = mvc.perform(post("/api/books")
                        .contentType(MediaType.APPLICATION_JSON).content(json))
                .andExpect(status().isCreated())
                .andExpect(header().string("Location", startsWith("http://localhost/api/books/")))
                .andReturn().getResponse().getHeader("Location");

        mvc.perform(get(location))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.title").value("Things Fall Apart"))
                .andExpect(jsonPath("$.publishedYear").value(1958));
    }

    @Test
    void rejectsAnInvalidBookWithProblemDetails() throws Exception {
        String json = """
                {"title": "", "author": "Unknown", "publishedYear": 3000}
                """;
        mvc.perform(post("/api/books")
                        .contentType(MediaType.APPLICATION_JSON).content(json))
                .andExpect(status().isBadRequest())
                .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
                .andExpect(jsonPath("$.title").value("Invalid book"))
                .andExpect(jsonPath("$.errors.title").exists())
                .andExpect(jsonPath("$.errors.publishedYear").exists());
    }

    @Test
    void returnsNotFoundForAMissingBook() throws Exception {
        mvc.perform(get("/api/books/9999"))
                .andExpect(status().isNotFound())
                .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
                .andExpect(jsonPath("$.detail").value("No book with id 9999"));
    }
}
JAVA
./mvnw test

The tests use Java text blocks (""") for the JSON, so the request bodies read as they would on the wire. Each test reads the ID back from the Location header or uses one that cannot exist, rather than assuming an ID, so the tests do not depend on the order they run in. The andExpect lines check the status, the content type and parts of the JSON with JsonPath expressions such as $.errors.title.

Check it worked

Near the end, Maven prints Tests run: 4, Failures: 0, Errors: 0, Skipped: 0 (your three tests plus the contextLoads test start.spring.io generated) and BUILD SUCCESS. To see a test fail, change "Invalid book" in ApiErrors.java to another title, run ./mvnw test again and read the assertion error Maven prints; then change it back.

Step 9 · Package and run the JAR

Maven's package phase compiles, runs the tests again and builds an executable JAR with Tomcat and every dependency inside it:

Bash
./mvnw -q package
ls -lh target/books-0.0.1-SNAPSHOT.jar

Run it on a different port, in the second terminal:

Bash
java -jar target/books-0.0.1-SNAPSHOT.jar --server.port=8081

Any --name=value argument overrides the same key in application.properties; environment variables such as SERVER_PORT=8081 work too, which is how you pass settings and secrets on a server without writing them into the code. From the first terminal:

Bash
curl -s http://localhost:8081/api/books
echo
curl -s -X POST http://localhost:8081/api/books \
  -H 'Content-Type: application/json' \
  -d '{"title":"Season of Migration to the North","author":"Tayeb Salih","publishedYear":1966}'
echo

Check it worked

ls shows a JAR of about 55 MB. The first curl prints []: the JAR started with a fresh in-memory database, so the books from the earlier run are gone. The POST returns the new book with "id":1. Stop the JAR with Ctrl+C. Before you keep real data, point spring.datasource.url at a server database such as PostgreSQL and manage the schema with a migration tool instead of letting Hibernate create it.

Step 10 · Clean up

Remove the demo project. The JDK stays installed, and Maven's download cache in ~/.m2 stays too, because other Java projects on your machine may use it:

Bash
cd ~
rm -rf ~/spring-books-demo

Check it worked

ls ~/spring-books-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.