Java REST API Project

Su Suriya Ravichandran Updated 18 Nov 2026
18 min read ·Lesson 303 of 306

A Java REST API project is a small web service that other programs call over HTTP to create, read, update and delete data as JSON. In this project you build a complete course catalogue API with no external libraries: the JDK's built-in HttpServer handles requests, a tiny JSON helper reads and writes bodies, and HttpClient tests every endpoint.

It follows the Java Quiz App and puts the ideas from REST API in Java into a runnable service. You model a course, write the JSON helper, store data safely for many threads, route requests to handlers with the right status codes, and package the server as course-api.jar. All examples were run on JDK 21.


Plan the Course API Endpoints

A REST API exposes resources at URLs and uses HTTP methods to act on them. This API has one resource, courses, plus a health check that monitoring tools can call.

MethodURLActionSuccess status
GET/api/coursesList courses (optional ?level= and ?q= filters)200 OK
POST/api/coursesCreate a course from a JSON body201 Created + Location header
GET/api/courses/{id}Get one course200 OK
PUT/api/courses/{id}Replace a course200 OK
DELETE/api/courses/{id}Delete a course204 No Content
GET/healthReport that the server is up200 OK

Errors also return JSON, always in the same shape: {"error":"..."}.

StatusWhen
400 Bad RequestInvalid JSON, a wrong field type or a failed validation rule
404 Not FoundUnknown course id or unknown URL
405 Method Not AllowedA method the URL does not support, such as PATCH
500 Internal Server ErrorAn unexpected bug on the server

Model the Course and Read and Write JSON in Java

The Course record validates its own data, so an invalid course can never be stored. The Json class converts courses to JSON text and parses flat request bodies such as {"title":"Java","price":499} into a Map.

package com.gocourse.api;

import java.util.Set;

/** One course in the catalogue. Price is in rupees. */
public record Course(int id, String title, String level, int price) {
    public static final Set<String> LEVELS = Set.of("beginner", "intermediate", "advanced");

    public Course {
        if (title == null || title.isBlank()) throw new IllegalArgumentException("title is required");
        if (title.length() > 80) throw new IllegalArgumentException("title must be at most 80 characters");
        level = level == null ? "" : level.strip().toLowerCase();
        if (!LEVELS.contains(level)) {
            throw new IllegalArgumentException("level must be beginner, intermediate or advanced");
        }
        if (price < 0) throw new IllegalArgumentException("price cannot be negative");
        title = title.strip();
    }

    public Course withId(int newId) {
        return new Course(newId, title, level, price);
    }
}
package com.gocourse.api;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/** A tiny JSON helper for flat objects, so the project needs no external library. */
public final class Json {
    private Json() { }

    public static String quote(String text) {
        StringBuilder sb = new StringBuilder("\"");
        for (char c : text.toCharArray()) {
            switch (c) {
                case '"' -> sb.append("\\\"");
                case '\\' -> sb.append("\\\\");
                case '\n' -> sb.append("\\n");
                case '\r' -> sb.append("\\r");
                case '\t' -> sb.append("\\t");
                default -> {
                    if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
                    else sb.append(c);
                }
            }
        }
        return sb.append('"').toString();
    }

    public static String of(Course c) {
        return "{\"id\":" + c.id() + ",\"title\":" + quote(c.title())
                + ",\"level\":" + quote(c.level()) + ",\"price\":" + c.price() + "}";
    }

    public static String of(List<Course> courses) {
        return courses.stream().map(Json::of).collect(Collectors.joining(",", "[", "]"));
    }

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

    /** Parses one flat JSON object such as {"title":"Java","price":499}. Values: string, number, boolean, null. */
    public static Map<String, Object> parseObject(String json) {
        Parser p = new Parser(json);
        Map<String, Object> result = p.object();
        p.skipSpaces();
        if (p.pos != json.length()) throw p.fail("unexpected text after the object");
        return result;
    }

    private static final class Parser {
        private final String s;
        private int pos;

