Tutorials / Java: From Zero to Advanced / A small REST service with the JDK HTTP server

A small REST service with the JDK HTTP server

17 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

What REST means in practice

A REST service exposes resources through URLs and uses HTTP methods to act on them. A todo list is a good example. GET /todos lists them, POST /todos creates one, GET /todos/3 reads one, and DELETE /todos/3 removes it. The response carries a status code that tells the client what happened: 200 for success, 201 for created, 204 for no content, 404 for not found. The body is usually JSON.

In real projects you will almost always use a framework such as Spring Boot, Quarkus, Micronaut or Javalin. They handle routing, JSON conversion, validation and security for you. But a framework hides what happens underneath, and that is hard to appreciate when you start. The JDK ships with a simple HTTP server in the package com.sun.net.httpserver, and a modern HTTP client in java.net.http. We use both to build and test a tiny service in a single file, with no dependencies.

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class Main {

    record Todo(int id, String title) {
        String toJson() {
            return "{\"id\":" + id + ",\"title\":\"" + escape(title) + "\"}";
        }
    }

    static final List<Todo> TODOS = new CopyOnWriteArrayList<>();
    static final AtomicInteger NEXT_ID = new AtomicInteger(1);

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/todos", Main::handle);
        server.start();
        String base = "http://localhost:" + server.getAddress().getPort();
        System.out.println("Server listening on " + base);

        HttpClient client = HttpClient.newHttpClient();

        call(client, HttpRequest.newBuilder(URI.create(base + "/todos"))
                .POST(HttpRequest.BodyPublishers.ofString("Write the lesson")).build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos"))
                .POST(HttpRequest.BodyPublishers.ofString("Test the lesson")).build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos")).GET().build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos/2")).GET().build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos/99")).GET().build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos/1")).DELETE().build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos")).GET().build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos"))
                .POST(HttpRequest.BodyPublishers.ofString("  ")).build());

        server.stop(0);
    }

    static void call(HttpClient client, HttpRequest request) throws Exception {
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(request.method() + " " + request.uri().getPath()
                + " -> " + response.statusCode() + " " + response.body());
    }

    static void handle(HttpExchange exchange) throws IOException {
        try (exchange) {
            String method = exchange.getRequestMethod();
            String[] parts = exchange.getRequestURI().getPath().split("/");   // "", "todos", maybe id
            Optional<Integer> id = parts.length > 2 ? parseId(parts[2]) : Optional.empty();

            if (parts.length > 2 && id.isEmpty()) {
                send(exchange, 400, error("id must be a number"));
            } else if (method.equals("GET") && parts.length == 2) {
                send(exchange, 200, "[" + TODOS.stream().map(Todo::toJson).collect(Collectors.joining(",")) + "]");
            } else if (method.equals("GET") && id.isPresent()) {
                Optional<Todo> todo = TODOS.stream().filter(t -> t.id() == id.get()).findFirst();
                if (todo.isPresent()) {
                    send(exchange, 200, todo.get().toJson());
                } else {
                    send(exchange, 404, error("todo " + id.get() + " not found"));
                }
            } else if (method.equals("POST") && parts.length == 2) {
                String title = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8).strip();
                if (title.isEmpty()) {
                    send(exchange, 400, error("title is required"));
                } else {
                    Todo created = new Todo(NEXT_ID.getAndIncrement(), title);
                    TODOS.add(created);
                    exchange.getResponseHeaders().set("Location", "/todos/" + created.id());
                    send(exchange, 201, created.toJson());
                }
            } else if (method.equals("DELETE") && id.isPresent()) {
                boolean removed = TODOS.removeIf(t -> t.id() == id.get());
                if (removed) {
                    exchange.sendResponseHeaders(204, -1);
                } else {
                    send(exchange, 404, error("todo " + id.get() + " not found"));
                }
            } else {
                send(exchange, 405, error("method not allowed"));
            }
        }
    }

    static Optional<Integer> parseId(String text) {
        try {
            return Optional.of(Integer.parseInt(text));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }

    static void send(HttpExchange exchange, int status, String json) throws IOException {
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
        exchange.sendResponseHeaders(status, bytes.length);
        try (OutputStream out = exchange.getResponseBody()) {
            out.write(bytes);
        }
    }

    static String error(String message) {
        return "{\"error\":\"" + escape(message) + "\"}";
    }

    static String escape(String text) {
        return text.replace("\\", "\\\\").replace("\"", "\\\"");
    }
}

Walking through it

HttpServer.create opens a server on localhost. Port 0 means "pick any free port", which avoids clashes, and we read the real port afterwards. createContext("/todos", Main::handle) registers a handler for every URL that starts with /todos. The server runs on its own thread, so main carries on and uses the client to talk to it. In the end, server.stop(0) shuts it down.

The handle method is the router. It splits the path into parts and checks the HTTP method and the shape of the URL. That is exactly what a framework does for you with annotations such as @GetMapping("/todos/{id}"). Writing it by hand once shows you how little magic there is. Each branch ends with a specific status code: 400 for a bad id, 404 for a missing todo, 405 for an unsupported method. Good APIs use status codes honestly.

