Building a REST API with Spring Boot
Java & Spring Boot for Beginners · Part 9 of 14
- #Java
- #Spring Boot
- #Beginners
- #Tutorial
- #REST API
Part 8 left you with a running
task-tracker service and exactly one endpoint: GET /api/tasks, returning
a hardcoded list from inside the controller itself. That's not a REST API,
it's a fixture with extra steps. This post turns it into one — GET,
POST, PUT, and DELETE over the same Task domain, a proper split
between the shape you expose over HTTP and the shape you work with in code,
and a service layer sitting between them that's doing real work, not just
adding a hop. Persistence is still out of scope — everything lives in a
Map in memory and resets on restart. Spring Data JPA, which fixes that, is
Part 10. Don't let it creep in early; the point of this post is the API
shape, and a database at this stage would just be one more thing to debug
at the same time.
Three layers, three jobs
Every non-trivial Spring Boot API ends up with roughly the same three-layer split, and it's worth understanding why before writing any of it:
- Controller — owns HTTP. Maps verbs and paths to methods, pulls data
out of the request (
@PathVariable,@RequestBody), and translates whatever the service hands back into a status code and a response body. It should not contain business logic. - Service — owns the rules. "A task can't be marked done twice," "an id that doesn't exist is a 404, not a 500," "creating a task assigns the next id" — that kind of decision lives here, not in the controller and not in the storage layer.
- Repository / store — owns persistence. Right now that's a
Mapyou wrote by hand; from Part 10 on it's Spring Data JPA. The point of drawing the line here at all is that the service layer's code doesn't change when the storage underneath it does.
The temptation, especially on a toy project, is to skip straight to "why not
just put the Map and the logic in the controller and save a file?" You
can, and for a single-endpoint demo it doesn't matter. It stops working the
moment two controllers need the same rule — say, an admin endpoint that also
validates task creation — and you either duplicate the check or reach
across controllers to call one from another, which is worse. The service
layer is what lets TaskController and, later, an AdminController or a
scheduled job both call createTask without either one owning the rule for
what a valid task is. It's not about lines of code — it's about there being
exactly one place a given rule lives.
DTOs vs. the entity: two shapes, one domain
Task from Part 8 is doing double duty right now — it's both "the thing
stored" and "the JSON on the wire," and that coincidence won't survive this
post. The two are going to diverge in a specific way: creating a task
shouldn't let the caller supply an id (the server assigns it), and once
JPA shows up in Part 10 the persisted entity is going to pick up fields —
version columns, audit timestamps, @Id generation strategy — that have no
business appearing in a JSON response. Keeping "what's stored" and "what's
exposed" as the same type means every change to one is a silent change to
the other.
So this post introduces two request DTOs (data transfer objects) alongside
the existing Task:
package dev.josealencar.tasktracker;
public record CreateTaskRequest(String title) {}
package dev.josealencar.tasktracker;
public record UpdateTaskRequest(String title, boolean done) {}
Both are records, same as Task — no getters or constructors to write by
hand for what's fundamentally a labeled tuple. CreateTaskRequest has no
id field at all, which isn't an oversight: the client doesn't get to pick
an id, the service does. UpdateTaskRequest has no id either, because the
id for an update comes from the URL path, not the body — a PUT /api/tasks/3 with an id: 7 in the body would be a contradiction, so the
type just doesn't allow it.
This is more ceremony than a single-endpoint demo needs, and for a throwaway script I wouldn't bother. On anything that's going to grow, the DTO boundary is what stops a database column rename from becoming a breaking API change, and what stops an API field rename from forcing a migration. They fail independently — worth the extra files.
The service layer
package dev.josealencar.tasktracker;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
@Service
public class TaskService {
private final Map<Long, Task> tasks = new ConcurrentHashMap<>();
private final AtomicLong nextId = new AtomicLong(1);
public List<Task> findAll() {
return List.copyOf(tasks.values());
}
public Optional<Task> findById(Long id) {
return Optional.ofNullable(tasks.get(id));
}
public Task create(CreateTaskRequest request) {
long id = nextId.getAndIncrement();
Task task = new Task(id, request.title(), false);
tasks.put(id, task);
return task;
}
public Optional<Task> update(Long id, UpdateTaskRequest request) {
return findById(id).map(existing -> {
Task updated = new Task(id, request.title(), request.done());
tasks.put(id, updated);
return updated;
});
}
public boolean delete(Long id) {
return tasks.remove(id) != null;
}
}
@Service is a @Component under a more specific name — same component
scanning from Part 8 picks it up, the annotation just documents intent for
whoever reads the class next. ConcurrentHashMap and AtomicLong instead
of a plain HashMap and a hand-rolled counter aren't paranoia: Spring MVC
handles each request on its own thread by default, and two POSTs arriving
close together on a plain HashMap will corrupt it under load in a way
that's miserable to reproduce later. It costs nothing to get this right
now, before you have a reason to remember it.
Notice what this class returns for the failure cases: Optional<Task> for
"might not exist," a boolean for "did the delete do anything." Nothing
here throws, and nothing here knows what an HTTP status code is — that's
deliberate. TaskService would work identically wired up to a CLI tool or
a test harness with no HttpServletRequest in sight. Whether "not found"
becomes a 404 is the controller's decision, not the service's, which is
exactly the boundary from the layers diagram above holding in real code.
The controller
package dev.josealencar.tasktracker;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
private final TaskService taskService;
public TaskController(TaskService taskService) {
this.taskService = taskService;
}
@GetMapping
public List<Task> listTasks() {
return taskService.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<Task> getTask(@PathVariable Long id) {
return taskService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<Task> createTask(@RequestBody CreateTaskRequest request) {
Task created = taskService.create(request);
return ResponseEntity.status(201).body(created);
}
@PutMapping("/{id}")
public ResponseEntity<Task> updateTask(@PathVariable Long id,
@RequestBody UpdateTaskRequest request) {
return taskService.update(id, request)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteTask(@PathVariable Long id) {
return taskService.delete(id)
? ResponseEntity.noContent().build()
: ResponseEntity.notFound().build();
}
}
A few things worth calling out that are easy to skim past:
@RequestMapping("/api/tasks") on the class hoists the shared path prefix
out of every method — @GetMapping with no argument means "the class-level
path, GET," and @GetMapping("/{id}") means "the class-level path plus
/{id}." Part 8's controller didn't need this because it had one method.
The constructor taking a TaskService and assigning it to a field is
constructor injection, and it's not boilerplate you're stuck writing by
hand forever — Lombok's @RequiredArgsConstructor generates exactly this
once you bring it in, which most real projects do. Worth typing out once
so you know what that annotation is doing for you later. Spring sees the
constructor, sees there's exactly one, and supplies a TaskService from
the container automatically — no @Autowired needed on a single
constructor since Spring 4.3.
@PathVariable Long id pulls the {id} segment out of the URL and converts
it to a Long for you. @RequestBody CreateTaskRequest request does the
reverse of what Part 8's List<Task> return value did — Jackson deserializes
the incoming JSON body straight into the record, matching fields by name.
ResponseEntity<T> is the type that lets a method control the status code
instead of always returning 200. Every method above returns one for exactly
that reason.
Status codes, chosen on purpose
This is the part of a REST API that's easiest to get lazily wrong — return
200 for everything and let the body's shape imply success or failure. It
works until something else consumes your API (a frontend, a CI script, a
monitoring check) and has to if (response.ok) to find out what happened
without parsing the body first. Here's the table this controller
implements and why:
| Endpoint | Success | Not found | Notes |
|---|---|---|---|
GET /api/tasks | 200 OK | — | Always succeeds; empty list if nothing exists |
GET /api/tasks/{id} | 200 OK | 404 Not Found | |
POST /api/tasks | 201 Created | — | Not 200 — a new resource now exists |
PUT /api/tasks/{id} | 200 OK | 404 Not Found | |
DELETE /api/tasks/{id} | 204 No Content | 404 Not Found | No body on success — nothing to return |
201 versus 200 on create is the one people most often skip, and it's
not pedantry — a 201 is what tells a well-behaved HTTP client "a new
resource exists now, and here it is in the body," which matters to caching
layers and to anyone consuming your API who bothered to read the spec.
204 on delete for the same reason: there's no task left to describe, so
sending an empty 200 body is just a 204 with extra steps. None of this
requires a library — it's ResponseEntity.status(...), chosen deliberately
per outcome, which is the whole idea.
Trying it end to end
Restart the app (./mvnw spring-boot:run) and run through the full cycle:
curl -X POST http://localhost:8080/api/tasks \
-H "Content-Type: application/json" \
-d '{"title":"Write Part 9"}'
# 201 Created
# {"id":1,"title":"Write Part 9","done":false}
curl http://localhost:8080/api/tasks/1
# 200 OK
# {"id":1,"title":"Write Part 9","done":false}
curl -X PUT http://localhost:8080/api/tasks/1 \
-H "Content-Type: application/json" \
-d '{"title":"Write Part 9","done":true}'
# 200 OK
# {"id":1,"title":"Write Part 9","done":true}
curl -X DELETE http://localhost:8080/api/tasks/1
# 204 No Content
curl http://localhost:8080/api/tasks/1
# 404 Not Found
That's a real CRUD API — the kind of shape most backend work actually looks
like day to day, minus the database. It also has an honest limitation
that's easy to forget once the demo works: restart the app and everything
above is gone, because ConcurrentHashMap lives in process memory and
nowhere else. That's not a bug to fix in this post — it's exactly the gap
Part 10 closes, swapping TaskService's hand-rolled Map for a Spring
Data JPA repository backed by a real database, without TaskController
changing at all. That "without the controller changing" part is the payoff
for drawing the layer boundaries carefully now, before a database was
forcing the issue.
If this shape — one controller, one service, DTOs at the edge — starts feeling small once an API grows past a handful of endpoints with real authorization rules and cross-resource validation, that's a fair reaction. It's a deeper topic than a beginner series can cover in one post, but worth knowing it exists as its own subject once you're past the fundamentals here.