Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 119 ยท Projects

Project: A REST API from Scratch

Build a complete JSON task API in plain Java - layered design, H2 repository, validation, problem details, pagination, PATCH, an HttpClient script and JUnit tests.

In Building a REST API with the JDK you learned how a router, JSON parsing and status codes fit together, with books stored in a map. In this project you will build the kind of API a real team ships: a task tracker with a database behind it, a clean layered design, validation that reports every problem at once, standard error responses, paging and sorting, partial updates with PATCH, and an automated test suite.

You will build it with nothing but the JDK, Jackson and H2: com.sun.net.httpserver.HttpServer for HTTP, Jackson for JSON, JDBC for storage, and JUnit for tests. That is deliberate. In the next project, Project: Task API with Spring Boot, you will rebuild the same API with Spring Boot, and you will know exactly what each annotation replaces.

The project has three stages, plus a short experiment with the JSON layer. Each stage is a complete program that includes all the code from before, because every run starts fresh. You should be comfortable with REST API Design, JSON with Jackson and The DAO and Repository Patterns.

The API contract

Design the contract first, the way you would before any client team starts work. A task has an id, a title, a status (TODO, IN_PROGRESS or DONE), a priority (LOW, MEDIUM or HIGH) and an optional dueDate.

Request Meaning Success Errors
GET /tasks?status=&sort=&page=&size= List tasks, filtered, sorted, paged 200 + page object 400 bad parameter
GET /tasks/{id} Read one task 200 + task 400, 404
POST /tasks Create a task 201 + task + Location 400, 415
PUT /tasks/{id} Replace a task 200 + task 400, 404, 409, 415
PATCH /tasks/{id} Change some fields 200 + task 400, 404, 409, 415
DELETE /tasks/{id} Delete a task 204 404

The business rules:

  • title is required, trimmed, and at most 100 characters.
  • status defaults to TODO and priority to MEDIUM when the client leaves them out.
  • A new task's dueDate can't be in the past.
  • A task that is DONE is final: changing it returns 409 Conflict.

Every error uses the problem details format from RFC 9457, with the content type application/problem+json. Validation errors add an errors array that lists each invalid field:

JSON
{
  "type": "about:blank",
  "title": "Bad Request",
  "status": 400,
  "detail": "The task has 2 invalid fields",
  "instance": "/tasks",
  "errors": [
    {"field": "title", "message": "must not be blank"},
    {"field": "dueDate", "message": "must not be in the past"}
  ]
}

The architecture

The code is split into three layers. Each one has a single job and only talks to the layer below it:

Layer Classes Responsibility Knows nothing about
HTTP (web) Router, TaskController, Problem URLs, methods, status codes, JSON, query parameters SQL
Service TaskService Validation, defaults, business rules HTTP, JSON, SQL
Repository TaskRepository, JdbcTaskRepository SQL and row mapping HTTP, business rules

The service reports problems with domain exceptions: TaskNotFoundException, ValidationException and ConflictException. It doesn't know that "not found" becomes 404; that translation happens in one place in the web layer. The payoff is that the same service could sit behind a command-line tool or a message consumer without changes, and that you can test every rule without starting a server. Layered Architecture discusses this structure in general.

Stage 1: the domain, repository and service

Start at the bottom, with no HTTP at all. The domain types are records and enums. TaskInput is what clients may send: it has no id, and its fields may be null so the service can apply defaults and report missing values. TaskQuery describes a list request, and Page is what a list request returns.

JdbcTaskRepository stores tasks in one H2 table. Status and priority are stored as their enum names, with CHECK constraints as a safety net. Two details in find are worth slowing down for:

  • Sorting is type-safe. Clients send sort=priority, but the repository never puts that string into SQL. The web layer turns it into a SortField enum, and the repository maps each enum constant to a fixed SQL expression. A column name can't be a ? parameter, so whitelisting like this is the only safe way to make ORDER BY dynamic (see PreparedStatement and SQL Injection).
  • Priority needs a custom order. Sorting the text column alphabetically gives HIGH, LOW, MEDIUM. A CASE expression maps LOW, MEDIUM and HIGH to 1, 2, 3 so the order matches the meaning, and sort=-priority (descending) puts the most important tasks first.

Paging uses OFFSET ? ROWS FETCH NEXT ? ROWS ONLY, which is standard SQL, plus a COUNT(*) with the same filter so clients know how many pages exist. Every sort ends with id as a tie-breaker. Without it, rows with equal values can come back in a different order on each request, and a task could appear on two pages or on none.

The service validates input, applies defaults, enforces the "done is final" rule, and translates "no row" into TaskNotFoundException. It receives a Clock so that "today" is fixed in demos and tests (the demo uses March 16, 2026).

