Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 119 ยท Web Fundamentals

Building a REST API with the JDK

Build a JSON CRUD REST API in plain Java - HttpServer, Jackson, an in-memory store, routing by method and path, status codes, validation and JUnit tests.

Frameworks like Spring Boot let you build a REST API with a few annotations. That is wonderful for productivity, but it hides the moving parts: how a URL finds the right method, where the JSON gets parsed, who picks the status code, and what happens when the body is invalid. In this lesson you will build all of those parts yourself, in plain Java, with no framework at all.

The result is a small but complete API for a book catalog: list, filter, read, create, replace and delete books, with proper status codes, JSON error messages and input validation. You will use the JDK's built-in com.sun.net.httpserver.HttpServer, Jackson for JSON, and an in-memory store, then test the API with HttpClient and JUnit. Later, when you meet @RestController in Building REST APIs with Spring Boot, you will recognize every piece. You should be comfortable with How HTTP Works and JSON with Jackson before you start.

The API we are building

A REST API exposes resources (here: books) at URLs and uses HTTP methods to act on them. This is the contract:

Method and path Action Success Typical errors
GET /books List books, optional ?author= filter 200 + array
GET /books/{id} Read one book 200 + book 400 bad id, 404
POST /books Create a book 201 + book + Location 400 invalid, 415 not JSON
PUT /books/{id} Replace a book 200 + book 400, 404, 415
DELETE /books/{id} Delete a book 204, no body 404
anything else 404 unknown path, 405 wrong method

Every error response has the same JSON shape, {"status": 404, "error": "Book 7 not found"}, so clients can handle errors in one place. REST API Design discusses these choices in depth, including the standard "problem details" format.

HttpServer in one minute

HttpServer is part of the JDK (module jdk.httpserver). It is small and fast enough for tools, tests and simple services, and it is what the examples in this chapter use because it runs anywhere. The core API:

  • HttpServer.create(address, backlog) creates the server; start() and stop(delaySeconds) control it.
  • createContext(path, handler) registers an HttpHandler for a path prefix. The context with the longest matching prefix wins, so a context for "/" receives everything that no other context claims.
  • setExecutor(executor) decides which threads run handlers. The default is a single thread, so set an executor; a virtual-thread-per-task executor is ideal for I/O-heavy handlers.
  • Inside a handler, HttpExchange gives you the method, URI, request headers and body, and lets you set response headers, call sendResponseHeaders(status, length) and write the body.

HttpServer knows nothing about JSON, path parameters or routing beyond prefixes. That is the job of the code you are about to write.

Step 1: a router

A router maps a method plus a path pattern such as /books/{id} to a handler. Ours turns each pattern into a regular expression, captures the placeholders as path parameters, and produces the two "no match" answers correctly: 404 when no route has this path, and 405 with an Allow header when the path exists but not for this method.

Handlers return a small Response record, and the router writes it as JSON. Exceptions of type ApiException become error responses with their status code; anything else becomes a 500, and its details stay in the server log instead of leaking to the client.

Java Step 1: routing by method and path

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 the last line of output: the handler crashed with a message containing a "password", but the client only sees a generic 500. The details went to standard error (the server log), where developers can read them. Never send stack traces or exception messages from unexpected errors to clients; they reveal internals that help attackers.

A few design notes:

  • try (exchange) closes the exchange on every path. HttpExchange implements AutoCloseable, and forgetting to close it leaks the connection.
  • Route order matters only when patterns overlap. With a literal route like /books/search next to /books/{id}, register the literal one first.
  • Handlers are lambdas with the signature Request -> Response. That is the same idea as Spring's controller methods, minus the annotations and reflection.

Step 2: the complete CRUD API

Now add the domain. A Book record is what we store and return. A separate BookInput record is what clients send: it has no id (the server assigns ids) and uses Integer for year, so a missing year arrives as null and can be reported instead of silently becoming 0. Separating input and output types is the same DTO idea you will meet again in Layered Architecture.

The BookStore keeps books in a ConcurrentSkipListMap (thread-safe and sorted by id) and hands out ids from an AtomicLong, because the virtual-thread executor runs requests concurrently. The Request record gains three helpers: a numeric path parameter, a decoded query parameter, and a JSON body that is accepted only with Content-Type: application/json.

Java Step 2: a JSON CRUD API for books

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.

