A REST API with Spring Boot: the Tasks application

Lesson 2 of 3 · Spring Boot

A REST API is a set of addresses through which another application reads and changes data on the server. In this lesson you make an API for a list of school tasks (adding, viewing, marking as done, deleting), split the code into a controller and a service, and make a simple page that uses the API.

Before you start: what you need to know first – Spring Boot – the first application, exceptions.
How to learn: work in your own project step by step, and after each step start the server and check the result in the browser. The examples are for Spring Boot 3 or 4 and Java 17+; type each piece of code into the file named in the comment at the top of the example.

REST: resources and HTTP methods

In the REST style, data are resources with their own addresses (/api/tasks, /api/tasks/3), and the kind of action is decided by the HTTP method:

Method and addressActionResponse (status)
GET /api/tasksa list of all tasks200 OK + JSON array
GET /api/tasks/3one task200 OK, or 404 Not Found
POST /api/tasksa new task (the data in the request body, JSON)201 Created
PUT /api/tasks/3changing a task200 OK, or 404
DELETE /api/tasks/3deleting204 No Content, or 404

The status is a three-digit number that says how the request went: 2xx – success, 4xx – a client error (a wrong request, does not exist), 5xx – an error on the server.

The model: the Task class

// src/main/java/rs/svetprogramiranja/tasks/Task.java
package rs.svetprogramiranja.tasks;

import java.time.LocalDate;

public class Task {
    private Long id;
    private String title;
    private String subject;
    private LocalDate dueDate;      // in JSON: "2026-11-20"
    private boolean done;

    public Task() { }               // empty constructor – needed for converting from JSON

    public Task(String title, String subject, LocalDate dueDate) {
        this.title = title;
        this.subject = subject;
        this.dueDate = dueDate;
    }

    // getters and setters – Spring reads and writes the fields in JSON through them
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getSubject() { return subject; }
    public void setSubject(String subject) { this.subject = subject; }
    public LocalDate getDueDate() { return dueDate; }
    public void setDueDate(LocalDate dueDate) { this.dueDate = dueDate; }
    public boolean isDone() { return done; }
    public void setDone(boolean done) { this.done = done; }
}

Here it is an ordinary class (not a record) because the fields will change, and in the next lesson the same class becomes a table in the database.

The service: logic and data

The controller should only receive the request and return the response. The actual work (storing, searching, rules) is done by a service – a class marked with @Service. For now the tasks are kept in a map in memory (they disappear when the server stops):

// src/main/java/rs/svetprogramiranja/tasks/TaskService.java
package rs.svetprogramiranja.tasks;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;

@Service
public class TaskService {
    // the server handles several requests at the same time – so the map and the counter are thread-safe
    private final Map<Long, Task> tasks = new ConcurrentHashMap<>();
    private final AtomicLong nextId = new AtomicLong(1);

    public TaskService() {
        // a few examples so that the list is not empty
        save(new Task("Do exercises 1-5", "Maths", LocalDate.now().plusDays(2)));
        save(new Task("Read the set book", "English", LocalDate.now().plusDays(7)));
    }

    private Task save(Task t) {
        t.setId(nextId.getAndIncrement());          // a new task gets the next number
        tasks.put(t.getId(), t);
        return t;
    }

    public List<Task> all() {
        List<Task> list = new ArrayList<>(tasks.values());
        // the nearest due date first; tasks without a due date (dueDate == null) go to the end
        list.sort(Comparator.comparing(Task::getDueDate, Comparator.nullsLast(Comparator.naturalOrder())));
        return list;
    }

    public Optional<Task> find(long id) {
        return Optional.ofNullable(tasks.get(id));
    }

    public Task add(Task t) {
        return save(t);
    }

    public Optional<Task> update(long id, Task changed) {
        Task t = tasks.get(id);
        if (t == null) return Optional.empty();
        t.setTitle(changed.getTitle());
        t.setSubject(changed.getSubject());
        t.setDueDate(changed.getDueDate());
        t.setDone(changed.isDone());
        return Optional.of(t);
    }

    public boolean delete(long id) {
        return tasks.remove(id) != null;
    }
}

The controller and dependency injection

The controller gets the service through its constructor – this is dependency injection: Spring itself creates one service object and hands it to everyone who needs it. @RequestMapping("/api/tasks") on the class sets the beginning of the address for all methods.

// src/main/java/rs/svetprogramiranja/tasks/TaskController.java
package rs.svetprogramiranja.tasks;

import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/tasks")
public class TaskController {
    private final TaskService service;

    public TaskController(TaskService service) {   // Spring injects the service
        this.service = service;
    }

