Java E-commerce API

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

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.

MethodURLActionSuccess status
GET/api/productsList products (optional ?q= search)200 OK
GET/api/products/{sku}Get one product with its stock200 OK
POST/api/cartsCreate an empty cart201 Created + Location
PUT/api/carts/{id}/items/{sku}Set the quantity of a product in the cart200 OK
DELETE/api/carts/{id}/items/{sku}Remove a product from the cart200 OK
GET/api/carts/{id}Price the cart (optional ?coupon=)200 OK
POST/api/carts/{id}/checkoutPlace an order from the cart201 Created + Location
GET/api/orders/{id}Get an order200 OK
POST/api/orders/{id}/cancelCancel an order and return its stock200 OK

Errors always use the same JSON shape, {"error":"..."}, with a status code that tells the client what went wrong:

StatusWhen
400 Bad RequestInvalid JSON, wrong field type, bad quantity, unknown coupon, empty cart
404 Not FoundUnknown product, cart, order or URL
409 ConflictNot enough stock, or an order that is already cancelled
500 Internal Server ErrorAn unexpected bug

Note: PUT sets 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) turns 599 into 599.00 and 345.312 into 345.31, so every amount looks and compares the same way.
  • percent multiplies first and divides second, then rounds once. Rounding only at the end avoids small errors that add up across many lines.
  • The Product constructor 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 example 599.00 x 2 = 1198.00.
  • cancelled() and asQuote() return a new record with a different status, because records cannot be changed.
  • ShopException carries an HTTP status with the message. The service throws new 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:

RuleValue
CouponsWELCOME10 = 10% off, FESTIVE20 = 20% off (case-insensitive)
Shipping₹49, free when the amount after discount is ₹999 or more
GST18% of the amount after discount
Quantity per product1 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. setItem checks that the product exists, that the quantity is between 0 and 10 and that enough stock is available. Quantity 0 removes the product.
  • price is 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.
  • checkout prices the cart first, so an unknown coupon fails with 400 before any stock changes. Inside synchronized (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.
  • cancel adds the quantities back to stock and marks the order CANCELLED. Cancelling twice returns 409, 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 ShopException with status 400.

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:

  • quote escapes backslashes, quotes and newlines so a product name can never break the JSON output.
  • order writes every line and every amount. BigDecimal.toString() prints 599.00 with both decimals, so clients see exact rupee values.
  • PAIR matches one "key": value pair followed by a comma or the end. parseObject requires each match to start exactly where the previous one ended, so garbage between pairs is rejected.
  • Whole numbers become Long and quoted values become String. 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 a Matcher only when both the method and the path match, so m.group(1) is the cart id and m.group(2) is the SKU.
  • body reads the request body and requires Content-Type: application/json whenever a body is present. POST /api/carts and POST .../checkout may have no body at all.
  • The catch blocks map errors to status codes: ShopException uses its own status, IllegalArgumentException becomes 400, and anything else becomes 500 without leaking details to the client.
  • ShopServer.start registers the handler, adds a /health endpoint 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 PUT has status QUOTE and is priced with the same rules as a real order.
  • Asking for 5 keyboards fails with 409 because only 3 are in stock. The rest of the cart is untouched.
  • Checkout with WELCOME10 creates ORD-1001 for ₹1537.25 and reduces BOOK-JAVA stock 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 get 409.
  • 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:

  1. Health check. /health lets a load balancer or Docker confirm the service is running.
  2. Cart creation. POST /api/carts returns 201 Created with a Location header pointing to the new cart.
  3. Clear validation. A quantity sent as text, a form-encoded body and a cut-off JSON body all return 400 with a message that says what to fix.
  4. Checkout with a coupon. FESTIVE20 takes 20% off ₹2398.00, which is ₹479.60. GST is 18% of ₹1918.40 = ₹345.31, so the total is ₹2263.71.
  5. Stock updates. The product list now shows 8 hoodies instead of 10.
  6. Unknown routes. A method or path the API does not support returns 404 with 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.

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 E-commerce API and get answers drawn from it.

Signed-in readers only.