Capstone: A Tasks API
The Tasks API is the full app built across this course. It joins a controller, a service, a repository, validation, and error handling into one working API.
List the tasks
This method answers GET /tasks. It asks the service for the full list.
@GetMapping("/tasks")
public List<TaskResponse> getTasks() {
return service.findAll();
}Add a task
This method answers POST /tasks. The @Valid mark checks the request before the service runs.
@PostMapping("/tasks")
public TaskResponse addTask(@Valid @RequestBody TaskRequest request) {
return service.addTask(request);
}Example
package com.example.demo;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TaskController {
private final TaskService service;
public TaskController(TaskService service) {
this.service = service;
}
@GetMapping("/tasks")
public List<TaskResponse> getTasks() {
return service.findAll();
}
@PostMapping("/tasks")
public TaskResponse addTask(@Valid @RequestBody TaskRequest request) {
return service.addTask(request);
}
}Key points
- The controller takes requests and returns answers.
- The service holds the task rules between the two layers.
- The repository saves tasks and reads them back.
- Validation rejects a task with an empty title.
- Error handling answers a missing task with 404.
- The API stores three seed tasks at the start.
In this example, the controller takes the TaskService through its constructor. The getTasks method answers GET /tasks with the full list. The addTask method takes a task from the request body. The @Valid mark checks the request before the service runs. The service saves the task through the repository. The GET answer lists the three seed tasks in seed order.
Note
Every piece here was taught in an earlier lesson.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the Tasks API join into one app?