Walk through the output and match each line to the code:

  • The three POST requests return 201 Created with a Location header and the stored book, including its new id. The client never chooses ids.
  • The filter ?author=ursula+k.+le+guin is decoded and compared case-insensitively, so both Le Guin books come back.
  • PUT /books/2 replaces the whole book (fixing the year) and returns it. PUT means "make the resource look exactly like this", so a missing field would be a validation error, not "leave unchanged". Partial updates are what PATCH is for.
  • DELETE returns 204 No Content, and a later GET of the same id is a 404 with a JSON error body.
  • The invalid book collects all problems in one 400 message, so the client can fix everything at once.
  • Sending an id fails with Unrecognized field "id": Jackson rejects unknown properties by default. That is a good default for input DTOs, because a typo like "autor" becomes an error instead of silently being ignored. Public APIs that must tolerate newer clients sometimes disable it with @JsonIgnoreProperties(ignoreUnknown = true).
  • A text/plain body gets 415 Unsupported Media Type, a bad id gets 400, and PATCH gets 405 with Allow: DELETE, GET, PUT.

Validation here is hand-written to show the idea. Real applications usually declare constraints with Jakarta Bean Validation (@NotBlank, @Min) and let the framework produce the error response; see Validation and Error Handling.

Step 3: automated tests

A manual client script proves the API works today. Automated tests prove it still works after the next change. Because the whole server starts in a few milliseconds, you can run real HTTP requests in JUnit tests. Each test class starts a server on a free port in @BeforeAll and stops it in @AfterAll. (The launcher code at the bottom runs the tests inside this page; in a project, Maven or Gradle does that. See Unit Testing with JUnit 6.)

The last test sends 50 POST requests at the same time from virtual threads and checks that every book got a unique id. It would fail with a plain HashMap and a non-atomic long counter.

Java Step 3: testing the API with JUnit and HttpClient

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 six tests pass. To see the concurrency test do its job, replace ConcurrentSkipListMap with TreeMap and AtomicLong with a plain counter, and run it a few times: you will see lost books, duplicate ids or even exceptions from the corrupted map. Tests like these are integration tests: they exercise the real HTTP layer, JSON mapping and storage together. Integration Testing covers the technique more broadly.

What a framework adds

You now have, in about 200 lines, the core of what a web framework does. Here is how each piece maps to Spring Boot:

Your code Spring Boot
HttpServer + virtual-thread executor Embedded Tomcat (or Jetty), virtual threads with one property
Router.route("GET", "/books/{id}", ...) @GetMapping("/books/{id}") on a @RestController method
req.idParam("id"), req.query("author") @PathVariable long id, @RequestParam Optional<String> author
req.body(BookInput.class) with 415 check @RequestBody BookInput input (content negotiation built in)
Response.created(location, book) ResponseEntity.created(uri).body(book)
ApiException caught by the router @ExceptionHandler / @ControllerAdvice returning ProblemDetail
BookInput.toBook validation @Valid with @NotBlank, @Min annotations

A framework also gives you things that would take much longer to write well: HTTPS, compression, request size limits, security filters, metrics, OpenAPI documentation and graceful shutdown. That is why production services use one. But when a Spring endpoint misbehaves, you now know what is happening underneath. The JDK server remains handy for test doubles of remote APIs, small internal tools, and demos like this one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The router has routes GET /books/{id} and DELETE /books/{id}. What does PUT /books/5 return?

    The path matches two routes, but neither for PUT. The correct answer is 405, and the Allow header lists the methods that do exist.
  2. 2. Why does the API use a separate BookInput record instead of accepting Book directly in POST?

    The input DTO contains only what the client may send. With an int year, a missing field would silently become 0.
  3. 3. A handler throws a NullPointerException. What does the client receive?

    The router turns unexpected exceptions into a generic 500 and logs the details server-side. Leaking internals to clients is a security risk.
  4. 4. Why does the BookStore use ConcurrentSkipListMap and AtomicLong?

    With a multi-threaded executor, several handlers modify the store at the same time. The concurrency test with 50 parallel POSTs proves the store is safe.
  5. 5. A client sends PUT /books/2 with only {"title": "New title"}. In this API, what happens?

    PUT sends the complete new state. Missing required fields are validation errors. Partial updates belong to PATCH.

Summary

  • HttpServer provides connections, prefix-based contexts and an executor; routing, JSON and validation are up to you. Set an executor (virtual threads work well) and close every HttpExchange.
  • A router maps method + path pattern to a handler, extracts path parameters, and answers 404 for unknown paths and 405 with Allow for wrong methods.
  • Use correct statuses: 200 for reads and updates, 201 with Location for creates, 204 for deletes, 400 for invalid input, 404 for missing resources, 415 for wrong content types, 500 for bugs (with no internal details).
  • Keep a single error shape such as {"status": ..., "error": ...} for every failure.
  • Separate input DTOs from stored entities, validate all fields at once, and let Jackson reject unknown properties.
  • Shared state must be thread-safe: concurrent maps and atomic counters.
  • Test the API end to end with JUnit and HttpClient, including concurrent requests.
  • Spring Boot automates exactly these pieces with annotations and adds production features on top.

Next: REST API Design looks at the decisions behind an API like this one: URLs, status codes, pagination, versioning, idempotency and standard error formats.