        Parser(String s) {
            this.s = s;
        }

        Map<String, Object> object() {
            Map<String, Object> map = new LinkedHashMap<>();
            expect('{');
            skipSpaces();
            if (peek() == '}') {
                pos++;
                return map;
            }
            while (true) {
                skipSpaces();
                String key = string();
                skipSpaces();
                expect(':');
                skipSpaces();
                map.put(key, value());
                skipSpaces();
                if (peek() == ',') {
                    pos++;
                } else {
                    expect('}');
                    return map;
                }
            }
        }

        Object value() {
            char c = peek();
            if (c == '"') return string();
            if (c == '-' || Character.isDigit(c)) return number();
            if (s.startsWith("true", pos)) { pos += 4; return Boolean.TRUE; }
            if (s.startsWith("false", pos)) { pos += 5; return Boolean.FALSE; }
            if (s.startsWith("null", pos)) { pos += 4; return null; }
            throw fail("expected a string, number, true, false or null");
        }

        String string() {
            expect('"');
            StringBuilder sb = new StringBuilder();
            while (true) {
                if (pos >= s.length()) throw fail("unterminated string");
                char c = s.charAt(pos++);
                if (c == '"') return sb.toString();
                if (c != '\\') {
                    sb.append(c);
                    continue;
                }
                char e = s.charAt(pos++);
                switch (e) {
                    case 'n' -> sb.append('\n');
                    case 't' -> sb.append('\t');
                    case 'r' -> sb.append('\r');
                    case 'u' -> {
                        sb.append((char) Integer.parseInt(s.substring(pos, pos + 4), 16));
                        pos += 4;
                    }
                    default -> sb.append(e); // \" \\ \/
                }
            }
        }

        Number number() {
            int start = pos;
            if (peek() == '-') pos++;
            while (pos < s.length() && (Character.isDigit(s.charAt(pos)) || ".eE+-".indexOf(s.charAt(pos)) >= 0)) pos++;
            String text = s.substring(start, pos);
            try {
                return text.matches("-?\\d+") ? (Number) Long.parseLong(text) : (Number) Double.parseDouble(text);
            } catch (NumberFormatException ex) {
                throw fail("bad number '" + text + "'");
            }
        }

        void skipSpaces() {
            while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) pos++;
        }

        char peek() {
            if (pos >= s.length()) throw fail("unexpected end of JSON");
            return s.charAt(pos);
        }

        void expect(char c) {
            if (peek() != c) throw fail("expected '" + c + "'");
            pos++;
        }

        IllegalArgumentException fail(String message) {
            return new IllegalArgumentException("Invalid JSON at position " + pos + ": " + message);
        }
    }
}
package com.gocourse.api;

import java.util.List;

public class JsonDemo {
    public static void main(String[] args) {
        Course java = new Course(1, "Java Basics", "Beginner", 499);
        Course spring = new Course(2, "Spring Boot \"Pro\"", "advanced", 1999);
        System.out.println(Json.of(java));
        System.out.println(Json.of(List.of(java, spring)));
        System.out.println(Json.error("course 9 not found"));

        String body = """
                { "title": "Python for Data", "level": "intermediate", "price": 799, "featured": true }
                """.strip();
        System.out.println(Json.parseObject(body));

        for (String bad : new String[] {"{\"title\": \"Java\"", "{\"price\": 49x}", "[1, 2]", "{\"a\":1} extra"}) {
            try {
                Json.parseObject(bad);
            } catch (IllegalArgumentException e) {
                System.out.println(bad + "  ->  " + e.getMessage());
            }
        }

        try {
            new Course(0, "Go Lang", "expert", 299);
        } catch (IllegalArgumentException e) {
            System.out.println("Course rejected: " + e.getMessage());
        }
    }
}
{"id":1,"title":"Java Basics","level":"beginner","price":499}
[{"id":1,"title":"Java Basics","level":"beginner","price":499},{"id":2,"title":"Spring Boot \"Pro\"","level":"advanced","price":1999}]
{"error":"course 9 not found"}
{title=Python for Data, level=intermediate, price=799, featured=true}
{"title": "Java"  ->  Invalid JSON at position 16: unexpected end of JSON
{"price": 49x}  ->  Invalid JSON at position 12: expected '}'
[1, 2]  ->  Invalid JSON at position 0: expected '{'
{"a":1} extra  ->  Invalid JSON at position 8: unexpected text after the object
Course rejected: level must be beginner, intermediate or advanced

How it works:

  • The Course constructor lowercases the level, so "Beginner" is stored as beginner, and rejects any level outside the LEVELS set.
  • quote escapes the characters JSON requires, so the title Spring Boot "Pro" becomes "Spring Boot \"Pro\"" and the output stays valid.
  • The parser walks the text one character at a time with a position counter pos. object() reads "key": value pairs until it meets }, and value() decides the type from the first character.
  • Whole numbers become Long and decimals become Double. The handler later checks for Long, so "price": 49.5 or "price": "free" is rejected.
  • Every parse error includes the position, which makes broken request bodies easy to debug. A real project usually uses a library such as Gson, as shown in JSON in Java; the small helper here keeps this project dependency-free.