    @GetMapping
    public List<Task> all() {
        return service.all();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Task> one(@PathVariable long id) {
        return service.find(id)
                .map(ResponseEntity::ok)                    // 200 + the task
                .orElse(ResponseEntity.notFound().build()); // 404
    }

    @PostMapping
    public ResponseEntity<Task> add(@RequestBody Task t) {   // JSON from the request body -> an object
        if (t.getTitle() == null || t.getTitle().isBlank())
            return ResponseEntity.badRequest().build();     // 400
        return ResponseEntity.status(HttpStatus.CREATED).body(service.add(t));   // 201
    }

    @PutMapping("/{id}")
    public ResponseEntity<Task> update(@PathVariable long id, @RequestBody Task t) {
        return service.update(id, t)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable long id) {
        return service.delete(id)
                ? ResponseEntity.noContent().build()        // 204
                : ResponseEntity.notFound().build();
    }
}

ResponseEntity lets you return the exact status together with the data. The map and orElse methods are the same as with Optional in the lesson Lambda expressions and the Stream API.

Trying out the API: curl

You can open GET requests in the browser, but POST, PUT and DELETE are sent by a program. The simplest one is curl, which also exists in Windows (commands for cmd; quotes inside JSON are written as \"):

curl http://localhost:8080/api/tasks

curl -X POST http://localhost:8080/api/tasks -H "Content-Type: application/json" -d "{\"title\":\"Report on Tesla\",\"subject\":\"Physics\",\"dueDate\":\"2026-11-25\"}"

curl -X PUT http://localhost:8080/api/tasks/3 -H "Content-Type: application/json" -d "{\"title\":\"Report on Tesla\",\"subject\":\"Physics\",\"dueDate\":\"2026-11-25\",\"done\":true}"

curl -i -X DELETE http://localhost:8080/api/tasks/1

curl -i http://localhost:8080/api/tasks/99

The -i option also shows the response status (e.g. HTTP/1.1 404). Graphical tools such as Postman or Bruno, or the HTTP client built into IntelliJ IDEA (a .http file), are more comfortable.

A page that uses the API

The page in static/index.html reads the list and sends new tasks with fetch:

<!-- src/main/resources/static/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Tasks</title>
  <style>
    body { font-family: sans-serif; max-width: 640px; margin: 2rem auto; }
    li.done span { text-decoration: line-through; color: gray; }
    li button { margin-left: .5rem; }
  </style>
</head>
<body>
  <h1>My tasks</h1>
  <form id="form">
    <input id="title" placeholder="Task" required>
    <input id="subject" placeholder="Subject">
    <input id="dueDate" type="date" required>
    <button>Add</button>
  </form>
  <ul id="list"></ul>

  <script>
    const API = "/api/tasks";

    async function load() {
      const tasks = await (await fetch(API)).json();
      const ul = document.getElementById("list");
      ul.innerHTML = "";
      for (const t of tasks) {
        const li = document.createElement("li");
        if (t.done) li.className = "done";
        const text = document.createElement("span");
        text.textContent = `${t.dueDate} – ${t.subject}: ${t.title}`;   // textContent: no HTML injection
        const doneButton = document.createElement("button");
        doneButton.textContent = t.done ? "Undo" : "Done";
        doneButton.onclick = async () => {
          t.done = !t.done;
          await fetch(`${API}/${t.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(t) });
          load();
        };
        const deleteButton = document.createElement("button");
        deleteButton.textContent = "Delete";
        deleteButton.onclick = async () => { await fetch(`${API}/${t.id}`, { method: "DELETE" }); load(); };
        li.append(text, doneButton, deleteButton);
        ul.appendChild(li);
      }
    }

    document.getElementById("form").onsubmit = async (e) => {
      e.preventDefault();                           // do not send the form the old way
      const newTask = {
        title: document.getElementById("title").value,
        subject: document.getElementById("subject").value,
        dueDate: document.getElementById("dueDate").value
      };
      await fetch(API, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newTask) });
      e.target.reset();
      load();
    };

    load();
  </script>
</body>
</html>

For now the tasks disappear when the server is restarted. In the next lesson they are stored in a database.

Practice tasks

Each task has a hint and a solution.

TASK 01Difficulty: medium

Filtering and statistics

Extend the API:

  • GET /api/tasks?subject=Physics returns only the tasks from that subject (regardless of upper and lower case); without the parameter it returns all of them;
  • GET /api/tasks/statistics returns JSON of the form {"total":5,"done":2,"late":1}, where "late" are the tasks not done whose due date has passed.
Common mistakes and tips
  • The route /statistics and the route /{id} do not clash: Spring first chooses the exact path, and only then a pattern with a variable.
  • For POST and PUT the request must have the header Content-Type: application/json, otherwise the server returns error 415.
  • A class that is received from JSON must have an empty constructor and setters (or be a record).
  • Do not show text from the database or from users with innerHTML – use textContent, so that nobody can inject their own HTML or JavaScript.

Check your knowledge

Open the quiz

REST API

1. Which HTTP method is used to add a new task?




2. What does status 404 mean?




3. What is @RequestBody used for?




4. How does the controller get the service object?