Java Stage 1: domain, JDBC repository and service

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 a few lines of the output. Task 2's title was trimmed and it got the default status and priority. The invalid task reports both problems in one exception, so a client can fix everything in one round trip. Sorting by priority, descending, puts the two HIGH tasks first (in id order, thanks to the tie-breaker), and sorting by due date descending puts the task without a due date last, because of NULLS LAST. Task 1 can be completed, but once it is DONE, the attempt to reopen it is refused.

The service's replace reads the task, checks the rule, then writes. Two requests arriving at the same moment could both pass the check. For this API that is acceptable: the worst case is that an edit lands just as someone completes the task. When it is not acceptable, add a version column and update with WHERE id = ? AND version = ? (optimistic locking), which is what JPA's @Version does; see Entity Lifecycle and Transactions.

A closer look at the JSON contract

Before writing the web layer, it pays to know exactly how Jackson will treat the domain types, because that behavior is the API contract. A short experiment answers the questions that matter:

  • How are LocalDate and enums written? With JavaTimeModule registered and WRITE_DATES_AS_TIMESTAMPS disabled, a date becomes "2026-03-20" (ISO-8601). Enums become their names.
  • What happens with an unknown field such as "id" or a typo like "tittle"? Jackson throws UnrecognizedPropertyException. That's a good default for input: a typo becomes a clear error instead of a silently ignored field.
  • What happens with an invalid value such as "status": "LATER" or "dueDate": "2026-02-30"? Jackson throws a JsonMappingException whose path names the field. The web layer will use that path to build a helpful message without leaking Java class names like Main$Status to clients.
  • How should PATCH work? The experiment uses the JSON Merge Patch idea (RFC 7386): turn the current task into a JSON object, copy the fields from the request on top of it, and convert the result back. A field that is absent stays unchanged; a field set to null is cleared. That distinction, "missing" versus "null", is impossible to see once JSON has been mapped to a record, which is why the merge happens on the JSON tree.
Java Experiment: how Jackson maps the task types

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.

Every bad input is rejected with a message that names the field and nothing else. Note the order of the catch blocks: UnrecognizedPropertyException is a subclass of JsonMappingException, which is a subclass of JsonProcessingException, so the most specific one must come first. Invalid dates are rejected too: February 30 doesn't exist, and the java.time parser refuses it. The deeper Jackson features used here are covered in Advanced Jackson.

Stage 2: the HTTP layer

Now put the service on the network. The web layer has four parts:

  1. Router, the method-and-path router from Building a REST API with the JDK. It answers 404 for unknown paths and 405 with an Allow header for wrong methods.
  2. Request helpers: the numeric path parameter, query parameters, and the JSON body. The body is accepted only with Content-Type: application/json (otherwise 415), and Jackson errors are turned into 400 responses exactly as in the experiment.
  3. TaskController, which registers one small handler per route. Each handler parses the request, calls one service method and wraps the result in a Response. There are no business rules here.
  4. Exception mapping, one method that turns every exception into a Problem: TaskNotFoundException becomes 404, ValidationException 400 with the errors array, ConflictException 409, and anything unexpected a generic 500 whose details go only to the server log.

The list endpoint parses status, sort, page and size and rejects bad values with a 400 instead of silently using a default. A client that sends size=500 gets told the maximum is 50; a client that sends sort=-priority gets descending priority. The response is the Page record, so clients see totalItems and totalPages next to the items.

The program finishes with a client script: a sequence of HttpClient calls that exercises every route and prints each response. Real projects keep scripts like this (or .http files for the IDE) to try an API by hand.

Java Stage 2: the complete HTTP API with a client script

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.

Go through the output and connect each response to the code that produced it:

  • Each POST returns 201 with a Location header, and the body shows the defaults the service applied.
  • GET /tasks?sort=-priority&size=2 returns the first page of two, highest priority first, with "totalItems":3,"totalPages":2 so a client knows to ask for page 2.
  • The PATCH changes the priority, clears the due date because it was sent as null, and leaves the title and status untouched because they were absent.
  • After PUT marks task 1 as DONE and task 3 is deleted with 204, the filter status=done (case-insensitive) finds exactly one task.
  • The invalid task gets one 400 problem with both field errors. The unknown status SOMEDAY is rejected by name without leaking a Java class name. Reopening the finished task is a 409, the deleted task is a 404, and an oversized page is a 400 that tells the client the limit.

Every error has the same shape, application/problem+json with type, title, status, detail and instance. A client needs one error handler for the whole API.

The router maps exceptions in a switch with type patterns (case TaskNotFoundException notFound -> ...), a Java 21 feature covered in Pattern Matching. In Spring Boot, the same mapping is a class annotated with @RestControllerAdvice with one @ExceptionHandler method per exception type.

Stage 3: automated tests