Store Courses in a Thread-Safe Repository

HttpServer handles requests on several threads at once, so two POST requests can arrive at the same moment. The repository uses ConcurrentHashMap and AtomicInteger so that no update is lost and no id is used twice.

package com.gocourse.api;

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.AtomicInteger;

/** Thread-safe in-memory storage. Many HTTP requests can use it at the same time. */
public class CourseRepository {
    private final Map<Integer, Course> courses = new ConcurrentHashMap<>();
    private final AtomicInteger nextId = new AtomicInteger(1);

    public Course create(Course course) {
        Course saved = course.withId(nextId.getAndIncrement());
        courses.put(saved.id(), saved);
        return saved;
    }

    public Optional<Course> find(int id) {
        return Optional.ofNullable(courses.get(id));
    }

    /** Both filters are optional: pass null to ignore them. */
    public List<Course> search(String level, String text) {
        return courses.values().stream()
                .filter(c -> level == null || c.level().equalsIgnoreCase(level))
                .filter(c -> text == null || c.title().toLowerCase().contains(text.toLowerCase()))
                .sorted(Comparator.comparingInt(Course::id))
                .toList();
    }

    /** Replaces an existing course. Returns empty when the id does not exist. */
    public Optional<Course> update(int id, Course course) {
        Course updated = course.withId(id);
        return Optional.ofNullable(courses.computeIfPresent(id, (key, old) -> updated));
    }

    public boolean delete(int id) {
        return courses.remove(id) != null;
    }
}

How it works:

  • nextId.getAndIncrement() is atomic: two threads calling it together always receive different numbers. A plain int nextId++ could hand out the same id twice, as explained in Java Atomic Classes.
  • search takes optional filters. Passing null skips a filter, so one method serves /api/courses, ?level=advanced and ?q=java.
  • computeIfPresent replaces the course only if the id exists, as a single atomic step. It returns null otherwise, which Optional.ofNullable turns into an empty result for a 404.
  • Results are sorted by id, because ConcurrentHashMap does not keep any order.

Handle HTTP Requests With Java HttpServer

CourseHandler implements HttpHandler. The server calls its handle method for every request under /api/courses. The method looks at the HTTP method and path, calls the repository and writes a JSON response with the right status code.

package com.gocourse.api;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Routes /api/courses and /api/courses/{id} to the repository and writes JSON responses. */
public class CourseHandler implements HttpHandler {
    private static final Pattern ITEM = Pattern.compile("/api/courses/(\\d+)");

    private final CourseRepository repository;

