Skip to lesson

Practice: a tiny HTTP server

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

A hand-built server stays healthy when you can extend its router, fix handler bugs, test every route with curl and explain one request. This optional page lets you check those four skills.

Adding an endpoint to a given server

Example 1 adds one route to a given router: the products of a category.

Example 1 · One new route: the products of a category

AddEndpointDemo.javaJava
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpHandler;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.ArrayList;import java.util.LinkedHashSet;import java.util.List;import java.util.Map;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.util.stream.Collectors;
/** The given server's tiny router: method + regex path; 404 and 405 with Allow. */class MiniRouter implements HttpHandler {    interface Route {        String handle(Matcher path) throws IOException;    }
    private record Entry(String method, Pattern path, Route route) {    }
    private final List<Entry> entries = new ArrayList<>();
    MiniRouter add(String method, String regex, Route route) {        entries.add(new Entry(method, Pattern.compile(regex), route));        return this;    }
    @Override    public void handle(HttpExchange exchange) throws IOException {        try (exchange) {            String path = exchange.getRequestURI().getPath();            Set<String> allowed = new LinkedHashSet<>();            for (Entry e : entries) {                Matcher m = e.path().matcher(path);                if (m.matches() && e.method().equals(exchange.getRequestMethod())) {                    send(exchange, 200, e.route().handle(m));                    return;                } else if (m.matches()) {                    allowed.add(e.method());                }            }            if (!allowed.isEmpty()) {                exchange.getResponseHeaders().set("Allow", String.join(", ", allowed));            }            send(exchange, allowed.isEmpty() ? 404 : 405, allowed.isEmpty() ? "not found" : "method not allowed");        }    }
    static void send(HttpExchange exchange, int status, String text) throws IOException {        byte[] body = text.getBytes(StandardCharsets.UTF_8);        exchange.sendResponseHeaders(status, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }}
public class AddEndpointDemo {    record Product(int id, String name, int categoryId) {    }
    static final List<Product> PRODUCTS = List.of(new Product(9, "Clean Code", 5),            new Product(10, "The Pragmatic Programmer", 5), new Product(11, "Atomic Habits", 5),            new Product(12, "Cotton Kurta", 6));    static final Map<Integer, String> CATEGORIES = Map.of(5, "Books", 6, "Fashion", 7, "Home & Kitchen");
    public static void main(String[] args) throws IOException, InterruptedException {        MiniRouter router = new MiniRouter()                .add("GET", "/api/v1/categories/([1-9][0-9]{0,8})", m -> CATEGORIES.getOrDefault(Integer.parseInt(m.group(1)), "?"))                // NEW endpoint: the products of one category, one line in the route table                .add("GET", "/api/v1/categories/([1-9][0-9]{0,8})/products", m -> {                    int categoryId = Integer.parseInt(m.group(1));                    return PRODUCTS.stream().filter(p -> p.categoryId() == categoryId)                            .map(Product::name).collect(Collectors.joining(", ", "[", "]"));                });        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/", router);        server.start();
        String base = "http://127.0.0.1:" + server.getAddress().getPort();        HttpClient client = HttpClient.newHttpClient();        String[][] calls = {{"GET", "/api/v1/categories/5/products"}, {"GET", "/api/v1/categories/6/products"},            {"GET", "/api/v1/categories/7/products"}, {"POST", "/api/v1/categories/5/products"}};        try {            for (String[] call : calls) {                HttpRequest request = HttpRequest.newBuilder(URI.create(base + call[1]))                        .method(call[0], HttpRequest.BodyPublishers.noBody()).build();                HttpResponse<String> r = client.send(request, HttpResponse.BodyHandlers.ofString());                System.out.println(call[0] + " " + call[1] + " -> " + r.statusCode() + " " + r.body()                        + r.headers().firstValue("Allow").map(a -> " (Allow: " + a + ")").orElse(""));            }        } finally {            server.stop(0);        }    }}
Output
GET /api/v1/categories/5/products -> 200 [Clean Code, The Pragmatic Programmer, Atomic Habits]
GET /api/v1/categories/6/products -> 200 [Cotton Kurta]
GET /api/v1/categories/7/products -> 200 []
POST /api/v1/categories/5/products -> 405 method not allowed (Allow: GET)

What this code does

  • The new endpoint is one .add(...) line plus a small lambda. Category 7 exists but has no products, so the answer is an empty list with 200.
  • The router already gives 405 with Allow: GET for the wrong method, because the path matched a route; nothing extra was needed for that.

Adding an endpoint to a server with a router takes three steps: write the route (method + path pattern), write the small handler that calls existing code, then call it with the right method, a wrong method and an id that does not exist.

The common mistakes: registering only the happy path, so a wrong method gets 404 instead of 405; a pattern that also matches longer paths; and a handler that does the work itself instead of calling a service. A nested list such as /categories/5/products that matches nothing is an empty list with 200, not 404; 404 is for a parent id that does not exist.

Fixing handlers that never close, send wrong lengths or wrong statuses

Example 2 shows three broken handlers next to their fixes.

Example 2 · Three handler bugs and their fixes

HandlerBugsDemo.javaJava
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.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class HandlerBugsDemo {
    static void buggyFind(HttpExchange exchange) throws IOException {        if (exchange.getRequestURI().getPath().endsWith("/99")) {            exchange.sendResponseHeaders(404, 0);            return;        }        send(exchange, 200, "Clean Code");    }
    static void fixedFind(HttpExchange exchange) throws IOException {        try (exchange) {            if (exchange.getRequestURI().getPath().endsWith("/99")) {                send(exchange, 404, "Product 99 was not found.");                return;            }            send(exchange, 200, "Clean Code");        }    }
    // BUG 2: the length counts characters; "Cables - ₹60" has a 3-byte rupee sign    static void buggyCart(HttpExchange exchange) throws IOException {        String text = "Cables - ₹60";        exchange.sendResponseHeaders(200, text.length());        try (OutputStream out = exchange.getResponseBody()) {            out.write(text.getBytes(StandardCharsets.UTF_8));        } catch (IOException e) {            System.out.println("  server: " + e.getMessage());        }    }
    static void fixedCart(HttpExchange exchange) throws IOException {        send(exchange, 200, "Cables - ₹60");    }
    static void buggyCreate(HttpExchange exchange) throws IOException {        send(exchange, 200, "created category 8");    }
    static void fixedCreate(HttpExchange exchange) throws IOException {        exchange.getResponseHeaders().set("Location", "http://localhost:8080/api/v1/categories/8");        send(exchange, 201, "created category 8");    }
    static void send(HttpExchange exchange, int status, String text) throws IOException {        byte[] body = text.getBytes(StandardCharsets.UTF_8);        exchange.sendResponseHeaders(status, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }
    public static void main(String[] args) throws Exception {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/buggy/products/", HandlerBugsDemo::buggyFind);        server.createContext("/fixed/products/", HandlerBugsDemo::fixedFind);        server.createContext("/buggy/cart", HandlerBugsDemo::buggyCart);        server.createContext("/fixed/cart", HandlerBugsDemo::fixedCart);        server.createContext("/buggy/categories", HandlerBugsDemo::buggyCreate);        server.createContext("/fixed/categories", HandlerBugsDemo::fixedCreate);        server.start();        String base = "http://127.0.0.1:" + server.getAddress().getPort();        HttpClient client = HttpClient.newHttpClient();        String[] paths = {"/buggy/products/99", "/fixed/products/99", "/buggy/cart", "/fixed/cart",            "/buggy/categories", "/fixed/categories"};        try {            for (String path : paths) {                HttpRequest request = HttpRequest.newBuilder(URI.create(base + path)).build();                try {                    HttpResponse<byte[]> r = client.sendAsync(request, HttpResponse.BodyHandlers.ofByteArray())                            .get(1, TimeUnit.SECONDS);                    System.out.println(path + " -> " + r.statusCode() + ", " + r.body().length + " bytes"                            + r.headers().firstValue("Location").map(l -> ", Location " + l).orElse(""));                } catch (TimeoutException e) {                    System.out.println(path + " -> client still waiting after 1 s");                }            }        } finally {            server.stop(0);        }    }}
Output
/buggy/products/99 -> client still waiting after 1 s
/fixed/products/99 -> 404, 25 bytes
  server: too many bytes to write to stream
/buggy/cart -> client still waiting after 1 s
/fixed/cart -> 200, 14 bytes
/buggy/categories -> 200, 18 bytes
/fixed/categories -> 201, 18 bytes, Location http://localhost:8080/api/v1/categories/8

What this code does

  • buggyFind starts a chunked 404 and returns without closing, and buggyCart promises 12 bytes but writes 14: both leave the client waiting. The fixed versions close in try (exchange) and send the byte length.
  • buggyCreate answers 200 with no Location; fixedCreate answers 201 with the absolute URL of the new category.

Three handler bugs cause most "the client just hangs" or "the client misread it" reports: an early return that skips close(); a length taken from String.length() when the text has ₹ or other multi-byte characters; and a create that answers 200 without Location.

The first two make the client wait until its timeout, with nothing useful in either log. The third works in a quick test but breaks every client that follows Location or checks for 201. The fixes are habits: try (exchange) at the top of every handler, one send helper that always uses bytes.length, and the status table of the contract next to you while you code.

Write curl tests for every route

Example 3 is the curl script that checks one status for each outcome.

Example 3 · scripts/api-test.sh: one status check per outcome

Runs in: the shoplite-http project, with the server running on port 8080

Terminal
#!/usr/bin/env bash# Calls every category and product endpoint once per expected outcome and checks the status code.# Start the server first, then run from the project folder:  bash scripts/api-test.sh# Another address:  bash scripts/api-test.sh http://localhost:9090/api/v1# It cleans up after itself (the test category and product are deleted), so you can run it again.BASE="${1:-http://localhost:8080/api/v1}"BODY_FILE="$(mktemp)"trap 'rm -f "$BODY_FILE"' EXITpass=0fail=0# check EXPECTED_STATUS METHOD PATH [BODY [CONTENT_TYPE]]   (a body is sent as JSON unless a type is given)check() {  local expected="$1" method="$2" path="$3" body="$4" type="${5:-application/json}" status  if [ -n "$body" ]; then    status=$(curl -s -o "$BODY_FILE" -w '%{http_code}' -X "$method" "$BASE$path" \      -H "Content-Type: $type" -d "$body")  else    status=$(curl -s -o "$BODY_FILE" -w '%{http_code}' -X "$method" "$BASE$path")  fi  if [ "$status" = "$expected" ]; then    pass=$((pass + 1))    printf 'PASS  %s %-6s %s\n' "$status" "$method" "$path"  else    fail=$((fail + 1))    printf 'FAIL  %s %-6s %s (expected %s)\n      %s\n' "$status" "$method" "$path" "$expected" "$(cat "$BODY_FILE")"  fi}# the "id" of the last response body, such as 16 from {"id":16,...}last_id() {  sed -n 's/^{"id":\([0-9]*\).*/\1/p' "$BODY_FILE"}echo "Testing $BASE"echo "-- categories"check 200 GET /categoriescheck 200 GET /categories/2check 404 GET /categories/99check 201 POST /categories '{"name":"Stationery","parentId":null}'cat_id=$(last_id)check 409 POST /categories '{"name":"stationery"}'check 422 POST /categories '{"name":"Tablets","parentId":42}'check 400 POST /categories '{"name":"X"}'check 400 PUT "/categories/$cat_id" '{"name":"Office Supplies"}'check 422 PUT "/categories/$cat_id" "{\"name\":\"Office Supplies\",\"parentId\":$cat_id}"check 200 PUT "/categories/$cat_id" '{"name":"Office Supplies","parentId":null}'check 409 DELETE /categories/1check 405 PATCH /categories/1 '{"name":"Gadgets"}'echo "-- products: lists"check 200 GET '/products'check 200 GET '/products?categoryId=2&sort=price,desc&page=0&size=2'check 200 GET '/products?q=pro&inStock=true&maxPrice=3000&sort=name'check 200 GET '/products?categoryId=99'check 400 GET '/products?size=500&sort=password'check 400 GET '/products?minPrice=5000&maxPrice=100'echo "-- products: one product"check 200 GET /products/1check 404 GET /products/99check 404 GET /products/abccheck 201 POST /products "{\"sku\":\"STN-PEN10\",\"name\":\"Gel Pen Pack of 10\",\"categoryId\":$cat_id,\"price\":120.00,\"stock\":200}"new_id=$(last_id)check 409 POST /products '{"sku":"MOB-RN13","name":"Duplicate SKU","categoryId":4,"price":999.00}'check 422 POST /products '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":42,"price":999.00}'check 400 POST /products '{"sku":"kb 1","name":"K","categoryId":4,"price":-5.00}'check 400 POST /products '{"id":5,"sku":"ACC-X1","name":"Has an id","categoryId":4,"price":10.00}'check 400 POST /products '{"sku":"ACC-X1","name":"Bad price","categoryId":4,"price":"abc"}'check 400 POST /products '{"sku":'check 415 POST /products 'sku=STN-PEN10' 'text/plain'check 200 PUT "/products/$new_id" "{\"sku\":\"STN-PEN10\",\"name\":\"Gel Pen Pack of 10\",\"categoryId\":$cat_id,\"price\":110.00,\"stock\":180,\"isActive\":true}"check 400 PUT "/products/$new_id" '{"price":110.00}'check 404 PUT /products/99 '{"sku":"X-123","name":"Nobody","categoryId":4,"price":1.00,"stock":1,"isActive":true}'check 200 PATCH "/products/$new_id" '{"price":99.50}'check 400 PATCH "/products/$new_id" '{"price":null}'check 400 PATCH "/products/$new_id" '{}'check 409 PATCH "/products/$new_id" '{"sku":"MOB-RN13"}'check 409 DELETE /products/1check 405 POST /products/1 '{}'echo "-- clean up"check 409 DELETE "/categories/$cat_id"check 204 DELETE "/products/$new_id"check 404 DELETE "/products/$new_id"check 204 DELETE "/categories/$cat_id"echo "$pass passed, $fail failed"[ "$fail" -eq 0 ]
Sample output
Testing http://localhost:8080/api/v1
-- categories
PASS  200 GET    /categories
PASS  200 GET    /categories/2
PASS  404 GET    /categories/99
PASS  201 POST   /categories
PASS  409 POST   /categories
PASS  422 POST   /categories
PASS  400 POST   /categories
PASS  400 PUT    /categories/8
PASS  422 PUT    /categories/8
PASS  200 PUT    /categories/8
PASS  409 DELETE /categories/1
PASS  405 PATCH  /categories/1
-- products: lists
PASS  200 GET    /products
PASS  200 GET    /products?categoryId=2&sort=price,desc&page=0&size=2
PASS  200 GET    /products?q=pro&inStock=true&maxPrice=3000&sort=name
PASS  200 GET    /products?categoryId=99
PASS  400 GET    /products?size=500&sort=password
PASS  400 GET    /products?minPrice=5000&maxPrice=100
-- products: one product
PASS  200 GET    /products/1
PASS  404 GET    /products/99
PASS  404 GET    /products/abc
PASS  201 POST   /products
PASS  409 POST   /products
PASS  422 POST   /products
PASS  400 POST   /products
PASS  400 POST   /products
PASS  400 POST   /products
PASS  400 POST   /products
PASS  415 POST   /products
PASS  200 PUT    /products/16
PASS  400 PUT    /products/16
PASS  404 PUT    /products/99
PASS  200 PATCH  /products/16
PASS  400 PATCH  /products/16
PASS  400 PATCH  /products/16
PASS  409 PATCH  /products/16
PASS  409 DELETE /products/1
PASS  405 POST   /products/1
-- clean up
PASS  409 DELETE /categories/8
PASS  204 DELETE /products/16
PASS  404 DELETE /products/16
PASS  204 DELETE /categories/8
42 passed, 0 failed

What this code does

  • check sends one request and compares the status from -w '%{http_code}' with the expected one; the body goes to a temporary file, shown only on FAIL.
  • last_id reads the new id from a 201 body, so later lines can update and delete exactly what the script created. The run ends with a count; the exit code is non-zero if anything failed.

A curl test script calls every route once for each expected outcome (success, 400, 404, 405, 409, 415, 422) and compares only the status code. It needs no extra tools: curl -s -o body.txt -w '%{http_code}' prints just the status.

Run it after every change: a forgotten route, a wrong status after a refactor or a broken error mapper shows up as one FAIL line with the response body next to it. Make it repeatable: the script creates its own test data and deletes it at the end. The ShopLite project uses exactly this script, scripts/api-test.sh.

Interview drill: what happens inside a web server for one request

Example 4 traces one request on the server side and on the client side.

Example 4 · Tracing one request, server side and client side

Text
One request: GET /api/v1/products/1 on shoplite-http 1. TCP      the client connects to port 8080; the JDK server accepts the connection 2. Parse    the dispatcher thread reads "GET /api/v1/products/1 HTTP/1.1" and the headers 3. Context  the longest matching context is "/", so the request goes to Router 4. Thread   the exchange is handed to a worker thread of the fixed pool (SERVER_THREADS) 5. Route    Router matches GET + /api/v1/products/{id}; id=1 passed the safe pattern 6. Handler  ProductHandler.get calls catalog.findProductView(1) 7. Service  CatalogService asks ProductDao; the DAO borrows a connection from HikariCP,             runs SELECT ... JOIN categories, maps the row, returns the connection 8. Response Router turns ProductResponse into JSON bytes, sets Content-Type,             sendResponseHeaders(200, 135), writes 135 bytes, closes the exchange 9. Errors   any exception in 5-8 goes to ErrorMapper -> Problem Details (404, 409, 500 ...)10. Reuse    the connection stays open (keep-alive) for the client's next request
Sample output
$ curl -v http://localhost:8080/api/v1/products/1
* Host localhost:8080 was resolved.
* IPv6: ::1
* IPv4: 127.0.0.1
*   Trying [::1]:8080...
* Connected to localhost (::1) port 8080
> GET /api/v1/products/1 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/8.8.0
> Accept: */*
> 
* Request completely sent off
< HTTP/1.1 200 OK
< Date: Fri, 16 Oct 2026 07:00:03 GMT
< Content-type: application/json
< Content-length: 135
< 
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}
* Connection #0 to host localhost left intact

What this code does

  • The ten steps name the class that does each job in shoplite-http; Tomcat and Spring do the same steps with other names.
  • curl -v shows steps 1, 2 and 8 from outside: the connection, the request lines (>), the status and headers (<), the 135-byte body, and the connection kept open for reuse.

One request passes through the same steps in every Java web server, JDK or Tomcat: accept the TCP connection, parse the request line and headers, pick the handler, run it on a worker thread, call the service and the database, write the status, headers and body, and keep or close the connection.

Interviewers ask this to see whether you understand what a framework does: answer in order, name the component at each step, and say where errors are turned into responses. curl -v shows the client side: the connection, the request lines starting with >, and the response lines starting with <.

Finish up

Mark complete & continue

Next: Project: ShopLite product API on HttpServer