The client script is a manual check: you read the output and decide whether it looks right. Automated tests make that judgment repeatable. This project uses two kinds, which match the layers:

  • TaskServiceTest tests the business rules through the service alone, with an InMemoryTaskRepository fake instead of H2. These tests don't touch HTTP or SQL, so they run in microseconds and fail only when a rule breaks. The fake works because the service depends on the TaskRepository interface, not on the JDBC class; see Test Doubles and Mockito.
  • TaskApiTest starts the real server with a fresh H2 database before each test and sends real HTTP requests. These tests check what the unit tests can't: routing, status codes, headers, JSON mapping, the SQL in the repository, and the problem format. A small send helper and Jackson's tree model (JsonNode) keep the assertions short.

Each TaskApiTest test gets its own database (tasks-test-1, tasks-test-2, ...) and its own server on a random free port, so tests are independent and can run in any order. Starting both takes a few milliseconds.

Java Stage 3: unit and API tests with JUnit

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.

All twelve tests pass. The two suites have different jobs. If you break the trimming in validate, only TaskServiceTest fails, and it points straight at the rule. If you break the router's Allow header or the CASE expression for priority order, only TaskApiTest catches it. A healthy project has many fast unit tests and fewer, broader integration tests, the shape known as the test pyramid (Integration Testing).

Notice that TaskApiTest checks JSON with JsonNode instead of mapping responses back to Task. That is intentional: the test should verify what a client sees on the wire, including field names and the date format. Deserializing into the server's own record would hide a renamed field, because the test and the server would change together.

Design decisions in review

Decision Choice here Alternative and trade-off
Error format RFC 9457 problem details everywhere A custom shape is simpler but every client must learn it
Exception mapping Domain exceptions, mapped in one router method Throwing HTTP status codes from the service ties it to HTTP
Validation Service collects all field errors Failing on the first error forces clients into many round trips
Sorting Enum whitelist mapped to fixed SQL Passing the column name through invites SQL injection
Paging Page number and size, plus totals Cursor paging scales better for huge, fast-changing tables
PATCH JSON merge on the tree, then the normal replace path A separate patch path would duplicate validation
Unknown fields Rejected Ignoring them helps old servers accept newer clients, but hides typos
Concurrency Read, check, write; last write wins Optimistic locking with a version column and If-Match

Ideas for extending the project

  • Optimistic locking with ETags. Add a version column, return it as an ETag header, require If-Match on PUT/PATCH, and answer 412 Precondition Failed when it doesn't match. REST API Design shows the pattern.
  • Search. Add q= to the list endpoint, matching titles with LIKE and escaped wildcards.
  • Projects or tags. Add a project table and nested routes like GET /projects/{id}/tasks, with a foreign key and a 404 for unknown projects.
  • Authentication. Require an Authorization: Bearer token checked in a filter before the router runs; see Web Security Basics and JWT and OAuth 2.
  • Idempotent creation. Accept an Idempotency-Key header on POST so that retried requests don't create duplicate tasks.
  • Cursor pagination. Replace page with an opaque cursor based on the last seen (sort value, id).
  • Graceful shutdown and logging. Log one line per request with method, path, status and duration, using java.util.logging or SLF4J.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client sends PATCH /tasks/2 with {"dueDate": null}. What happens to task 2?

    The patch is merged onto the current task as a JSON tree. Absent fields keep their values; a field explicitly set to null is cleared.
  2. 2. Why does TaskService throw TaskNotFoundException instead of an exception carrying status 404?

    Domain exceptions keep the business layer independent of the transport. The router's toProblem method is the only code that knows the mapping.
  3. 3. The repository builds ORDER BY from a SortField enum instead of the raw sort query parameter. What does that prevent?

    Column names and expressions can't be bound as parameters, so the only safe way is a whitelist that maps known values to fixed SQL.
  4. 4. Why does every sort end with ", id"?

    OFFSET-based paging only works when the order is fully deterministic. Adding the primary key as the last sort key guarantees that.
  5. 5. In TaskApiTest, why are responses checked as JsonNode rather than mapped back to the Task record?

    A contract test should look at the wire format. If the server and the test share the same record, a rename changes both and the test still passes.

Summary

  • Design the contract first: resources, methods, status codes, rules and one error format (RFC 9457 problem details).
  • Split the code into web, service and repository layers. The service throws domain exceptions; one method in the web layer maps them to HTTP responses.
  • The repository owns SQL: parameters for values, an enum whitelist for ORDER BY, a CASE for meaningful enum order, a unique tie-breaker for stable paging, and a COUNT(*) for totals.
  • Configure Jackson deliberately: ISO dates, enums by name, unknown fields rejected, and error messages built from the exception's field path.
  • Implement PATCH as a JSON merge onto the current state, then reuse the normal validation path; absent means unchanged, null means clear.
  • Test business rules with fast unit tests and a fake repository, and the HTTP contract with API tests against a real server and a fresh database per test.

Next: Project: Task API with Spring Boot rebuilds this exact API with Spring Boot, Spring Data JPA and Bean Validation, and maps every annotation to the code you wrote here.