Skip to lesson

Parsing responses with Jackson

The ShopLite API sends JSON text, but your screens want a Product or a page of products, not strings. Mapping the text to records once keeps the rest of the program simple.

Mapping a JSON body to a record

A response DTO (data transfer object) is a record that mirrors the JSON an API sends, such as Product. Jackson fills it by matching each JSON property to the record component with the same name.

jsonMapper.readValue(response.body(), Product.class) reads the JSON text into a Product record. Check the status first, then map the body.

Example 1 · One product: JSON body to a record

Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind)

RecordMappingDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.math.BigDecimal;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.time.Duration;import tools.jackson.databind.json.JsonMapper;
/** The JSON shape of one product, as the API sends it (a response DTO). */record Product(int id, String sku, String name, String category, BigDecimal price, int stock) {}
class ShopApi {    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/products/4", exchange -> {            byte[] body = """                    {"id":4,"sku":"LAP-IPS3","name":"Lenovo IdeaPad Slim 3","category":"Laptops",\                    "price":42990.00,"stock":12}""".getBytes(StandardCharsets.UTF_8);            exchange.getResponseHeaders().set("Content-Type", "application/json");            exchange.sendResponseHeaders(200, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        server.start();        return server;    }}
public class RecordMappingDemo {    private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();    private static final JsonMapper JSON = JsonMapper.builder().build();
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = ShopApi.start();        URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products/4");        try {            HttpRequest request = HttpRequest.newBuilder(uri)                    .header("Accept", "application/json")                    .timeout(Duration.ofSeconds(3))                    .build();            HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());            if (response.statusCode() != 200) {                throw new IllegalStateException("GET " + uri.getPath() + " failed with " + response.statusCode());            }
            Product laptop = JSON.readValue(response.body(), Product.class);   // JSON text -> record            System.out.println(laptop);            System.out.println(laptop.name() + " costs Rs. " + laptop.price());            BigDecimal stockValue = laptop.price().multiply(BigDecimal.valueOf(laptop.stock()));            System.out.println("Stock value: Rs. " + stockValue);        } finally {            server.stop(0);        }    }}
Output
Product[id=4, sku=LAP-IPS3, name=Lenovo IdeaPad Slim 3, category=Laptops, price=42990.00, stock=12]
Lenovo IdeaPad Slim 3 costs Rs. 42990.00
Stock value: Rs. 515880.00

What this code does

  • The status is checked first; only then does JSON.readValue(response.body(), Product.class) turn the text into a Product record.
  • The price arrives as a BigDecimal, so multiply gives the exact stock value 515880.00, with no double rounding.

A property such as "price":42990.00 fills BigDecimal price exactly. Splitting strings or using indexOf("price") breaks on spacing, nesting and escaping, and gives you Strings instead of numbers. Jackson parses real JSON and checks types: "price":"cheap" fails clearly instead of becoming a wrong number later.

Two rules keep this safe. Check the status before readValue, because a 404 body has a different shape. And build one JsonMapper for the whole app, like the HttpClient: it is thread-safe and expensive to create.

All examples in this lesson need Jackson 3 (tools.jackson.core:jackson-databind), set up as in the JSON and Jackson module. Jackson 3 exceptions are unchecked (JacksonException extends RuntimeException), so readValue needs no throws.

Lists and paged responses with TypeReference

TypeReference is a Jackson class that keeps a full generic type such as List<Category> at run time, so Jackson builds the right item type inside the list.

List<Category>.class is not valid Java, so pass new TypeReference<List<Category>>() { } to readValue. The same works for Page<Product>.

Example 2 · A list and a page with TypeReference

Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind)

PagedListDemo.javaJava
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.math.BigDecimal;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.List;import tools.jackson.core.type.TypeReference;import tools.jackson.databind.json.JsonMapper;
record Category(int id, String name) {}
record ProductSummary(int id, String name, BigDecimal price) {}
/** One page of a longer list, the envelope every ShopLite list endpoint uses (page starts at 0). */record Page<T>(List<T> content, int page, int size, long totalElements, int totalPages) {}
class ShopApi {    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/categories", exchange -> reply(exchange,                "[{\"id\":5,\"name\":\"Books\"},{\"id\":6,\"name\":\"Fashion\"}]"));        server.createContext("/api/v1/products", exchange -> reply(exchange, """                {"content":[{"id":9,"name":"Clean Code","price":499.00},\                {"id":10,"name":"The Pragmatic Programmer","price":650.00}],\                "page":0,"size":2,"totalElements":3,"totalPages":2}"""));        server.start();        return server;    }
    static void reply(HttpExchange exchange, String json) throws IOException {        byte[] body = json.getBytes(StandardCharsets.UTF_8);        exchange.getResponseHeaders().set("Content-Type", "application/json");        exchange.sendResponseHeaders(200, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }}
public class PagedListDemo {    private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();    private static final JsonMapper JSON = JsonMapper.builder().build();    private static final TypeReference<List<Category>> CATEGORY_LIST = new TypeReference<>() { };    private static final TypeReference<Page<ProductSummary>> PRODUCT_PAGE = new TypeReference<>() { };
    static String get(String url) throws IOException, InterruptedException {        HttpRequest request = HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(3)).build();        return CLIENT.send(request, HttpResponse.BodyHandlers.ofString()).body();   // status check left out to keep it short    }
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = ShopApi.start();        String base = "http://127.0.0.1:" + server.getAddress().getPort();        try {            List<Category> categories = JSON.readValue(get(base + "/api/v1/categories"), CATEGORY_LIST);            System.out.println("Categories: " + categories);
            Page<ProductSummary> page = JSON.readValue(get(base + "/api/v1/products?category=5&page=0&size=2"), PRODUCT_PAGE);            System.out.println("Page " + (page.page() + 1) + " of " + page.totalPages() + ", showing "                    + page.content().size() + " of " + page.totalElements());            for (ProductSummary p : page.content()) {                System.out.println("  " + p.id() + " " + p.name() + " Rs. " + p.price());            }        } finally {            server.stop(0);        }    }}
Output
Categories: [Category[id=5, name=Books], Category[id=6, name=Fashion]]
Page 1 of 2, showing 2 of 3
  9 Clean Code Rs. 499.00
  10 The Pragmatic Programmer Rs. 650.00

What this code does

  • TypeReference<List<Category>> and TypeReference<Page<ProductSummary>> keep the full generic type, so the lists hold real records.
  • The two type references are static final fields, created once and reused like the client and the mapper.
  • Page<T> is one generic record for every list endpoint; only the item type changes.

Example 3 · Mistake: List.class gives maps, not records

Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind)

ListClassMistakeDemo.javaJava
import java.util.List;import tools.jackson.core.type.TypeReference;import tools.jackson.databind.json.JsonMapper;
record Category(int id, String name) {}
public class ListClassMistakeDemo {    private static final JsonMapper JSON = JsonMapper.builder().build();
    @SuppressWarnings("unchecked")    public static void main(String[] args) {        String body = "[{\"id\":5,\"name\":\"Books\"},{\"id\":6,\"name\":\"Fashion\"}]";   // as the API sent it
        List<Category> wrong = JSON.readValue(body, List.class);          // compiles: an unchecked conversion        System.out.println("Looks fine: " + wrong);        try {            Category first = wrong.get(0);            System.out.println(first.name());        } catch (ClassCastException e) {            System.out.println("ClassCastException: " + e.getMessage());        }
        List<Category> right = JSON.readValue(body, new TypeReference<List<Category>>() { });        System.out.println("With TypeReference: " + right.get(0).name());    }}
Output
Looks fine: [{id=5, name=Books}, {id=6, name=Fashion}]
ClassCastException: class java.util.LinkedHashMap cannot be cast to class Category (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; Category is in unnamed module of loader 'app')
With TypeReference: Books

What this code does

  • With List.class, Jackson does not know the item type, so each item becomes a LinkedHashMap. Printing looks fine, which hides the bug.
  • The first line that treats an item as a Category throws ClassCastException. The TypeReference version returns real Category records.

Page<Product> is the page envelope ShopLite designed for every list endpoint: content, page (counted from 0), size, totalElements and totalPages. The common mistake is readValue(body, List.class): it compiles, and printing the list even looks right, but each item is a LinkedHashMap, and the first Category c = list.get(0) throws ClassCastException, far from the line that caused it.

A TypeReference is an object, so keep it in a static final field and reuse it, like the mapper.

Find the bug

Find the wrong readValue

Each snippet reads JSON into a generic type. Click the line that causes the bug.

The list prints fine, but a later line crashes. Which line is the cause?

Round 1 of 2

Reading a Problem Details error body

Problem Details (RFC 9457) is the standard JSON shape for API errors: type, title, status, detail and instance, sent with the media type application/problem+json.

ShopLite also adds an errors list of {field, message} pairs for validation failures. One Problem record reads the whole error body.

Example 4 · Not found and validation errors as Problem records

Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind)

ProblemDetailsDemo.javaJava
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.List;import tools.jackson.databind.json.JsonMapper;
/** One invalid field in a validation error. */record FieldError(String field, String message) {}
/** RFC 9457 Problem Details, plus the "errors" list ShopLite adds for validation. */record Problem(String type, String title, int status, String detail, String instance, List<FieldError> errors) {}
class ShopApi {    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/products/99", exchange -> reply(exchange, 404, """                {"type":"about:blank","title":"Not Found","status":404,\                "detail":"No product with id 99","instance":"/api/v1/products/99"}"""));        server.createContext("/api/v1/products", exchange -> {            exchange.getRequestBody().readAllBytes();            reply(exchange, 400, """                    {"type":"about:blank","title":"Bad Request","status":400,\                    "detail":"2 fields are invalid","instance":"/api/v1/products",\                    "errors":[{"field":"price","message":"must be greater than 0"},\                    {"field":"sku","message":"must not be blank"}]}""");        });        server.start();        return server;    }
    static void reply(HttpExchange exchange, int status, String json) throws IOException {        byte[] body = json.getBytes(StandardCharsets.UTF_8);        exchange.getResponseHeaders().set("Content-Type", "application/problem+json");        exchange.sendResponseHeaders(status, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }}
public class ProblemDetailsDemo {    private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();    private static final JsonMapper JSON = JsonMapper.builder().build();
    static void call(HttpRequest request) throws IOException, InterruptedException {        HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());        String type = response.headers().firstValue("Content-Type").orElse("");        System.out.println(request.method() + " " + request.uri().getPath() + " -> " + response.statusCode());        if (response.statusCode() >= 400 && type.startsWith("application/problem+json")) {            Problem problem = JSON.readValue(response.body(), Problem.class);            System.out.println("  " + problem.title() + ": " + problem.detail());            if (problem.errors() != null) {                              // only validation errors have it                for (FieldError error : problem.errors()) {                    System.out.println("  - " + error.field() + " " + error.message());                }            }        }    }
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = ShopApi.start();        String base = "http://127.0.0.1:" + server.getAddress().getPort();        try {            call(HttpRequest.newBuilder(URI.create(base + "/api/v1/products/99")).timeout(Duration.ofSeconds(3)).build());            call(HttpRequest.newBuilder(URI.create(base + "/api/v1/products"))                    .header("Content-Type", "application/json")                    .POST(HttpRequest.BodyPublishers.ofString("{\"sku\":\"\",\"name\":\"Pen\",\"price\":0}"))                    .timeout(Duration.ofSeconds(3))                    .build());        } finally {            server.stop(0);        }    }}
Output
GET /api/v1/products/99 -> 404
  Not Found: No product with id 99
POST /api/v1/products -> 400
  Bad Request: 2 fields are invalid
  - price must be greater than 0
  - sku must not be blank

What this code does

  • The error body is read only for 4xx/5xx with application/problem+json, so an HTML error page never reaches the JSON parser.
  • The 404 has no errors field, so that component is null; the 400 validation error lists each bad field with its message.

The detail text is written for humans ("No product with id 99", "SKU BK-CLEAN already exists"), so your app can show a useful message instead of a bare status code, and the field errors can be shown next to the right input box in a form. A record such as Problem(String type, String title, int status, String detail, String instance, List<FieldError> errors) reads all of it.

Read the error body only when the status is 4xx or 5xx and Content-Type says problem+json. A proxy or gateway in front of the API may send an HTML page for 502, and parsing that as JSON throws a second, confusing error.

Ignoring unknown fields

A tolerant reader is a client that reads only the fields it needs and ignores any others, so a new field added to the API does not break it.

An unknown field is a JSON property your record does not have, such as "rating" added later. Put @JsonIgnoreProperties(ignoreUnknown = true) on response records to state the intent.

Example 5 · An API adds fields: default, strict and annotated

Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind)

UnknownFieldsDemo.javaJava
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import java.math.BigDecimal;import tools.jackson.core.JacksonException;import tools.jackson.databind.DeserializationFeature;import tools.jackson.databind.json.JsonMapper;
record Product(int id, String name, BigDecimal price) {}
@JsonIgnoreProperties(ignoreUnknown = true)                    // this class always ignores extra fieldsrecord TolerantProduct(int id, String name, BigDecimal price) {}
public class UnknownFieldsDemo {    public static void main(String[] args) {        // Version 1.1 of the API added "rating" and "tags". Our records do not know them.        String body = "{\"id\":9,\"name\":\"Clean Code\",\"price\":499.00,\"rating\":4.6,\"tags\":[\"coding\"]}";
        JsonMapper defaults = JsonMapper.builder().build();        System.out.println("Jackson 3 default:  " + defaults.readValue(body, Product.class));
        JsonMapper strict = JsonMapper.builder()                .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)   // the Jackson 2 default                .build();        try {            strict.readValue(body, Product.class);        } catch (JacksonException e) {            System.out.println("Strict mapper:      " + e.getOriginalMessage().lines().findFirst().orElse(""));        }        System.out.println("Strict + annotated: " + strict.readValue(body, TolerantProduct.class));    }}
Output
Jackson 3 default:  Product[id=9, name=Clean Code, price=499.00]
Strict mapper:      Unrecognized property "rating" (class Product), not marked as ignorable
Strict + annotated: TolerantProduct[id=9, name=Clean Code, price=499.00]

What this code does

  • The Jackson 3 default mapper ignores the new rating and tags fields and fills the record.
  • A mapper with FAIL_ON_UNKNOWN_PROPERTIES on (the Jackson 2 default) fails on rating. The record with @JsonIgnoreProperties(ignoreUnknown = true) still works even with that strict mapper.

In Jackson 3 the default is to ignore unknown fields (FAIL_ON_UNKNOWN_PROPERTIES is off). In Jackson 2, which much older code uses, it was on, and every new field crashed the client with UnrecognizedPropertyException. The annotation keeps the intent clear and safe under any mapper setting. APIs grow, and adding a field is a non-breaking change for the server, so a client that reads only what it needs keeps working.

Missing fields are different. In Jackson 3, a missing int component fails by default (Cannot map null into type int), while a missing String or Integer becomes null. Use wrapper types for fields the API may leave out, and check what you require.

A small typed API client class

A typed client is a class whose methods look like the API in Java terms, such as find(int id) and list(int page, int size). Inside, it builds requests, checks the status and maps the JSON; callers never see URLs or JSON.

Give the class the HttpClient, the JsonMapper and the base URL through its constructor, and let it hide every request detail from its callers.

Example 6 · ProductClient: the API as Java methods

Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind)

ProductClientDemo.javaJava
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.math.BigDecimal;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.List;import java.util.Optional;import tools.jackson.core.type.TypeReference;import tools.jackson.databind.json.JsonMapper;
record Product(int id, String sku, String name, BigDecimal price, int stock) {}
record NewProduct(String sku, String name, int categoryId, BigDecimal price, int stock) {}
record Page<T>(List<T> content, int page, int size, long totalElements, int totalPages) {}
record Problem(String title, int status, String detail) {}
/** Any error answer from the API, with the server's own explanation. */class ApiException extends RuntimeException {    private final int status;
    ApiException(int status, String message) {        super(message);        this.status = status;    }
    int status() {        return status;    }}
/** The ShopLite products API as plain Java methods. Callers never see HTTP or JSON. */class ProductClient {    private static final Duration TIMEOUT = Duration.ofSeconds(3);    private static final TypeReference<Page<Product>> PRODUCT_PAGE = new TypeReference<>() { };
    private final HttpClient http;    private final JsonMapper json;    private final URI baseUrl;
    ProductClient(HttpClient http, JsonMapper json, URI baseUrl) {        this.http = http;        this.json = json;        this.baseUrl = baseUrl;    }
    Optional<Product> find(int id) throws IOException, InterruptedException {        HttpResponse<String> response = send(get("/api/v1/products/" + id));        if (response.statusCode() == 404) {            return Optional.empty();                                    // "not found" is a normal answer here        }        return Optional.of(json.readValue(requireSuccess(response), Product.class));    }
    Page<Product> list(int page, int size) throws IOException, InterruptedException {        HttpResponse<String> response = send(get("/api/v1/products?page=" + page + "&size=" + size));        return json.readValue(requireSuccess(response), PRODUCT_PAGE);    }
    Product create(NewProduct product) throws IOException, InterruptedException {        HttpRequest request = HttpRequest.newBuilder(baseUrl.resolve("/api/v1/products"))                .header("Content-Type", "application/json")                .header("Accept", "application/json")                .timeout(TIMEOUT)                .POST(HttpRequest.BodyPublishers.ofString(json.writeValueAsString(product)))                .build();        return json.readValue(requireSuccess(send(request)), Product.class);    }
    private HttpRequest get(String path) {        return HttpRequest.newBuilder(baseUrl.resolve(path))                .header("Accept", "application/json")                .timeout(TIMEOUT)                .build();    }
    private HttpResponse<String> send(HttpRequest request) throws IOException, InterruptedException {        return http.send(request, HttpResponse.BodyHandlers.ofString());    }
    /** The body of a 2xx answer; otherwise an ApiException with the Problem Details text. */    private String requireSuccess(HttpResponse<String> response) {        int status = response.statusCode();        if (status >= 200 && status < 300) {            return response.body();        }        String detail = response.headers().firstValue("Content-Type").orElse("").startsWith("application/problem+json")                ? json.readValue(response.body(), Problem.class).detail()                : "HTTP " + status;        throw new ApiException(status, response.request().method() + " " + response.uri().getPath() + ": " + detail);    }}
/** Stand-in API: products 1 and 9, a page of two, and a 409 for a duplicate SKU. */class ShopApi {    static HttpServer start() throws IOException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/products", exchange -> {            String path = exchange.getRequestURI().getPath();            exchange.getRequestBody().readAllBytes();            if (exchange.getRequestMethod().equals("POST")) {                reply(exchange, 409, "application/problem+json",                        "{\"title\":\"Conflict\",\"status\":409,\"detail\":\"SKU BK-CLEAN already exists\"}");            } else if (path.equals("/api/v1/products")) {                reply(exchange, 200, "application/json", "{\"content\":["                        + "{\"id\":1,\"sku\":\"MOB-RN13\",\"name\":\"Redmi Note 13 5G\",\"price\":17999.00,\"stock\":40},"                        + "{\"id\":9,\"sku\":\"BK-CLEAN\",\"name\":\"Clean Code\",\"price\":499.00,\"stock\":30}],"                        + "\"page\":0,\"size\":2,\"totalElements\":14,\"totalPages\":7}");            } else if (path.equals("/api/v1/products/9")) {                reply(exchange, 200, "application/json",                        "{\"id\":9,\"sku\":\"BK-CLEAN\",\"name\":\"Clean Code\",\"price\":499.00,\"stock\":30}");            } else {                reply(exchange, 404, "application/problem+json",                        "{\"title\":\"Not Found\",\"status\":404,\"detail\":\"No such product\"}");            }        });        server.start();        return server;    }
    static void reply(HttpExchange exchange, int status, String type, String json) throws IOException {        byte[] body = json.getBytes(StandardCharsets.UTF_8);        exchange.getResponseHeaders().set("Content-Type", type);        exchange.sendResponseHeaders(status, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }}
public class ProductClientDemo {    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = ShopApi.start();        HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build();        JsonMapper json = JsonMapper.builder().build();        ProductClient products = new ProductClient(http, json,                URI.create("http://127.0.0.1:" + server.getAddress().getPort()));        try {            System.out.println("find(9):  " + products.find(9).map(Product::name).orElse("not found"));            System.out.println("find(99): " + products.find(99).map(Product::name).orElse("not found"));
            Page<Product> page = products.list(0, 2);            System.out.println("list(0, 2): " + page.content().size() + " of " + page.totalElements() + " products");
            try {                products.create(new NewProduct("BK-CLEAN", "Clean Code", 5, new BigDecimal("499.00"), 5));            } catch (ApiException e) {                System.out.println("create: " + e.status() + " " + e.getMessage());            }        } finally {            server.stop(0);        }    }}
Output
find(9):  Clean Code
find(99): not found
list(0, 2): 2 of 14 products
create: 409 POST /api/v1/products: SKU BK-CLEAN already exists

What this code does

  • ProductClient gets the client, mapper and base URL through its constructor. Every request has a timeout and every response goes through requireSuccess.
  • find returns Optional.empty() for 404, because "no such product" is a normal answer. Other errors become an ApiException that carries the server's detail, as with the duplicate SKU.
  • main only calls find, list and create; it contains no URL, status code or JSON.

Without a typed client, every screen repeats the same ten lines of request building and status checks, and each copy forgets something: a timeout here, a status check there. With one class the rules live in one place, a change such as a new header or a longer timeout is one edit, and the class is easy to test against a fake server.

Passing the dependencies through the constructor, never creating them inside, lets the whole app share one client and mapper, and lets tests pass in a different base URL.

baseUrl.resolve("/api/v1/products") keeps the scheme, host and port and replaces the path, so the base URL should be just http://host:port.

Next step

Check your understanding

12 quick questions