    public CourseHandler(CourseRepository repository) {
        this.repository = repository;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String method = exchange.getRequestMethod();
        String path = exchange.getRequestURI().getPath();
        try {
            if (path.equals("/api/courses") || path.equals("/api/courses/")) {
                switch (method) {
                    case "GET" -> list(exchange);
                    case "POST" -> create(exchange);
                    default -> send(exchange, 405, Json.error("method " + method + " not allowed here"));
                }
                return;
            }
            Matcher item = ITEM.matcher(path);
            if (!item.matches()) {
                send(exchange, 404, Json.error("no route for " + path));
                return;
            }
            int id = Integer.parseInt(item.group(1));
            switch (method) {
                case "GET" -> repository.find(id).ifPresentOrElse(
                        c -> send(exchange, 200, Json.of(c)),
                        () -> send(exchange, 404, Json.error("course " + id + " not found")));
                case "PUT" -> {
                    Course course = readCourse(exchange);
                    repository.update(id, course).ifPresentOrElse(
                            c -> send(exchange, 200, Json.of(c)),
                            () -> send(exchange, 404, Json.error("course " + id + " not found")));
                }
                case "DELETE" -> {
                    if (repository.delete(id)) send(exchange, 204, null);
                    else send(exchange, 404, Json.error("course " + id + " not found"));
                }
                default -> send(exchange, 405, Json.error("method " + method + " not allowed here"));
            }
        } catch (IllegalArgumentException e) { // bad JSON or failed validation
            send(exchange, 400, Json.error(e.getMessage()));
        } catch (RuntimeException e) {
            send(exchange, 500, Json.error("internal error"));
            e.printStackTrace();
        } finally {
            exchange.close();
        }
    }

    private void list(HttpExchange exchange) {
        Map<String, String> query = queryParams(exchange.getRequestURI().getRawQuery());
        send(exchange, 200, Json.of(repository.search(query.get("level"), query.get("q"))));
    }

    private void create(HttpExchange exchange) throws IOException {
        Course saved = repository.create(readCourse(exchange));
        exchange.getResponseHeaders().set("Location", "/api/courses/" + saved.id());
        send(exchange, 201, Json.of(saved));
    }

    /** Reads the request body and turns it into a Course (id 0 until it is saved). */
    private Course readCourse(HttpExchange exchange) throws IOException {
        String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
        if (contentType == null || !contentType.startsWith("application/json")) {
            throw new IllegalArgumentException("Content-Type must be application/json");
        }
        String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
        Map<String, Object> fields = Json.parseObject(body);
        if (!(fields.get("title") instanceof String title)) throw new IllegalArgumentException("title must be a string");
        if (!(fields.get("level") instanceof String level)) throw new IllegalArgumentException("level must be a string");
        if (!(fields.get("price") instanceof Long price)) throw new IllegalArgumentException("price must be a whole number");
        if (price > 1_000_000) throw new IllegalArgumentException("price is too large");
        return new Course(0, title, level, price.intValue());
    }

    private static Map<String, String> queryParams(String rawQuery) {
        Map<String, String> params = new HashMap<>();
        if (rawQuery == null) return params;
        for (String pair : rawQuery.split("&")) {
            String[] kv = pair.split("=", 2);
            params.put(URLDecoder.decode(kv[0], StandardCharsets.UTF_8),
                    kv.length > 1 ? URLDecoder.decode(kv[1], StandardCharsets.UTF_8) : "");
        }
        return params;
    }

    /** Writes a JSON body, or no body at all for 204 No Content. */
    static void send(HttpExchange exchange, int status, String json) {
        try {
            if (json == null) {
                exchange.sendResponseHeaders(status, -1); // -1 = no body
                return;
            }
            byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
            exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
            exchange.sendResponseHeaders(status, bytes.length);
            try (OutputStream body = exchange.getResponseBody()) {
                body.write(bytes);
            }
        } catch (IOException e) {
            throw new java.io.UncheckedIOException(e);
        }
    }
}

