Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 66 ยท Projects

Project: Todo REST API

Build a complete Spring Boot Todo REST API: CRUD endpoints, validation, consistent errors, pagination and tests, with a runnable plain-Java model of the core.

Time to put the pieces together. In this project you build a small but complete Todo API: create, read, update and delete todos, with validated input, consistent error responses, paginated lists and automated tests. It is deliberately small so you can see every layer clearly, and it follows the same shape as real services: controller, service, repository, database.

You will combine ideas from earlier lessons: REST Controllers, Request and Response Bodies, Bean Validation, Error Handling and Problem Details and Spring Data JPA Repositories. For a second, differently styled walk-through see Project: Spring Boot API.

Spring Boot and a database cannot run on this site, so the real Spring code is read-only. Two runnable stand-ins model the project: a plain-Java version of the core logic (with self-checks) and a tiny HTTP layer built on real Jackson that shows the status codes and error bodies.

What we are building

Request What it does Success Failures
POST /api/todos Create a todo 201 + Location header 400 invalid input
GET /api/todos?done=&page=&size= List todos, one page at a time 200 400 bad parameters
GET /api/todos/{id} Read one 200 404
PUT /api/todos/{id} Replace title, description and done 200 400, 404
DELETE /api/todos/{id} Remove 204 404

Four layers, one job each

Controller HTTP in, HTTP out. No business rules.
Service Rules, transactions, not-found handling.
Repository Queries and paging through Spring Data.
Database H2 for development and tests.

A request flows down, the result flows back up as a DTO.

1 / 2

Step 1: the project

Create the project with Spring Initializr as in Creating a Project, choosing Web, Validation, Spring Data JPA and H2. The dependency block looks like this:

XML
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

Two settings in application.yml protect the API from careless clients and give clients standard error bodies:

YAML
spring:
  mvc:
    problemdetails:
      enabled: true
  data:
    web:
      pageable:
        max-page-size: 100
        default-page-size: 20

Step 2: entity and repository

The entity is the database model. It never leaves the service layer:

Java
@Entity
public class Todo {

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

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

    @Column(length = 2000)
    private String description;

    private boolean done;

    private Instant createdAt = Instant.now();

    protected Todo() {
    }

    public Todo(String title, String description) {
        this.title = title;
        this.description = description;
    }

    public void change(String title, String description, boolean done) {
        this.title = title;
        this.description = description;
        this.done = done;
    }

    // getters omitted
}
Java
public interface TodoRepository extends JpaRepository<Todo, Long> {

    Page<Todo> findByDone(boolean done, Pageable pageable);
}

findAll(Pageable) comes from JpaRepository, and findByDone is a derived query. Both accept a Pageable, so paging and sorting cost no extra code.

Step 3: DTOs with validation

The API shape is separate from the entity, so you can change the database without breaking clients, and clients cannot set fields such as id or createdAt:

Java
public record CreateTodoRequest(
    @NotBlank @Size(max = 120) String title,
    @Size(max = 2000) String description) {
}

public record UpdateTodoRequest(
    @NotBlank @Size(max = 120) String title,
    @Size(max = 2000) String description,
    boolean done) {
}

public record TodoResponse(long id, String title, String description, boolean done) {

    static TodoResponse from(Todo todo) {
        return new TodoResponse(todo.getId(), todo.getTitle(), todo.getDescription(), todo.isDone());
    }
}

public record PageResponse<T>(List<T> items, int page, int size, long total, int totalPages) {

    static <T> PageResponse<T> of(Page<T> page) {
        return new PageResponse<>(page.getContent(), page.getNumber(), page.getSize(),
            page.getTotalElements(), page.getTotalPages());
    }
}

We return our own PageResponse rather than Spring Data's Page object, so the JSON shape is a stable part of your API instead of an implementation detail of a library.

Step 4: the service

Java
@Service
@Transactional(readOnly = true)
public class TodoService {

    private final TodoRepository repository;

    public TodoService(TodoRepository repository) {
        this.repository = repository;
    }

    @Transactional
    public TodoResponse create(CreateTodoRequest request) {
        Todo todo = repository.save(new Todo(request.title().strip(), request.description()));
        return TodoResponse.from(todo);
    }

    public TodoResponse get(long id) {
        return TodoResponse.from(find(id));
    }

    public PageResponse<TodoResponse> list(Boolean done, Pageable pageable) {
        Page<Todo> page = (done == null)
            ? repository.findAll(pageable)
            : repository.findByDone(done, pageable);
        return PageResponse.of(page.map(TodoResponse::from));
    }

    @Transactional
    public TodoResponse update(long id, UpdateTodoRequest request) {
        Todo todo = find(id);
        todo.change(request.title().strip(), request.description(), request.done());
        return TodoResponse.from(todo);   // dirty checking saves the change
    }

    @Transactional
    public void delete(long id) {
        repository.delete(find(id));
    }

    private Todo find(long id) {
        return repository.findById(id).orElseThrow(() -> new TodoNotFoundException(id));
    }
}
Java
public class TodoNotFoundException extends RuntimeException {
    public TodoNotFoundException(long id) {
        super("No todo with id " + id);
    }
}

The service holds the rules that do not belong to HTTP: it throws a domain exception instead of returning null, and it marks write methods @Transactional. See Transactions with @Transactional for why readOnly is the class default. The next example is a plain-Java model of this logic, with the same rules and the same exceptions, so you can run them and see the behavior.

Java The core logic as plain Java

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Step 5: the controller

The controller translates HTTP to service calls and back:

Java
@RestController
@RequestMapping("/api/todos")
public class TodoController {

    private final TodoService service;

    public TodoController(TodoService service) {
        this.service = service;
    }

