Java REST API Project
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.
| Method | URL | Action | Success status |
|---|---|---|---|
GET | /api/courses | List courses (optional ?level= and ?q= filters) | 200 OK |
POST | /api/courses | Create a course from a JSON body | 201 Created + Location header |
GET | /api/courses/{id} | Get one course | 200 OK |
PUT | /api/courses/{id} | Replace a course | 200 OK |
DELETE | /api/courses/{id} | Delete a course | 204 No Content |
GET | /health | Report that the server is up | 200 OK |
Errors also return JSON, always in the same shape: {"error":"..."}.
| Status | When |
|---|---|
400 Bad Request | Invalid JSON, a wrong field type or a failed validation rule |
404 Not Found | Unknown course id or unknown URL |
405 Method Not Allowed | A method the URL does not support, such as PATCH |
500 Internal Server Error | An 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
Courseconstructor lowercases the level, so"Beginner"is stored asbeginner, and rejects any level outside theLEVELSset. quoteescapes the characters JSON requires, so the titleSpring 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": valuepairs until it meets}, andvalue()decides the type from the first character. - Whole numbers become
Longand decimals becomeDouble. The handler later checks forLong, so"price": 49.5or"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 plainint nextId++could hand out the same id twice, as explained in Java Atomic Classes.searchtakes optional filters. Passingnullskips a filter, so one method serves/api/courses,?level=advancedand?q=java.computeIfPresentreplaces the course only if the id exists, as a single atomic step. It returnsnullotherwise, whichOptional.ofNullableturns into an empty result for a404.- Results are sorted by id, because
ConcurrentHashMapdoes 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:
ITEMis a regular expression that matches/api/courses/followed by digits.item.group(1)returns the digits, so/api/courses/3gives id3, while/api/courses/abcfalls through to a404.readCourserequiresContent-Type: application/json, reads the whole body withreadAllBytes()and checks each field's type with pattern matching forinstanceof, such asfields.get("price") instanceof Long price.- Validation errors from
JsonandCourseareIllegalArgumentExceptions, and onecatchturns them all into400responses with the message. Any otherRuntimeExceptionbecomes a500without exposing details to the caller. sendResponseHeaders(status, -1)tells the server there is no body, which is what204 No Contentrequires. For other responses, the second argument is the exact body length in bytes.queryParamssplitslevel=advanced&q=javainto a map and decodes values such asq=spring%20bootwithURLDecoder.- The
finallyblock 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/coursesto the course handler. Paths outside all contexts get the server's own plain404page.Executors.newVirtualThreadPerTaskExecutor()gives each request its own cheap thread, so slow clients never block others. See Java Virtual Threads for how they work.- Port
0asks the operating system for any free port, andserver.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 fromHttpResponse, as covered in Java HttpClient. - The run shows the full life of a resource: course 3 is created with a
Locationheader, course 1 is replaced, course 2 is deleted and then returns404. Bad input returns400, andPATCHreturns405.
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:
sendAsyncreturns aCompletableFutureimmediately, 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 thatAtomicIntegerandConcurrentHashMapguarantee.
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:
- Health first.
/healthanswers without touching the data, so a load balancer or Docker health check can confirm the service is alive. - Search with query strings.
?q=javamatched "Java Basics" without caring about case, and?level=intermediatereturned both intermediate courses. - Proper REST responses.
POSTreturned201 Createdwith aLocationheader pointing to the new course, andDELETEreturned204with no body. - Clear client errors. A cut-off JSON body and a form-encoded body both got
400with a message that says exactly what to fix. - 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.