How it works:

  • ITEM is a regular expression that matches /api/courses/ followed by digits. item.group(1) returns the digits, so /api/courses/3 gives id 3, while /api/courses/abc falls through to a 404.
  • readCourse requires Content-Type: application/json, reads the whole body with readAllBytes() and checks each field's type with pattern matching for instanceof, such as fields.get("price") instanceof Long price.
  • Validation errors from Json and Course are IllegalArgumentExceptions, and one catch turns them all into 400 responses with the message. Any other RuntimeException becomes a 500 without exposing details to the caller.
  • sendResponseHeaders(status, -1) tells the server there is no body, which is what 204 No Content requires. For other responses, the second argument is the exact body length in bytes.
  • queryParams splits level=advanced&q=java into a map and decodes values such as q=spring%20boot with URLDecoder.
  • The finally block closes the exchange on every path, so a connection is never left open.

Start the Server and Test the Java REST API With HttpClient

ApiServer creates the server, registers the handlers and runs each request on a virtual thread. The demo then calls every endpoint with java.net.http.HttpClient, which works like a small test suite.

package com.gocourse.api;

import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

/** Starts the course REST API on http://localhost:<port>. */
public class ApiServer {
    public static HttpServer start(int port, CourseRepository repository) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext("/api/courses", new CourseHandler(repository));
        server.createContext("/health", exchange -> {
            CourseHandler.send(exchange, 200, "{\"status\":\"UP\"}");
            exchange.close();
        });
        server.setExecutor(Executors.newVirtualThreadPerTaskExecutor()); // one virtual thread per request
        server.start();
        return server;
    }

    public static void main(String[] args) throws IOException {
        int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));
        CourseRepository repository = new CourseRepository();
        repository.create(new Course(0, "Java Basics", "beginner", 499));
        repository.create(new Course(0, "Spring Boot REST APIs", "advanced", 1999));
        repository.create(new Course(0, "Python for Data", "intermediate", 799));

        HttpServer server = start(port, repository);
        System.out.println("Course API running on http://localhost:" + server.getAddress().getPort());
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            server.stop(1); // wait up to 1 second for running requests
            System.out.println("Server stopped");
        }));
    }
}
package com.gocourse.api;

import com.sun.net.httpserver.HttpServer;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/** Starts the API on a free port and calls every endpoint with java.net.http.HttpClient. */
public class ApiClientDemo {
    static HttpClient client = HttpClient.newHttpClient();
    static String base;

    static void call(String method, String path, String json) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path));
        if (json == null) {
            request.method(method, HttpRequest.BodyPublishers.noBody());
        } else {
            request.header("Content-Type", "application/json")
                    .method(method, HttpRequest.BodyPublishers.ofString(json));
        }
        HttpResponse<String> response = client.send(request.build(), HttpResponse.BodyHandlers.ofString());
        String location = response.headers().firstValue("Location").map(l -> "  Location: " + l).orElse("");
        System.out.printf("%-6s %-28s -> %d%s%n", method, path, response.statusCode(), location);
        if (!response.body().isEmpty()) System.out.println("       " + response.body());
    }

    public static void main(String[] args) throws Exception {
        CourseRepository repository = new CourseRepository();
        repository.create(new Course(0, "Java Basics", "beginner", 499));
        repository.create(new Course(0, "Spring Boot REST APIs", "advanced", 1999));
        HttpServer server = ApiServer.start(0, repository); // port 0 = any free port
        base = "http://localhost:" + server.getAddress().getPort();

        call("GET", "/api/courses", null);
        call("POST", "/api/courses", "{\"title\":\"Python for Data\",\"level\":\"Intermediate\",\"price\":799}");
        call("GET", "/api/courses/3", null);
        call("GET", "/api/courses?level=advanced", null);
        call("PUT", "/api/courses/1", "{\"title\":\"Java Basics 2026\",\"level\":\"beginner\",\"price\":399}");
        call("DELETE", "/api/courses/2", null);
        call("GET", "/api/courses/2", null);
        call("POST", "/api/courses", "{\"title\":\"\",\"level\":\"beginner\",\"price\":0}");
        call("POST", "/api/courses", "{\"title\":\"Go\",\"level\":\"beginner\",\"price\":\"free\"}");
        call("PATCH", "/api/courses/1", "{}");
        call("GET", "/api/courses/abc", null);
        call("GET", "/api/courses", null);

        server.stop(0);
    }
}
GET    /api/courses                 -> 200
       [{"id":1,"title":"Java Basics","level":"beginner","price":499},{"id":2,"title":"Spring Boot REST APIs","level":"advanced","price":1999}]
