Most Spring Boot tutorials stop at "it returns JSON". Real APIs also need input validation, clear error responses and a database that behaves the same on every machine. In this tutorial we will build a small but production-shaped REST API for managing members of a savings scheme, using Spring Boot 3, Java 21 and PostgreSQL running in Docker.
By the end you will have:
- A PostgreSQL database started with one command
- CRUD endpoints for members
- Request validation with clear error messages
- A global exception handler that returns consistent JSON errors
- Paginated list results
Prerequisites
- Java 21
- Maven 3.9+
- Docker and Docker Compose
-
curlor any API client
Step 1: Create the project
Go to start.spring.io and choose:
- Project: Maven, Language: Java, Spring Boot: the latest 3.x release
- Java: 21
- Dependencies: Spring Web, Spring Data JPA, Validation, PostgreSQL Driver
Download and unzip the project. Your pom.xml should contain these dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
Step 2: Start PostgreSQL with Docker Compose
Create compose.yaml in the project root:
services:
db:
image: postgres:16
environment:
POSTGRES_DB: members
POSTGRES_USER: app
POSTGRES_PASSWORD: app
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
Start it:
docker compose up -d
Using Docker means everyone on the team runs the same database version, and you never have to install PostgreSQL locally.
Step 3: Configure the connection
Replace the contents of src/main/resources/application.properties:
spring.datasource.url=jdbc:postgresql://localhost:5432/members
spring.datasource.username=app
spring.datasource.password=app
spring.jpa.hibernate.ddl-auto=update
spring.jpa.open-in-view=false
Two notes:
-
ddl-auto=updatelets Hibernate create the table for us. It is fine for a tutorial, but in a real project use a migration tool such as Flyway or Liquibase so schema changes are versioned and reviewed. -
open-in-view=falsestops database sessions from staying open during the whole web request. Turning it off early saves you from hard-to-find lazy loading problems later.
Step 4: Create the entity
Member.java:
package com.example.members;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDate;
@Entity
@Table(name = "member")
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String memberNumber;
@Column(nullable = false)
private String fullName;
@Column(nullable = false, unique = true)
private String email;
private LocalDate dateOfBirth;
@Column(nullable = false, precision = 15, scale = 2)
private BigDecimal monthlyContribution;
// getters and setters omitted for brevity
}
Notice two choices that matter in financial applications:
-
BigDecimalfor money, neverdouble. Floating-point types cannot represent many decimal amounts exactly, and the rounding errors add up. -
Explicit
precisionandscale, so the database column matches what the business expects.
Step 5: Add the repository
MemberRepository.java:
package com.example.members;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MemberRepository extends JpaRepository<Member, Long> {
boolean existsByEmail(String email);
boolean existsByMemberNumber(String memberNumber);
}
Spring Data generates the implementation, including the two existsBy queries, from the method names.
Step 6: Define request and response records
Do not expose your entity directly in the API. Use records for what clients send and receive. This keeps your database model free to change without breaking clients.
MemberRequest.java:
package com.example.members;
import jakarta.validation.constraints.*;
import java.math.BigDecimal;
import java.time.LocalDate;
public record MemberRequest(
@NotBlank String memberNumber,
@NotBlank @Size(max = 120) String fullName,
@NotBlank @Email String email,
@Past LocalDate dateOfBirth,
@NotNull @DecimalMin("0.00") BigDecimal monthlyContribution
) {}
MemberResponse.java:
package com.example.members;
import java.math.BigDecimal;
import java.time.LocalDate;
public record MemberResponse(
Long id,
String memberNumber,
String fullName,
String email,
LocalDate dateOfBirth,
BigDecimal monthlyContribution
) {
static MemberResponse from(Member m) {
return new MemberResponse(m.getId(), m.getMemberNumber(), m.getFullName(),
m.getEmail(), m.getDateOfBirth(), m.getMonthlyContribution());
}
}
Step 7: Put the business rules in a service
MemberService.java:
package com.example.members;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class MemberService {
private final MemberRepository repository;
public MemberService(MemberRepository repository) {
this.repository = repository;
}
@Transactional
public MemberResponse create(MemberRequest request) {
if (repository.existsByEmail(request.email())) {
throw new DuplicateMemberException("A member with this email already exists");
}
if (repository.existsByMemberNumber(request.memberNumber())) {
throw new DuplicateMemberException("A member with this member number already exists");
}
Member member = new Member();
apply(member, request);
return MemberResponse.from(repository.save(member));
}
@Transactional(readOnly = true)
public MemberResponse get(Long id) {
return MemberResponse.from(find(id));
}
@Transactional(readOnly = true)
public Page<MemberResponse> list(Pageable pageable) {
return repository.findAll(pageable).map(MemberResponse::from);
}
@Transactional
public MemberResponse update(Long id, MemberRequest request) {
Member member = find(id);
apply(member, request);
return MemberResponse.from(member);
}
@Transactional
public void delete(Long id) {
repository.delete(find(id));
}
private Member find(Long id) {
return repository.findById(id)
.orElseThrow(() -> new MemberNotFoundException(id));
}
private void apply(Member m, MemberRequest r) {
m.setMemberNumber(r.memberNumber());
m.setFullName(r.fullName());
m.setEmail(r.email());
m.setDateOfBirth(r.dateOfBirth());
m.setMonthlyContribution(r.monthlyContribution());
}
}
In update, we never call save. The member was loaded inside the transaction, so Hibernate tracks it and writes the changes when the transaction commits.
The two exceptions are simple:
public class MemberNotFoundException extends RuntimeException {
public MemberNotFoundException(Long id) {
super("Member " + id + " not found");
}
}
public class DuplicateMemberException extends RuntimeException {
public DuplicateMemberException(String message) {
super(message);
}
}
The
existsBychecks give friendly error messages, but they are not enough on their own: two requests can pass the check at the same moment. Theuniqueconstraints on the table are your real safety net.
Step 8: Expose the endpoints
MemberController.java:
package com.example.members;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/members")
public class MemberController {
private final MemberService service;
public MemberController(MemberService service) {
this.service = service;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public MemberResponse create(@Valid @RequestBody MemberRequest request) {
return service.create(request);
}
@GetMapping("/{id}")
public MemberResponse get(@PathVariable Long id) {
return service.get(id);
}
@GetMapping
public Page<MemberResponse> list(Pageable pageable) {
return service.list(pageable);
}
@PutMapping("/{id}")
public MemberResponse update(@PathVariable Long id, @Valid @RequestBody MemberRequest request) {
return service.update(id, request);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
service.delete(id);
}
}
@Valid tells Spring to run the validation annotations from MemberRequest before your code runs.
Step 9: Return consistent errors
Without a handler, clients get Spring's default error page format, which differs between error types. Spring Boot 3 supports ProblemDetail, a standard JSON error format:
ApiExceptionHandler.java:
package com.example.members;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.stream.Collectors;
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(MemberNotFoundException.class)
ProblemDetail notFound(MemberNotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
@ExceptionHandler(DuplicateMemberException.class)
ProblemDetail duplicate(DuplicateMemberException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail invalid(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Validation failed");
problem.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
.collect(Collectors.toMap(
e -> e.getField(),
e -> e.getDefaultMessage(),
(first, second) -> first)));
return problem;
}
}
Now every error has the same shape: a status, a title and a detail, plus a map of field errors for validation failures.
Step 10: Try it out
Run the app:
./mvnw spring-boot:run
Create a member:
curl -i -X POST http://localhost:8080/api/members \
-H "Content-Type: application/json" \
-d '{"memberNumber":"M-1001","fullName":"Jane Wanjiru","email":"jane@example.com","dateOfBirth":"1990-04-12","monthlyContribution":"5000.00"}'
You should get 201 Created with the new member in the body.
Send an invalid request:
curl -s -X POST http://localhost:8080/api/members \
-H "Content-Type: application/json" \
-d '{"memberNumber":"","fullName":"","email":"not-an-email","monthlyContribution":"-1"}'
The response lists every problem at once:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Validation failed",
"instance": "/api/members",
"errors": {
"memberNumber": "must not be blank",
"fullName": "must not be blank",
"email": "must be a well-formed email address",
"monthlyContribution": "must be greater than or equal to 0.00"
}
}
List members, 10 per page, sorted by name:
curl -s "http://localhost:8080/api/members?page=0&size=10&sort=fullName"
Where to go next
You now have a clean base for a real service. Natural next steps:
-
Replace
ddl-auto=updatewith Flyway so your schema changes are versioned. - Add integration tests with Testcontainers, which starts a real PostgreSQL container during your tests.
- Add Spring Security before exposing any of this outside your machine.
In my day job I work on Java systems that handle pension contributions, where getting money types, validation and error handling right from the start saves a lot of pain later. I hope this gives you a solid starting point. Questions and improvements are welcome in the comments.
I'm Mackrine Awino, a full-stack software engineer in Nairobi working with Java, Jakarta EE, Spring Boot and React. You can find me on LinkedIn and GitHub.
Top comments (0)