    @PostMapping
    ResponseEntity<TodoResponse> create(@Valid @RequestBody CreateTodoRequest request) {
        TodoResponse created = service.create(request);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
            .path("/{id}").buildAndExpand(created.id()).toUri();
        return ResponseEntity.created(location).body(created);
    }

    @GetMapping
    PageResponse<TodoResponse> list(
            @RequestParam(required = false) Boolean done,
            @PageableDefault(size = 20, sort = "id") Pageable pageable) {
        return service.list(done, pageable);
    }

    @GetMapping("/{id}")
    TodoResponse get(@PathVariable long id) {
        return service.get(id);
    }

    @PutMapping("/{id}")
    TodoResponse update(@PathVariable long id, @Valid @RequestBody UpdateTodoRequest request) {
        return service.update(id, request);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    void delete(@PathVariable long id) {
        service.delete(id);
    }
}

@Valid triggers validation before the method body runs. ResponseEntity.created(...) produces 201 with a Location header, so the client learns where the new resource lives. Pageable is filled from ?page=, ?size= and ?sort=, and the max-page-size setting caps size.

Step 6: consistent errors

One advice class turns exceptions into problem details. It extends ResponseEntityExceptionHandler so Spring's own exceptions (malformed JSON, wrong method, bad parameter type) already produce application/problem+json, and adds our domain exception and field errors:

Java
@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(TodoNotFoundException.class)
    ProblemDetail notFound(TodoNotFoundException ex) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
        problem.setTitle("Todo not found");
        return problem;
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {
        Map<String, String> errors = new LinkedHashMap<>();
        ex.getBindingResult().getFieldErrors()
            .forEach(e -> errors.putIfAbsent(e.getField(), String.valueOf(e.getDefaultMessage())));
        ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        problem.setTitle("Validation failed");
        problem.setProperty("errors", errors);
        return handleExceptionInternal(ex, problem, headers, status, request);
    }
}

A client-supplied ?sort=nonsense makes Spring Data throw a PropertyReferenceException. Add a handler that turns it into a 400, or restrict the sortable fields, so that bad input never becomes a 500.

The next stand-in is a tiny HTTP layer using real Jackson. It routes a method and path to the right action, maps exceptions to status codes and hides internal details on a server error, like the advice class above.

Java A tiny HTTP layer with Jackson

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the last line: the server error body says only "Something went wrong." The database detail stays on the server, as the error-handling lesson recommends.

Step 7: tests

Test each layer with the narrowest tool that covers it. A web slice test checks status codes, validation and JSON without starting the whole application or a real server:

Java
@WebMvcTest(TodoController.class)
class TodoControllerTest {

    @Autowired
    MockMvcTester mvc;

    @MockitoBean
    TodoService service;

    @Test
    void blankTitleIsRejectedWithFieldErrors() {
        assertThat(mvc.post().uri("/api/todos")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"title\": \"  \"}"))
            .hasStatus(HttpStatus.BAD_REQUEST)
            .bodyJson().extractingPath("$.errors.title").isEqualTo("must not be blank");
    }

    @Test
    void unknownTodoReturnsNotFound() {
        when(service.get(42)).thenThrow(new TodoNotFoundException(42));

        assertThat(mvc.get().uri("/api/todos/42"))
            .hasStatus(HttpStatus.NOT_FOUND);
    }
}

A data slice test runs the real repository against an in-memory database:

Java
@DataJpaTest
class TodoRepositoryTest {

    @Autowired
    TodoRepository repository;

    @Test
    void findByDoneReturnsOnlyMatchingTodosOnePageAtATime() {
        for (int i = 0; i < 5; i++) {
            Todo todo = new Todo("task " + i, null);
            todo.change(todo.getTitle(), null, i % 2 == 0);
            repository.save(todo);
        }

        Page<Todo> firstPage = repository.findByDone(true, PageRequest.of(0, 2));

        assertThat(firstPage.getContent()).hasSize(2);
        assertThat(firstPage.getTotalElements()).isEqualTo(3);
    }
}

Finally, one @SpringBootTest that creates a todo and reads it back guards the wiring between the layers. The details of these annotations are the topic of the Testing chapter.

Ideas for extending it

  • Add createdAt and completedAt to TodoResponse and sort by them.
  • Add a search parameter ?q= using a derived query such as findByTitleContainingIgnoreCase.
  • Replace ddl-auto with a Flyway migration for the table.
  • Add an optimistic-locking @Version field so two clients cannot silently overwrite each other.
  • Protect the endpoints with Spring Security so each user sees only their own todos.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the controller return TodoResponse records instead of the Todo entity?

    DTOs decouple the public contract from persistence details and prevent clients from writing fields like id or createdAt.
  2. 2. What does ResponseEntity.created(location) add compared with returning the object directly?

    Creating a resource should answer 201 Created and tell the client where it lives through the Location header.
  3. 3. Why is a max-page-size of 100 configured?

    An unbounded list endpoint is a performance and availability risk. The cap keeps response sizes predictable.
  4. 4. Which test slice runs the controller layer with a mocked service, without starting a real server?

    @WebMvcTest loads only the web layer, which makes tests fast and focused on status codes, validation and serialization.

Summary

  • A small API still needs four layers: controller (HTTP), service (rules and transactions), repository (data) and DTOs between them.
  • Validate input with Bean Validation, return 201 plus Location on create, 204 on delete and 404 through a domain exception.
  • Paginate every list endpoint and cap the page size.
  • Centralize errors with @RestControllerAdvice and ProblemDetail; never leak internals on a 500.
  • Test with the narrowest slice: @WebMvcTest for HTTP, @DataJpaTest for queries, one @SpringBootTest for wiring.

Next: Project: URL Shortener Service.