POST   /api/courses                 -> 201  Location: /api/courses/3
       {"id":3,"title":"Python for Data","level":"intermediate","price":799}
GET    /api/courses/3               -> 200
       {"id":3,"title":"Python for Data","level":"intermediate","price":799}
GET    /api/courses?level=advanced  -> 200
       [{"id":2,"title":"Spring Boot REST APIs","level":"advanced","price":1999}]
PUT    /api/courses/1               -> 200
       {"id":1,"title":"Java Basics 2026","level":"beginner","price":399}
DELETE /api/courses/2               -> 204
GET    /api/courses/2               -> 404
       {"error":"course 2 not found"}
POST   /api/courses                 -> 400
       {"error":"title is required"}
POST   /api/courses                 -> 400
       {"error":"price must be a whole number"}
PATCH  /api/courses/1               -> 405
       {"error":"method PATCH not allowed here"}
GET    /api/courses/abc             -> 404
       {"error":"no route for /api/courses/abc"}
GET    /api/courses                 -> 200
       [{"id":1,"title":"Java Basics 2026","level":"beginner","price":399},{"id":3,"title":"Python for Data","level":"intermediate","price":799}]

How it works:

  • createContext("/api/courses", ...) sends every path that starts with /api/courses to the course handler. Paths outside all contexts get the server's own plain 404 page.
  • Executors.newVirtualThreadPerTaskExecutor() gives each request its own cheap thread, so slow clients never block others. See Java Virtual Threads for how they work.
  • Port 0 asks the operating system for any free port, and server.getAddress().getPort() reports which one was chosen. This keeps demos and tests from failing when port 8080 is busy.
  • The client builds each request with HttpRequest.newBuilder, adds a JSON body only when needed, and reads the status, headers and body from HttpResponse, as covered in Java HttpClient.
  • The run shows the full life of a resource: course 3 is created with a Location header, course 1 is replaced, course 2 is deleted and then returns 404. Bad input returns 400, and PATCH returns 405.

Check the API Under Concurrent Requests

A REST API must stay correct when many clients call it at once. This demo sends 200 POST requests at the same time with sendAsync and checks that every course received a unique id.

package com.gocourse.api;

import com.sun.net.httpserver.HttpServer;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/** Sends 200 POST requests at the same time and checks that every course got its own id. */
public class LoadDemo {
    public static void main(String[] args) {
        CourseRepository repository = new CourseRepository();
        HttpServer server;
        try {
            server = ApiServer.start(0, repository);
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
        String url = "http://localhost:" + server.getAddress().getPort() + "/api/courses";
        HttpClient client = HttpClient.newHttpClient();

        List<CompletableFuture<HttpResponse<String>>> calls = new ArrayList<>();
        for (int i = 1; i <= 200; i++) {
            String json = "{\"title\":\"Course " + i + "\",\"level\":\"beginner\",\"price\":" + i + "}";
            HttpRequest request = HttpRequest.newBuilder(URI.create(url))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(json))
                    .build();
            calls.add(client.sendAsync(request, HttpResponse.BodyHandlers.ofString()));
        }
        CompletableFuture.allOf(calls.toArray(CompletableFuture[]::new)).join();

        long created = calls.stream().filter(f -> f.join().statusCode() == 201).count();
        List<Course> all = repository.search(null, null);
        long distinctIds = all.stream().mapToInt(Course::id).distinct().count();
        System.out.println("201 Created responses: " + created);
        System.out.println("Courses stored:        " + all.size());
        System.out.println("Distinct ids:          " + distinctIds);
        System.out.println("Id range:              " + all.get(0).id() + " to " + all.get(all.size() - 1).id());
        server.stop(0);
    }
}
201 Created responses: 200
Courses stored:        200
Distinct ids:          200
Id range:              1 to 200