The try (exchange) line works because HttpExchange is AutoCloseable. Closing it finishes the response. The send helper sets the content type, announces the body length with sendResponseHeaders and writes the bytes. For a response with no body, such as the 204 for delete, pass -1 as the length.

The JSON is built by hand with string concatenation, and the escape method handles quotes and backslashes. That is fine for a demonstration. In real code, never build JSON by hand. Use a library such as Jackson or Gson, because correct escaping, numbers, dates and nesting are harder than they look. Here the POST body is plain text only to keep the example short.

The client side uses java.net.http.HttpClient from Java 11. You build an HttpRequest, pick the method, and call send with a body handler that says how to read the response. The output of the program shows the whole conversation, including the 201 on create, the 404 for todo 99, the 204 on delete and the 400 for an empty title.

The data lives in a CopyOnWriteArrayList, and the ids come from an AtomicInteger, because the server handles requests on several threads. Anything shared between requests must be thread-safe.

Where frameworks come in

  • Spring Boot is the most widely used. It gives you dependency injection, JSON conversion, validation, security and database access with a lot of conventions.
  • Quarkus and Micronaut aim for fast start-up and low memory, which suits containers.

Whichever you choose, the ideas are the same: resources, HTTP methods, status codes, JSON bodies and stateless requests. If you understand this lesson, the framework documentation will make sense.

Common mistakes

  • Building JSON by hand in production code.

Try it yourself

  1. Add a PUT /todos/{id} endpoint that renames a todo, with the same validation as POST.
  2. Replace the hand-written JSON with Jackson in a Maven project, and compare the code.
java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class Main {

    record Todo(int id, String title) {
        String toJson() {
            return "{\"id\":" + id + ",\"title\":\"" + escape(title) + "\"}";
        }
    }

    static final List<Todo> TODOS = new CopyOnWriteArrayList<>();
    static final AtomicInteger NEXT_ID = new AtomicInteger(1);

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
        server.createContext("/todos", Main::handle);
        server.start();
        String base = "http://localhost:" + server.getAddress().getPort();
        System.out.println("Server listening on " + base);

        HttpClient client = HttpClient.newHttpClient();

        call(client, HttpRequest.newBuilder(URI.create(base + "/todos"))
                .POST(HttpRequest.BodyPublishers.ofString("Write the lesson")).build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos"))
                .POST(HttpRequest.BodyPublishers.ofString("Test the lesson")).build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos")).GET().build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos/2")).GET().build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos/99")).GET().build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos/1")).DELETE().build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos")).GET().build());
        call(client, HttpRequest.newBuilder(URI.create(base + "/todos"))
                .POST(HttpRequest.BodyPublishers.ofString("  ")).build());

        server.stop(0);
    }

    static void call(HttpClient client, HttpRequest request) throws Exception {
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(request.method() + " " + request.uri().getPath()
                + " -> " + response.statusCode() + " " + response.body());
    }

    static void handle(HttpExchange exchange) throws IOException {
        try (exchange) {
            String method = exchange.getRequestMethod();
            String[] parts = exchange.getRequestURI().getPath().split("/");   // "", "todos", maybe id
            Optional<Integer> id = parts.length > 2 ? parseId(parts[2]) : Optional.empty();

            if (parts.length > 2 && id.isEmpty()) {
                send(exchange, 400, error("id must be a number"));
            } else if (method.equals("GET") && parts.length == 2) {
                send(exchange, 200, "[" + TODOS.stream().map(Todo::toJson).collect(Collectors.joining(",")) + "]");
            } else if (method.equals("GET") && id.isPresent()) {
                Optional<Todo> todo = TODOS.stream().filter(t -> t.id() == id.get()).findFirst();
                if (todo.isPresent()) {
                    send(exchange, 200, todo.get().toJson());
                } else {
                    send(exchange, 404, error("todo " + id.get() + " not found"));
                }
            } else if (method.equals("POST") && parts.length == 2) {
                String title = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8).strip();
                if (title.isEmpty()) {
                    send(exchange, 400, error("title is required"));
                } else {
                    Todo created = new Todo(NEXT_ID.getAndIncrement(), title);
                    TODOS.add(created);
                    exchange.getResponseHeaders().set("Location", "/todos/" + created.id());
                    send(exchange, 201, created.toJson());
                }
            } else if (method.equals("DELETE") && id.isPresent()) {
                boolean removed = TODOS.removeIf(t -> t.id() == id.get());
                if (removed) {
                    exchange.sendResponseHeaders(204, -1);
                } else {
                    send(exchange, 404, error("todo " + id.get() + " not found"));
                }
            } else {
                send(exchange, 405, error("method not allowed"));
            }
        }
    }

    static Optional<Integer> parseId(String text) {
        try {
            return Optional.of(Integer.parseInt(text));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }

    static void send(HttpExchange exchange, int status, String json) throws IOException {
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
        exchange.sendResponseHeaders(status, bytes.length);
        try (OutputStream out = exchange.getResponseBody()) {
            out.write(bytes);
        }
    }

    static String error(String message) {
        return "{\"error\":\"" + escape(message) + "\"}";
    }

    static String escape(String text) {
        return text.replace("\\", "\\\\").replace("\"", "\\\"");
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account