Spring Boot Mini Project
Let's build a complete task-tracker REST API step by step, using everything from this course: a JPA entity and repository, DTO records with validation, a transactional service, a controller with proper status codes, global error handling with ProblemDetail, pagination, and tests.
Dependencies (start.spring.io): Spring Web, Validation, Spring Data JPA, H2 Database, Spring Boot Actuator.
The API we are building
| Method & path | Does | Success |
|---|---|---|
GET /api/tasks?done=&page=&size=&sort= |
list tasks, paged | 200 |
GET /api/tasks/{id} |
one task | 200 / 404 |
POST /api/tasks |
create | 201 + Location / 400 / 409 |
PATCH /api/tasks/{id} |
partial update | 200 / 400 / 404 |
POST /api/tasks/{id}/complete |
mark as done | 200 / 404 |
DELETE /api/tasks/{id} |
delete | 204 / 404 |
com.example.tasks
├── TasksApplication.java
└── task
├── Task.java entity
├── Priority.java enum
├── TaskRepository.java Spring Data
├── TaskDtos.java request/response records
├── TaskService.java business logic, transactions
├── TaskController.java HTTP
└── TaskErrors.java exceptions + @RestControllerAdviceStep 1: entity and repository
public enum Priority { LOW, MEDIUM, HIGH }
@Entity
@Table(name = "tasks")
public class Task {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 120, unique = true)
private String title;
@Enumerated(EnumType.STRING) @Column(nullable = false, length = 10)
private Priority priority;
private boolean done;
private LocalDate dueDate;
protected Task() {}
public Task(String title, Priority priority, LocalDate dueDate) {
this.title = title; this.priority = priority; this.dueDate = dueDate;
}
public void complete() { done = true; }
public void rename(String title) { this.title = title; }
public void reprioritise(Priority p) { this.priority = p; }
public void reschedule(LocalDate d) { this.dueDate = d; }
// getters omitted
}
public interface TaskRepository extends JpaRepository<Task, Long> {
Page<Task> findByDone(boolean done, Pageable pageable);
boolean existsByTitleIgnoreCase(String title);
}Step 2: DTO records
public record CreateTask(@NotBlank @Size(max = 120) String title,
@NotNull Priority priority,
@FutureOrPresent LocalDate dueDate) {}
public record UpdateTask(@Size(min = 1, max = 120) String title,
Priority priority,
@FutureOrPresent LocalDate dueDate) {}
public record TaskResponse(long id, String title, Priority priority, boolean done, LocalDate dueDate) {
static TaskResponse from(Task t) {
return new TaskResponse(t.getId(), t.getTitle(), t.getPriority(), t.isDone(), t.getDueDate());
}
}Step 3: the service
@Service
@Transactional
public class TaskService {
private final TaskRepository tasks;
public TaskService(TaskRepository tasks) { this.tasks = tasks; }
@Transactional(readOnly = true)
public Page<TaskResponse> list(boolean done, Pageable pageable) {
return tasks.findByDone(done, pageable).map(TaskResponse::from);
}
@Transactional(readOnly = true)
public TaskResponse get(long id) { return TaskResponse.from(load(id)); }
public TaskResponse create(CreateTask req) {
if (tasks.existsByTitleIgnoreCase(req.title())) throw new DuplicateTitleException(req.title());
return TaskResponse.from(tasks.save(new Task(req.title().strip(), req.priority(), req.dueDate())));
}
public TaskResponse update(long id, UpdateTask req) {
Task t = load(id);
if (req.title() != null) t.rename(req.title().strip());
if (req.priority() != null) t.reprioritise(req.priority());
if (req.dueDate() != null) t.reschedule(req.dueDate());
return TaskResponse.from(t); // dirty checking saves the changes
}
public TaskResponse complete(long id) {
Task t = load(id);
t.complete();
return TaskResponse.from(t);
}
public void delete(long id) { tasks.delete(load(id)); }
private Task load(long id) {
return tasks.findById(id).orElseThrow(() -> new TaskNotFoundException(id));
}
}Step 4: the controller
@RestController
@RequestMapping("/api/tasks")
class TaskController {
private final TaskService service;
TaskController(TaskService service) { this.service = service; }
@GetMapping
PagedModel<TaskResponse> list(@RequestParam(defaultValue = "false") boolean done,
@PageableDefault(size = 20, sort = "dueDate") Pageable pageable) {
return new PagedModel<>(service.list(done, pageable));
}
@GetMapping("/{id}")
TaskResponse get(@PathVariable long id) { return service.get(id); }
@PostMapping
ResponseEntity<TaskResponse> create(@Valid @RequestBody CreateTask req, UriComponentsBuilder uri) {
TaskResponse created = service.create(req);
return ResponseEntity.created(uri.path("/api/tasks/{id}").buildAndExpand(created.id()).toUri())
.body(created);
}
@PatchMapping("/{id}")
TaskResponse update(@PathVariable long id, @Valid @RequestBody UpdateTask req) { return service.update(id, req); }
@PostMapping("/{id}/complete")
TaskResponse complete(@PathVariable long id) { return service.complete(id); }
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
void delete(@PathVariable long id) { service.delete(id); }
}Step 5: errors
class TaskNotFoundException extends RuntimeException {
TaskNotFoundException(long id) { super("Task " + id + " not found"); }
}
class DuplicateTitleException extends RuntimeException {
DuplicateTitleException(String t) { super("A task titled '" + t + "' already exists"); }
}
@RestControllerAdvice
class TaskErrors extends ResponseEntityExceptionHandler {
@ExceptionHandler(TaskNotFoundException.class)
ProblemDetail notFound(TaskNotFoundException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
}
@ExceptionHandler(DuplicateTitleException.class)
ProblemDetail duplicate(DuplicateTitleException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
Map<String, String> errors = new TreeMap<>();
ex.getBindingResult().getFieldErrors().forEach(f -> errors.put(f.getField(), f.getDefaultMessage()));
ProblemDetail pd = ex.getBody();
pd.setProperty("errors", errors);
return ResponseEntity.status(status).body(pd);
}
}spring.application.name=tasks
spring.jpa.open-in-view=false
management.endpoints.web.exposure.include=health,infoStep 6: try it
curl -s -X POST localhost:8080/api/tasks -H "Content-Type: application/json" \
-d '{"title":"Write README","priority":"HIGH","dueDate":"2025-11-01"}' -i | grep -E "^(HTTP|Location)|^\{"
curl -s -X POST localhost:8080/api/tasks -H "Content-Type: application/json" \
-d '{"title":"Set up CI","priority":"MEDIUM"}'
echo
curl -s -X POST localhost:8080/api/tasks/1/complete
echo
curl -s -X PATCH localhost:8080/api/tasks/2 -H "Content-Type: application/json" -d '{"priority":"LOW"}'
echo
curl -s "localhost:8080/api/tasks?done=false"
echo
curl -s -X POST localhost:8080/api/tasks -H "Content-Type: application/json" \
-d '{"title":"write readme","priority":"LOW"}'
echo
curl -s -X DELETE localhost:8080/api/tasks/7
echo
curl -s -X DELETE localhost:8080/api/tasks/2 -w "%{http_code}\n"HTTP/1.1 201
Location: http://localhost:8080/api/tasks/1
{"id":1,"title":"Write README","priority":"HIGH","done":false,"dueDate":"2025-11-01"}
{"id":2,"title":"Set up CI","priority":"MEDIUM","done":false,"dueDate":null}
{"id":1,"title":"Write README","priority":"HIGH","done":true,"dueDate":"2025-11-01"}
{"id":2,"title":"Set up CI","priority":"LOW","done":false,"dueDate":null}
{"content":[{"id":2,"title":"Set up CI","priority":"LOW","done":false,"dueDate":null}],"page":{"size":20,"number":0,"totalElements":1,"totalPages":1}}
{"type":"about:blank","title":"Conflict","status":409,"detail":"A task titled 'write readme' already exists","instance":"/api/tasks"}
{"type":"about:blank","title":"Not Found","status":404,"detail":"Task 7 not found","instance":"/api/tasks/7"}
204
The service logic, runnable
Here is the core of TaskService — duplicate check, partial update, completion, not-found handling — with an in-memory repository instead of JPA, exercised in the same order as the curl session:
import java.util.*;
enum Priority { LOW, MEDIUM, HIGH }
class Task {
final long id; String title; Priority priority; boolean done;
Task(long id, String title, Priority priority) { this.id = id; this.title = title; this.priority = priority; }
}
record CreateTask(String title, Priority priority) {}
record UpdateTask(String title, Priority priority) {}
record TaskResponse(long id, String title, Priority priority, boolean done) {
static TaskResponse from(Task t) { return new TaskResponse(t.id, t.title, t.priority, t.done); }
}
class ApiException extends RuntimeException {
final int status;
ApiException(int status, String msg) { super(msg); this.status = status; }
}
class TaskService {
private final Map<Long, Task> repo = new TreeMap<>();
private long nextId = 1;
TaskResponse create(CreateTask req) {
if (req.title() == null || req.title().isBlank()) throw new ApiException(400, "title: must not be blank");
boolean exists = repo.values().stream().anyMatch(t -> t.title.equalsIgnoreCase(req.title().strip()));
if (exists) throw new ApiException(409, "A task titled '" + req.title() + "' already exists");
Task t = new Task(nextId++, req.title().strip(), req.priority());
repo.put(t.id, t);
return TaskResponse.from(t);
}
TaskResponse update(long id, UpdateTask req) {
Task t = load(id);
if (req.title() != null) t.title = req.title().strip();
if (req.priority() != null) t.priority = req.priority();
return TaskResponse.from(t);
}
TaskResponse complete(long id) { Task t = load(id); t.done = true; return TaskResponse.from(t); }
List<TaskResponse> list(boolean done) {
return repo.values().stream().filter(t -> t.done == done).map(TaskResponse::from).toList();
}
void delete(long id) { repo.remove(load(id).id); }
private Task load(long id) {
Task t = repo.get(id);
if (t == null) throw new ApiException(404, "Task " + id + " not found");
return t;
}
}
class Main {
interface Call { Object run(); }
static void http(String label, int okStatus, Call call) {
try {
Object body = call.run();
System.out.println(label + " -> " + okStatus + (body == null ? "" : " " + body));
} catch (ApiException e) {
System.out.println(label + " -> " + e.status + " " + e.getMessage());
}
}
public static void main(String[] args) {
TaskService s = new TaskService();
http("POST /api/tasks", 201, () -> s.create(new CreateTask("Write README", Priority.HIGH)));
http("POST /api/tasks", 201, () -> s.create(new CreateTask("Set up CI", Priority.MEDIUM)));
http("POST /api/tasks/1/complete", 200, () -> s.complete(1));
http("PATCH /api/tasks/2", 200, () -> s.update(2, new UpdateTask(null, Priority.LOW)));
http("GET /api/tasks?done=false", 200, () -> s.list(false));
http("POST /api/tasks", 201, () -> s.create(new CreateTask("write readme", Priority.LOW)));
http("POST /api/tasks", 201, () -> s.create(new CreateTask(" ", Priority.LOW)));
http("DELETE /api/tasks/7", 204, () -> { s.delete(7); return null; });
http("DELETE /api/tasks/2", 204, () -> { s.delete(2); return null; });
http("GET /api/tasks?done=false", 200, () -> s.list(false));
}
}POST /api/tasks -> 201 TaskResponse[id=1, title=Write README, priority=HIGH, done=false]
POST /api/tasks -> 201 TaskResponse[id=2, title=Set up CI, priority=MEDIUM, done=false]
POST /api/tasks/1/complete -> 200 TaskResponse[id=1, title=Write README, priority=HIGH, done=true]
PATCH /api/tasks/2 -> 200 TaskResponse[id=2, title=Set up CI, priority=LOW, done=false]
GET /api/tasks?done=false -> 200 [TaskResponse[id=2, title=Set up CI, priority=LOW, done=false]]
POST /api/tasks -> 409 A task titled 'write readme' already exists
POST /api/tasks -> 400 title: must not be blank
DELETE /api/tasks/7 -> 404 Task 7 not found
DELETE /api/tasks/2 -> 204
GET /api/tasks?done=false -> 200 []
Step 7: tests
@WebMvcTest(TaskController.class)
class TaskControllerTest {
@Autowired MockMvc mvc;
@MockitoBean TaskService service;
@Test
void createReturns201WithLocation() throws Exception {
when(service.create(any())).thenReturn(new TaskResponse(1, "Write README", Priority.HIGH, false, null));
mvc.perform(post("/api/tasks").contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"Write README\",\"priority\":\"HIGH\"}"))
.andExpect(status().isCreated())
.andExpect(header().string("Location", "http://localhost/api/tasks/1"))
.andExpect(jsonPath("$.title").value("Write README"));
}
@Test
void blankTitleReturns400() throws Exception {
mvc.perform(post("/api/tasks").contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\" \",\"priority\":\"HIGH\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.title").value("must not be blank"));
}
}./mvnw test | grep -E "Tests run:|BUILD"[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.391 s -- in com.example.tasks.task.TaskControllerTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.874 s -- in com.example.tasks.TasksApplicationTests
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
Ideas to extend it
- Add a
Projectentity with a@ManyToOnefromTask, andGET /api/projects/{id}/tasks. - Replace
ddl-autowith Flyway migrations and run against PostgreSQL in Docker Compose. - Protect write endpoints with Spring Security (
hasRole("EDITOR")). - Add a custom health indicator and a
tasks.completedMicrometer counter. - Package it with
./mvnw spring-boot:build-imageand run the container with theprodprofile.
Test yourself
Why does TaskService.update not call repository.save?
- It forgot to
- The entity is managed inside the transaction, so dirty checking writes the changes at commit
- PATCH requests never change data
- save is called by the controller
Which status should creating a task with a title that already exists return?
- 200
- 400
- 409
- 500
Why does the controller return TaskResponse instead of the Task entity?
- Entities cannot be serialised
- To decouple the API contract from the persistence model and avoid leaking fields or lazy-loading issues
- Records are faster
- Spring requires DTOs