How it works:

  • sendAsync returns a CompletableFuture immediately, so all 200 requests are in flight together instead of one after another.
  • CompletableFuture.allOf(...).join() waits until every response has arrived.
  • All 200 requests returned 201, the repository holds 200 courses, and the ids are exactly 1 to 200 with no duplicates. This is the result that AtomicInteger and ConcurrentHashMap guarantee.

Real-World Example: Run the Course API and Call It With curl

course-api/
└── src/
    └── com/
        └── gocourse/
            └── api/
                ├── ApiServer.java
                ├── Course.java
                ├── CourseHandler.java
                ├── CourseRepository.java
                └── Json.java
cd course-api
javac -d out src/com/gocourse/api/*.java
jar --create --file course-api.jar --main-class com.gocourse.api.ApiServer -C out .

PORT=8080 java -jar course-api.jar
Course API running on http://localhost:8080

The server starts with three sample courses. In a second terminal, call it with curl:

$ curl -s http://localhost:8080/health
{"status":"UP"}

$ curl -s "http://localhost:8080/api/courses?q=java"
[{"id":1,"title":"Java Basics","level":"beginner","price":499}]

$ curl -s -i -X POST http://localhost:8080/api/courses \
    -H "Content-Type: application/json" \
    -d '{"title":"Docker for Developers","level":"intermediate","price":899}'
HTTP/1.1 201 Created
Date: Wed, 18 Nov 2026 01:21:26 GMT
Content-type: application/json; charset=utf-8
Content-length: 75
Location: /api/courses/4

{"id":4,"title":"Docker for Developers","level":"intermediate","price":899}

$ curl -s "http://localhost:8080/api/courses?level=intermediate"
[{"id":3,"title":"Python for Data","level":"intermediate","price":799},{"id":4,"title":"Docker for Developers","level":"intermediate","price":899}]

$ curl -s -X PUT http://localhost:8080/api/courses/4 \
    -H "Content-Type: application/json" \
    -d '{"title":"Docker for Developers","level":"intermediate","price":699}'
{"id":4,"title":"Docker for Developers","level":"intermediate","price":699}

$ curl -s -i -X DELETE http://localhost:8080/api/courses/2
HTTP/1.1 204 No Content
Date: Wed, 18 Nov 2026 01:21:26 GMT

$ curl -s -X POST http://localhost:8080/api/courses \
    -H "Content-Type: application/json" -d '{"title":"Kotlin","level":"beginner"'
{"error":"Invalid JSON at position 36: unexpected end of JSON"}

$ curl -s -X POST http://localhost:8080/api/courses -d 'title=Kotlin'
{"error":"Content-Type must be application/json"}

$ curl -s http://localhost:8080/api/courses
[{"id":1,"title":"Java Basics","level":"beginner","price":499},{"id":3,"title":"Python for Data","level":"intermediate","price":799},{"id":4,"title":"Docker for Developers","level":"intermediate","price":699}]

Press Ctrl+C in the server terminal to stop it:

Server stopped

How it works:

  1. Health first. /health answers without touching the data, so a load balancer or Docker health check can confirm the service is alive.
  2. Search with query strings. ?q=java matched "Java Basics" without caring about case, and ?level=intermediate returned both intermediate courses.
  3. Proper REST responses. POST returned 201 Created with a Location header pointing to the new course, and DELETE returned 204 with no body.
  4. Clear client errors. A cut-off JSON body and a form-encoded body both got 400 with a message that says exactly what to fix.
  5. Clean shutdown. The shutdown hook calls server.stop(1), which lets running requests finish for up to one second when you press Ctrl+C. The data lives in memory only; for a version that stores it in a database with Spring, see Spring Boot REST API.

The next project, the Java Chat Server, keeps connections open with sockets so many users can talk in real time.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java REST API Project and get answers drawn from it.

Signed-in readers only.