Java E-commerce API
A Java e-commerce API is the backend of an online shop: it lists products, keeps a shopping cart for each customer, prices the cart with discounts, shipping and tax, and turns the cart into an order while reducing stock. This final project builds that backend as a complete JSON REST service with no external libraries, using the JDK's built-in HttpServer, BigDecimal for money and thread-safe collections for stock.
It is the last project in the Java tutorial and combines ideas from the Java REST API Project (routing and status codes), the Java Bank App (money with BigDecimal) and the Java Employee Manager (business rules in one place). You design the endpoints, write the pricing rules, protect stock from overselling, route HTTP requests, test a full shopping session and package the server as shop-api.jar. All examples were run on JDK 21.
Plan the E-commerce API Endpoints
The API has three resources: products, carts and orders. A cart is a draft that the customer can change freely; an order is a permanent record created from a cart at checkout.
| Method | URL | Action | Success status |
|---|---|---|---|
GET | /api/products | List products (optional ?q= search) | 200 OK |
GET | /api/products/{sku} | Get one product with its stock | 200 OK |
POST | /api/carts | Create an empty cart | 201 Created + Location |
PUT | /api/carts/{id}/items/{sku} | Set the quantity of a product in the cart | 200 OK |
DELETE | /api/carts/{id}/items/{sku} | Remove a product from the cart | 200 OK |
GET | /api/carts/{id} | Price the cart (optional ?coupon=) | 200 OK |
POST | /api/carts/{id}/checkout | Place an order from the cart | 201 Created + Location |
GET | /api/orders/{id} | Get an order | 200 OK |
POST | /api/orders/{id}/cancel | Cancel an order and return its stock | 200 OK |
Errors always use the same JSON shape, {"error":"..."}, with a status code that tells the client what went wrong:
| Status | When |
|---|---|
400 Bad Request | Invalid JSON, wrong field type, bad quantity, unknown coupon, empty cart |
404 Not Found | Unknown product, cart, order or URL |
409 Conflict | Not enough stock, or an order that is already cancelled |
500 Internal Server Error | An unexpected bug |
Note:
PUTsets the quantity instead of adding to it. Sending{"quantity":2}twice still leaves 2 items in the cart, which makes the request safe to retry after a network error.
Handle Money With BigDecimal
Prices must never use double, because 0.1 + 0.2 is not exactly 0.3 in binary floating point. The Money class keeps every amount at exactly 2 decimal places, rounded half-up, and calculates percentages for discounts and GST. Product uses it so every price is stored in the same format.
package com.gocourse.shop;
import java.math.BigDecimal;
import java.math.RoundingMode;
/** Money rules in one place: always 2 decimal places, rounded half-up. */
public final class Money {
public static final BigDecimal ZERO = of(BigDecimal.ZERO);
private Money() { }
public static BigDecimal of(BigDecimal amount) {
return amount.setScale(2, RoundingMode.HALF_UP);
}
public static BigDecimal of(String amount) {
return of(new BigDecimal(amount));
}
/** percent of an amount, e.g. percent(1000.00, 18) = 180.00 */
public static BigDecimal percent(BigDecimal amount, int percent) {
return of(amount.multiply(BigDecimal.valueOf(percent)).divide(BigDecimal.valueOf(100)));
}
}
package com.gocourse.shop;
import java.math.BigDecimal;
/** A product in the catalogue. Price is in rupees with 2 decimal places. */
public record Product(String sku, String name, BigDecimal price) {
public Product {
if (sku == null || !sku.matches("[A-Z0-9-]{3,20}")) throw new IllegalArgumentException("bad sku: " + sku);
if (name == null || name.isBlank()) throw new IllegalArgumentException("name is required");
if (price == null || price.signum() <= 0) throw new IllegalArgumentException("price must be positive");
price = Money.of(price);
}
}
How it works:
setScale(2, RoundingMode.HALF_UP)turns599into599.00and345.312into345.31, so every amount looks and compares the same way.percentmultiplies first and divides second, then rounds once. Rounding only at the end avoids small errors that add up across many lines.- The
Productconstructor rejects a bad SKU, a blank name or a zero or negative price, so an invalid product can never enter the catalogue.
Model Orders and Business Errors
An Order is an immutable record. Each Line copies the product's name and unit price at checkout time, so a later price change does not alter old orders. The same record is used for a cart preview with the status QUOTE.
package com.gocourse.shop;
import java.math.BigDecimal;
import java.util.List;
/** An immutable order. Prices are copied from the catalogue at checkout time. */
public record Order(String id, List<Line> lines, BigDecimal subtotal, BigDecimal discount,
BigDecimal shipping, BigDecimal gst, BigDecimal total, Status status) {
public enum Status { QUOTE, PLACED, CANCELLED }
public record Line(String sku, String name, BigDecimal unitPrice, int quantity) {
public BigDecimal amount() {
return Money.of(unitPrice.multiply(BigDecimal.valueOf(quantity)));
}
}
public Order cancelled() {
return new Order(id, lines, subtotal, discount, shipping, gst, total, Status.CANCELLED);
}
public Order asQuote() {
return new Order(id, lines, subtotal, discount, shipping, gst, total, Status.QUOTE);
}
}
package com.gocourse.shop;
/** A business error that maps straight to an HTTP status code. */
public class ShopException extends RuntimeException {
private final int status;
public ShopException(int status, String message) {
super(message);
this.status = status;
}
public int status() {
return status;
}
}
How it works:
Line.amount()multiplies the unit price by the quantity, for example599.00 x 2 = 1198.00.cancelled()andasQuote()return a new record with a different status, because records cannot be changed.ShopExceptioncarries an HTTP status with the message. The service throwsnew ShopException(409, "only 3 left of KB-MECH")and the HTTP layer only has to copy the status and message into the response.
Write the Shop Service: Carts, Pricing and Checkout
Shop holds all business rules. It knows nothing about HTTP, so it can be tested and reused without a server. The pricing rules are:
| Rule | Value |
|---|---|
| Coupons | WELCOME10 = 10% off, FESTIVE20 = 20% off (case-insensitive) |
| Shipping | ₹49, free when the amount after discount is ₹999 or more |
| GST | 18% of the amount after discount |
| Quantity per product | 1 to 10, and never more than the current stock |
package com.gocourse.shop;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/** The business logic: catalogue, stock, carts, pricing and orders. Thread-safe. */
public class Shop {
static final BigDecimal FREE_SHIPPING_FROM = Money.of("999");
static final BigDecimal SHIPPING_FEE = Money.of("49");
static final int GST_PERCENT = 18;
static final Map<String, Integer> COUPONS = Map.of("WELCOME10", 10, "FESTIVE20", 20);
private final Map<String, Product> products = new ConcurrentHashMap<>();
private final Map<String, Integer> stock = new ConcurrentHashMap<>();
private final Map<String, Map<String, Integer>> carts = new ConcurrentHashMap<>();
private final Map<String, Order> orders = new ConcurrentHashMap<>();
private final AtomicInteger cartSeq = new AtomicInteger(1);
private final AtomicInteger orderSeq = new AtomicInteger(1001);
// ---- catalogue ----
public void addProduct(Product product, int quantity) {
products.put(product.sku(), product);
stock.put(product.sku(), quantity);
}
public List<Product> products(String search) {
return products.values().stream()
.filter(p -> search == null || p.name().toLowerCase().contains(search.toLowerCase()))
.sorted((a, b) -> a.sku().compareTo(b.sku()))
.toList();
}
public Product product(String sku) {
Product p = products.get(sku);
if (p == null) throw new ShopException(404, "product " + sku + " not found");
return p;
}
public int stockOf(String sku) {
return stock.getOrDefault(sku, 0);
}
// ---- carts ----
public String createCart() {
String id = "C" + cartSeq.getAndIncrement();
carts.put(id, new ConcurrentHashMap<>());
return id;
}
private Map<String, Integer> cart(String cartId) {
Map<String, Integer> cart = carts.get(cartId);
if (cart == null) throw new ShopException(404, "cart " + cartId + " not found");
return cart;
}
/** Sets the quantity of one product in a cart. Quantity 0 removes it. */
public void setItem(String cartId, String sku, int quantity) {
product(sku); // 404 for unknown products
if (quantity < 0 || quantity > 10) throw new ShopException(400, "quantity must be between 0 and 10");
if (quantity > stockOf(sku)) throw new ShopException(409, "only " + stockOf(sku) + " left of " + sku);
if (quantity == 0) cart(cartId).remove(sku);
else cart(cartId).put(sku, quantity);
}
/** Prices a cart without placing an order, so the client can show a preview. */
public Order quote(String cartId, String coupon) {
Map<String, Integer> cart = cart(cartId);
List<Order.Line> lines = new ArrayList<>();
new java.util.TreeMap<>(cart).forEach((sku, qty) -> {
Product p = product(sku);
lines.add(new Order.Line(sku, p.name(), p.price(), qty));
});
return price(cartId, lines, coupon).asQuote();
}
static Order price(String id, List<Order.Line> lines, String coupon) {
BigDecimal subtotal = lines.stream().map(Order.Line::amount).reduce(Money.ZERO, BigDecimal::add);
int off = 0;
if (coupon != null && !coupon.isBlank()) {
Integer percent = COUPONS.get(coupon.toUpperCase());
if (percent == null) throw new ShopException(400, "unknown coupon " + coupon);
off = percent;
}
BigDecimal discount = Money.percent(subtotal, off);
BigDecimal taxable = subtotal.subtract(discount);
BigDecimal shipping = lines.isEmpty() || taxable.compareTo(FREE_SHIPPING_FROM) >= 0 ? Money.ZERO : SHIPPING_FEE;
BigDecimal gst = Money.percent(taxable, GST_PERCENT);
BigDecimal total = taxable.add(shipping).add(gst);
return new Order(id, List.copyOf(lines), subtotal, discount, shipping, gst, total, Order.Status.PLACED);
}
// ---- orders ----
/** All-or-nothing: either every line is reserved and the order placed, or nothing changes. */
public Order checkout(String cartId, String coupon) {
Map<String, Integer> cart = cart(cartId);
if (cart.isEmpty()) throw new ShopException(400, "cart " + cartId + " is empty");
Order quote = quote(cartId, coupon); // validates the coupon before touching stock
synchronized (stock) {
for (Order.Line line : quote.lines()) {
if (stockOf(line.sku()) < line.quantity()) {
throw new ShopException(409, "not enough stock for " + line.sku()
+ " (wanted " + line.quantity() + ", have " + stockOf(line.sku()) + ")");
}
}
quote.lines().forEach(line -> stock.merge(line.sku(), -line.quantity(), Integer::sum));
}
Order order = price("ORD-" + orderSeq.getAndIncrement(), quote.lines(), coupon);
orders.put(order.id(), order);
carts.remove(cartId); // a checked-out cart cannot be used again
return order;
}
public Order order(String id) {
Order o = orders.get(id);
if (o == null) throw new ShopException(404, "order " + id + " not found");
return o;
}
public Order cancel(String id) {
synchronized (stock) {
Order o = order(id);
if (o.status() == Order.Status.CANCELLED) throw new ShopException(409, "order " + id + " is already cancelled");
o.lines().forEach(line -> stock.merge(line.sku(), line.quantity(), Integer::sum));
Order cancelled = o.cancelled();
orders.put(id, cancelled);
return cancelled;
}
}
public Map<String, Integer> stockReport() {
return Collections.unmodifiableMap(new LinkedHashMap<>(new java.util.TreeMap<>(stock)));
}
}
How it works:
- Carts are maps from SKU to quantity.
setItemchecks that the product exists, that the quantity is between 0 and 10 and that enough stock is available. Quantity0removes the product. priceis a static method that computes subtotal, discount, shipping, GST and total from a list of lines. The cart preview and the real order both use it, so the customer always sees the same numbers they will pay.checkoutprices the cart first, so an unknown coupon fails with400before any stock changes. Insidesynchronized (stock)it checks every line and only then subtracts stock for all lines. If one product is short, nothing is reserved: the order is all-or-nothing.canceladds the quantities back to stock and marks the orderCANCELLED. Cancelling twice returns409, so stock is never returned twice.- The checked-out cart is removed, so the same cart cannot be paid for a second time.
Test the Pricing Rules
Before adding HTTP, check the numbers directly. This demo prices a small cart, a large cart and a large cart with a coupon.
package com.gocourse.shop;
import java.util.List;
public class PricingDemo {
public static void main(String[] args) {
List<Order.Line> small = List.of(new Order.Line("MUG-CODE", "Coder Coffee Mug", Money.of("249.50"), 2));
List<Order.Line> big = List.of(
new Order.Line("BOOK-JAVA", "Java Programming Book", Money.of("599"), 2),
new Order.Line("MUG-CODE", "Coder Coffee Mug", Money.of("249.50"), 1));
print("Small cart, no coupon", Shop.price("Q1", small, null));
print("Big cart, no coupon", Shop.price("Q2", big, null));
print("Big cart, WELCOME10", Shop.price("Q3", big, "welcome10"));
try {
Shop.price("Q4", big, "FREE100");
} catch (ShopException e) {
System.out.println(e.status() + " " + e.getMessage());
}
}
static void print(String label, Order o) {
System.out.printf("%-22s subtotal=%8s discount=%7s shipping=%6s gst=%7s total=%8s%n",
label, o.subtotal(), o.discount(), o.shipping(), o.gst(), o.total());
}
}
Small cart, no coupon subtotal= 499.00 discount= 0.00 shipping= 49.00 gst= 89.82 total= 637.82
Big cart, no coupon subtotal= 1447.50 discount= 0.00 shipping= 0.00 gst= 260.55 total= 1708.05
Big cart, WELCOME10 subtotal= 1447.50 discount= 144.75 shipping= 0.00 gst= 234.50 total= 1537.25
400 unknown coupon FREE100
How it works:
- The small cart is ₹499.00, below ₹999, so it pays ₹49 shipping. GST is 18% of 499.00 = 89.82, and the total is 499.00 + 49.00 + 89.82 = 637.82.
- The large cart is ₹1447.50, so shipping is free and GST is 260.55.
- With
welcome10, the discount is 10% of 1447.50 = 144.75. GST is charged on the reduced amount, 1302.75 x 18% = 234.50, giving 1537.25. - An unknown coupon raises a
ShopExceptionwith status400.
Read and Write JSON Without a Library
The API only needs flat request bodies such as {"quantity":2} or {"coupon":"WELCOME10"}. A small helper writes products and orders as JSON and reads flat objects with a regular expression. A real project would normally use a library such as Jackson or Gson.
package com.gocourse.shop;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/** Minimal JSON writing and flat-object reading, so the project needs no library. */
public final class Json {
private static final Pattern PAIR = Pattern.compile(
"\\s*\"([^\"]+)\"\\s*:\\s*(\"((?:[^\"\\\\]|\\\\.)*)\"|-?\\d+|true|false|null)\\s*(,|$)");
private Json() { }
public static String quote(String s) {
return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") + "\"";
}
public static String product(Product p, int stock) {
return "{\"sku\":" + quote(p.sku()) + ",\"name\":" + quote(p.name())
+ ",\"price\":" + p.price().toPlainString() + ",\"stock\":" + stock + "}";
}
public static String order(Order o) {
String lines = o.lines().stream()
.map(l -> "{\"sku\":" + quote(l.sku()) + ",\"quantity\":" + l.quantity()
+ ",\"unitPrice\":" + l.unitPrice() + ",\"amount\":" + l.amount() + "}")
.collect(Collectors.joining(",", "[", "]"));
return "{\"id\":" + quote(o.id()) + ",\"status\":" + quote(o.status().name()) + ",\"lines\":" + lines
+ ",\"subtotal\":" + o.subtotal() + ",\"discount\":" + o.discount()
+ ",\"shipping\":" + o.shipping() + ",\"gst\":" + o.gst() + ",\"total\":" + o.total() + "}";
}
public static String array(List<String> items) {
return items.stream().collect(Collectors.joining(",", "[", "]"));
}
public static String error(String message) {
return "{\"error\":" + quote(message) + "}";
}
/** Reads {"sku":"BOOK-JAVA","quantity":2}. Values: strings, whole numbers, true, false, null. */
public static Map<String, Object> parseObject(String json) {
String body = json.strip();
if (body.isEmpty()) return Map.of();
if (!body.startsWith("{") || !body.endsWith("}")) throw new IllegalArgumentException("body must be a JSON object");
String inner = body.substring(1, body.length() - 1).strip();
Map<String, Object> map = new LinkedHashMap<>();
Matcher m = PAIR.matcher(inner);
int pos = 0;
while (pos < inner.length()) {
if (!m.find(pos) || m.start() != pos) throw new IllegalArgumentException("invalid JSON near position " + pos);
String raw = m.group(2);
Object value = m.group(3) != null ? m.group(3).replace("\\\"", "\"").replace("\\\\", "\\")
: raw.equals("null") ? null
: raw.equals("true") || raw.equals("false") ? Boolean.valueOf(raw)
: (Object) Long.valueOf(raw);
map.put(m.group(1), value);
pos = m.end();
}
return map;
}
}
How it works:
quoteescapes backslashes, quotes and newlines so a product name can never break the JSON output.orderwrites every line and every amount.BigDecimal.toString()prints599.00with both decimals, so clients see exact rupee values.PAIRmatches one"key": valuepair followed by a comma or the end.parseObjectrequires each match to start exactly where the previous one ended, so garbage between pairs is rejected.- Whole numbers become
Longand quoted values becomeString. The handler checks these types, so{"quantity":"two"}is rejected with a clear message.
Route HTTP Requests in the Java E-commerce API
ApiHandler receives every request under /api. It builds a route string such as PUT /api/carts/C1/items/BOOK-JAVA, matches it against regular expressions, calls the Shop and converts any exception into a JSON error.
package com.gocourse.shop;
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.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Routes every /api request to the Shop and turns results and errors into JSON. */
public class ApiHandler implements HttpHandler {
private static final Pattern PRODUCT = Pattern.compile("/api/products/([A-Z0-9-]+)");
private static final Pattern CART = Pattern.compile("/api/carts/(C\\d+)");
private static final Pattern CART_ITEM = Pattern.compile("/api/carts/(C\\d+)/items/([A-Z0-9-]+)");
private static final Pattern CHECKOUT = Pattern.compile("/api/carts/(C\\d+)/checkout");
private static final Pattern ORDER = Pattern.compile("/api/orders/(ORD-\\d+)");
private static final Pattern CANCEL = Pattern.compile("/api/orders/(ORD-\\d+)/cancel");
private final Shop shop;
public ApiHandler(Shop shop) {
this.shop = shop;
}
@Override
public void handle(HttpExchange ex) throws IOException {
try {
route(ex, ex.getRequestMethod() + " " + ex.getRequestURI().getPath());
} catch (ShopException e) {
send(ex, e.status(), Json.error(e.getMessage()));
} catch (IllegalArgumentException | ClassCastException e) {
send(ex, 400, Json.error(e.getMessage()));
} catch (RuntimeException e) {
e.printStackTrace();
send(ex, 500, Json.error("internal error"));
} finally {
ex.close();
}
}
private void route(HttpExchange ex, String route) throws IOException {
Matcher m;
if (route.equals("GET /api/products")) {
String q = query(ex).get("q");
send(ex, 200, Json.array(shop.products(q).stream().map(p -> Json.product(p, shop.stockOf(p.sku()))).toList()));
} else if ((m = match(PRODUCT, route, "GET")) != null) {
send(ex, 200, Json.product(shop.product(m.group(1)), shop.stockOf(m.group(1))));
} else if (route.equals("POST /api/carts")) {
String id = shop.createCart();
ex.getResponseHeaders().set("Location", "/api/carts/" + id);
send(ex, 201, "{\"cartId\":" + Json.quote(id) + "}");
} else if ((m = match(CART_ITEM, route, "PUT")) != null) {
Map<String, Object> body = body(ex);
if (!(body.get("quantity") instanceof Long qty)) throw new IllegalArgumentException("quantity must be a whole number");
shop.setItem(m.group(1), m.group(2), qty.intValue());
send(ex, 200, Json.order(shop.quote(m.group(1), null)));
} else if ((m = match(CART_ITEM, route, "DELETE")) != null) {
shop.setItem(m.group(1), m.group(2), 0);
send(ex, 200, Json.order(shop.quote(m.group(1), null)));
} else if ((m = match(CART, route, "GET")) != null) {
send(ex, 200, Json.order(shop.quote(m.group(1), query(ex).get("coupon"))));
} else if ((m = match(CHECKOUT, route, "POST")) != null) {
Object coupon = body(ex).get("coupon");
Order order = shop.checkout(m.group(1), coupon == null ? null : coupon.toString());
ex.getResponseHeaders().set("Location", "/api/orders/" + order.id());
send(ex, 201, Json.order(order));
} else if ((m = match(ORDER, route, "GET")) != null) {
send(ex, 200, Json.order(shop.order(m.group(1))));
} else if ((m = match(CANCEL, route, "POST")) != null) {
send(ex, 200, Json.order(shop.cancel(m.group(1))));
} else {
send(ex, 404, Json.error("no route for " + route));
}
}
/** Matches "METHOD /path" against a path pattern for one HTTP method. */
private static Matcher match(Pattern path, String route, String method) {
if (!route.startsWith(method + " ")) return null;
Matcher m = path.matcher(route.substring(method.length() + 1));
return m.matches() ? m : null;
}
private static Map<String, Object> body(HttpExchange ex) throws IOException {
String text = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
if (!text.isBlank()) {
String type = ex.getRequestHeaders().getFirst("Content-Type");
if (type == null || !type.startsWith("application/json")) {
throw new IllegalArgumentException("Content-Type must be application/json");
}
}
return Json.parseObject(text);
}
private static Map<String, String> query(HttpExchange ex) {
Map<String, String> params = new java.util.HashMap<>();
String raw = ex.getRequestURI().getRawQuery();
if (raw == null) return params;
for (String pair : raw.split("&")) {
String[] kv = pair.split("=", 2);
params.put(kv[0], kv.length > 1 ? URLDecoder.decode(kv[1], StandardCharsets.UTF_8) : "");
}
return params;
}
static void send(HttpExchange ex, int status, String json) throws IOException {
byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
ex.sendResponseHeaders(status, bytes.length);
try (OutputStream out = ex.getResponseBody()) {
out.write(bytes);
}
}
}
package com.gocourse.shop;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
/** Starts the e-commerce API. */
public class ShopServer {
public static Shop sampleShop() {
Shop shop = new Shop();
shop.addProduct(new Product("BOOK-JAVA", "Java Programming Book", Money.of("599")), 25);
shop.addProduct(new Product("MUG-CODE", "Coder Coffee Mug", Money.of("249.50")), 40);
shop.addProduct(new Product("KB-MECH", "Mechanical Keyboard", Money.of("3499")), 3);
shop.addProduct(new Product("HOODIE-DEV", "Developer Hoodie", Money.of("1199")), 10);
return shop;
}
public static HttpServer start(int port, Shop shop) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/api", new ApiHandler(shop));
server.createContext("/health", ex -> {
ApiHandler.send(ex, 200, "{\"status\":\"UP\"}");
ex.close();
});
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.start();
return server;
}
public static void main(String[] args) throws IOException {
int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));
HttpServer server = start(port, sampleShop());
System.out.println("E-commerce API running on http://localhost:" + server.getAddress().getPort());
Runtime.getRuntime().addShutdownHook(new Thread(() -> server.stop(1)));
}
}
How it works:
match(CART_ITEM, route, "PUT")returns aMatcheronly when both the method and the path match, som.group(1)is the cart id andm.group(2)is the SKU.bodyreads the request body and requiresContent-Type: application/jsonwhenever a body is present.POST /api/cartsandPOST .../checkoutmay have no body at all.- The
catchblocks map errors to status codes:ShopExceptionuses its own status,IllegalArgumentExceptionbecomes400, and anything else becomes500without leaking details to the client. ShopServer.startregisters the handler, adds a/healthendpoint and runs each request on a virtual thread, as in the Java REST API Project.
Test a Full Shopping Session With HttpClient
This demo starts the server on a free port and walks through a real session: search, create a cart, add items, try to buy too many keyboards, preview with a coupon, check out, cancel and check stock.
package com.gocourse.shop;
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;
/** Walks through a full shopping session against the running API. */
public class ShopClientDemo {
static final HttpClient client = HttpClient.newHttpClient();
static String base;
static void call(String method, String path, String json) throws Exception {
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(base + path));
if (json == null) b.method(method, HttpRequest.BodyPublishers.noBody());
else b.header("Content-Type", "application/json").method(method, HttpRequest.BodyPublishers.ofString(json));
HttpResponse<String> r = client.send(b.build(), HttpResponse.BodyHandlers.ofString());
System.out.printf("%s %s -> %d%n %s%n", method, path, r.statusCode(), r.body());
}
public static void main(String[] args) throws Exception {
HttpServer server = ShopServer.start(0, ShopServer.sampleShop());
base = "http://localhost:" + server.getAddress().getPort();
call("GET", "/api/products?q=java", null);
call("POST", "/api/carts", null);
call("PUT", "/api/carts/C1/items/BOOK-JAVA", "{\"quantity\":2}");
call("PUT", "/api/carts/C1/items/MUG-CODE", "{\"quantity\":1}");
call("PUT", "/api/carts/C1/items/KB-MECH", "{\"quantity\":5}");
call("GET", "/api/carts/C1?coupon=WELCOME10", null);
call("POST", "/api/carts/C1/checkout", "{\"coupon\":\"WELCOME10\"}");
call("GET", "/api/products/BOOK-JAVA", null);
call("POST", "/api/carts/C1/checkout", null);
call("POST", "/api/orders/ORD-1001/cancel", null);
call("POST", "/api/orders/ORD-1001/cancel", null);
call("GET", "/api/products/BOOK-JAVA", null);
call("GET", "/api/products/PHONE-X", null);
server.stop(0);
}
}
GET /api/products?q=java -> 200
[{"sku":"BOOK-JAVA","name":"Java Programming Book","price":599.00,"stock":25}]
POST /api/carts -> 201
{"cartId":"C1"}
PUT /api/carts/C1/items/BOOK-JAVA -> 200
{"id":"C1","status":"QUOTE","lines":[{"sku":"BOOK-JAVA","quantity":2,"unitPrice":599.00,"amount":1198.00}],"subtotal":1198.00,"discount":0.00,"shipping":0.00,"gst":215.64,"total":1413.64}
PUT /api/carts/C1/items/MUG-CODE -> 200
{"id":"C1","status":"QUOTE","lines":[{"sku":"BOOK-JAVA","quantity":2,"unitPrice":599.00,"amount":1198.00},{"sku":"MUG-CODE","quantity":1,"unitPrice":249.50,"amount":249.50}],"subtotal":1447.50,"discount":0.00,"shipping":0.00,"gst":260.55,"total":1708.05}
PUT /api/carts/C1/items/KB-MECH -> 409
{"error":"only 3 left of KB-MECH"}
GET /api/carts/C1?coupon=WELCOME10 -> 200
{"id":"C1","status":"QUOTE","lines":[{"sku":"BOOK-JAVA","quantity":2,"unitPrice":599.00,"amount":1198.00},{"sku":"MUG-CODE","quantity":1,"unitPrice":249.50,"amount":249.50}],"subtotal":1447.50,"discount":144.75,"shipping":0.00,"gst":234.50,"total":1537.25}
POST /api/carts/C1/checkout -> 201
{"id":"ORD-1001","status":"PLACED","lines":[{"sku":"BOOK-JAVA","quantity":2,"unitPrice":599.00,"amount":1198.00},{"sku":"MUG-CODE","quantity":1,"unitPrice":249.50,"amount":249.50}],"subtotal":1447.50,"discount":144.75,"shipping":0.00,"gst":234.50,"total":1537.25}
GET /api/products/BOOK-JAVA -> 200
{"sku":"BOOK-JAVA","name":"Java Programming Book","price":599.00,"stock":23}
POST /api/carts/C1/checkout -> 404
{"error":"cart C1 not found"}
POST /api/orders/ORD-1001/cancel -> 200
{"id":"ORD-1001","status":"CANCELLED","lines":[{"sku":"BOOK-JAVA","quantity":2,"unitPrice":599.00,"amount":1198.00},{"sku":"MUG-CODE","quantity":1,"unitPrice":249.50,"amount":249.50}],"subtotal":1447.50,"discount":144.75,"shipping":0.00,"gst":234.50,"total":1537.25}
POST /api/orders/ORD-1001/cancel -> 409
{"error":"order ORD-1001 is already cancelled"}
GET /api/products/BOOK-JAVA -> 200
{"sku":"BOOK-JAVA","name":"Java Programming Book","price":599.00,"stock":25}
GET /api/products/PHONE-X -> 404
{"error":"product PHONE-X not found"}
How it works:
- The cart preview after each
PUThas statusQUOTEand is priced with the same rules as a real order. - Asking for 5 keyboards fails with
409because only 3 are in stock. The rest of the cart is untouched. - Checkout with
WELCOME10createsORD-1001for ₹1537.25 and reducesBOOK-JAVAstock from 25 to 23. - Checking out the same cart again returns
404, because a cart is deleted after checkout. - Cancelling the order returns the books to stock (back to 25). A second cancel returns
409.
Prevent Overselling During a Flash Sale
The most important rule in an online shop is: never sell stock you do not have. In this test, 20 customers each have one keyboard in their cart and all check out at the same moment, but only 3 keyboards are left.
package com.gocourse.shop;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/** 20 shoppers try to buy the last 3 keyboards at the same moment. */
public class FlashSaleDemo {
public static void main(String[] args) throws Exception {
Shop shop = ShopServer.sampleShop();
List<String> carts = new ArrayList<>();
for (int i = 0; i < 20; i++) {
String cart = shop.createCart();
shop.setItem(cart, "KB-MECH", 1);
carts.add(cart);
}
List<Future<String>> results = new ArrayList<>();
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (String cart : carts) {
results.add(pool.submit(() -> {
try {
return "OK " + shop.checkout(cart, null).id();
} catch (ShopException e) {
return "FAIL " + e.status();
}
}));
}
}
long sold = 0, rejected = 0;
for (Future<String> f : results) {
if (f.get().startsWith("OK")) sold++;
else rejected++;
}
System.out.println("Orders placed: " + sold);
System.out.println("Rejected (409): " + rejected);
System.out.println("Keyboards left: " + shop.stockOf("KB-MECH"));
}
}
Orders placed: 3
Rejected (409): 17
Keyboards left: 0
How it works:
- Each checkout runs on its own virtual thread, so all 20 compete for the same 3 keyboards at once.
- Inside
synchronized (stock), only one checkout at a time can check and subtract stock. The first 3 succeed; the other 17 see a stock of 0 and get409. - Without the lock, two threads could both read "1 left" and both sell it. Checking and subtracting in one locked step is what prevents this race condition.
Note: One shared lock is simple and correct for a single server. A real shop running on many servers keeps stock in a database and uses a transaction or a conditional update such as
UPDATE stock SET qty = qty - 1 WHERE sku = ? AND qty >= 1.
Real-World Example: Run the Shop API and Call It With curl
shop-api/
└── src/
└── com/
└── gocourse/
└── shop/
├── ApiHandler.java
├── Json.java
├── Money.java
├── Order.java
├── Product.java
├── Shop.java
├── ShopException.java
└── ShopServer.java
cd shop-api
javac -d out src/com/gocourse/shop/*.java
jar --create --file shop-api.jar --main-class com.gocourse.shop.ShopServer -C out .
PORT=8080 java -jar shop-api.jar
E-commerce API running on http://localhost:8080
In a second terminal:
$ curl -s http://localhost:8080/health
{"status":"UP"}
$ curl -s -i -X POST http://localhost:8080/api/carts
HTTP/1.1 201 Created
Location: /api/carts/C1
{"cartId":"C1"}
$ curl -s -X PUT http://localhost:8080/api/carts/C1/items/HOODIE-DEV \
-H "Content-Type: application/json" -d '{"quantity":2}'
{"id":"C1","status":"QUOTE","lines":[{"sku":"HOODIE-DEV","quantity":2,"unitPrice":1199.00,"amount":2398.00}],"subtotal":2398.00,"discount":0.00,"shipping":0.00,"gst":431.64,"total":2829.64}
$ curl -s -X PUT http://localhost:8080/api/carts/C1/items/HOODIE-DEV \
-H "Content-Type: application/json" -d '{"quantity":"two"}'
{"error":"quantity must be a whole number"}
$ curl -s -X PUT http://localhost:8080/api/carts/C1/items/HOODIE-DEV -d 'quantity=2'
{"error":"Content-Type must be application/json"}
$ curl -s -X PUT http://localhost:8080/api/carts/C1/items/HOODIE-DEV \
-H "Content-Type: application/json" -d '{"quantity":2'
{"error":"body must be a JSON object"}
$ curl -s -X POST http://localhost:8080/api/carts/C1/checkout \
-H "Content-Type: application/json" -d '{"coupon":"FESTIVE20"}'
{"id":"ORD-1001","status":"PLACED","lines":[{"sku":"HOODIE-DEV","quantity":2,"unitPrice":1199.00,"amount":2398.00}],"subtotal":2398.00,"discount":479.60,"shipping":0.00,"gst":345.31,"total":2263.71}
$ curl -s http://localhost:8080/api/products
[{"sku":"BOOK-JAVA","name":"Java Programming Book","price":599.00,"stock":25},{"sku":"HOODIE-DEV","name":"Developer Hoodie","price":1199.00,"stock":8},{"sku":"KB-MECH","name":"Mechanical Keyboard","price":3499.00,"stock":3},{"sku":"MUG-CODE","name":"Coder Coffee Mug","price":249.50,"stock":40}]
$ curl -s -X PATCH http://localhost:8080/api/orders/ORD-1001
{"error":"no route for PATCH /api/orders/ORD-1001"}
How it works:
- Health check.
/healthlets a load balancer or Docker confirm the service is running. - Cart creation.
POST /api/cartsreturns201 Createdwith aLocationheader pointing to the new cart. - Clear validation. A quantity sent as text, a form-encoded body and a cut-off JSON body all return
400with a message that says what to fix. - Checkout with a coupon.
FESTIVE20takes 20% off ₹2398.00, which is ₹479.60. GST is 18% of ₹1918.40 = ₹345.31, so the total is ₹2263.71. - Stock updates. The product list now shows 8 hoodies instead of 10.
- Unknown routes. A method or path the API does not support returns
404with the route in the message.
The data lives in memory, so it resets when the server stops. To keep products and orders in a database, combine this service with JDBC transactions or Spring Data JPA from the earlier lessons.