Home / Blog / Wrap an Amazon Product API in a Spring Boot Microservice: Caching and Bean Validation

Wrap an Amazon Product API in a Spring Boot Microservice: Caching and Bean Validation

Wrap the SellerMagnet API in a small Spring Boot microservice: a jakarta bean-validation constraint validates the ASIN and marketplace before any network call, a short-lived in-process cache answers repeat lookups for free, and the Java quickstart's own ApiClient.java and Retry.java are reused with only a package line added. Every scenario is run against a real embedded Spring Boot app and a fails-closed fake HTTP server, not described by hand.

December 02, 2026
9 min read
SellerMagnet Team
Share & Bookmark
Code editor showing a Spring Boot controller validating a lookup request with a bean constraint before any network call

A Spring Boot microservice in front of the SellerMagnet API validates every request with a jakarta bean-validation constraint before it can spend a credit, answers repeat lookups from a short-lived in-process cache, and retries only the status codes a second attempt can fix. This guide builds that wrapper - LookupRequest.java, a custom @KnownMarketplace constraint, TTLCache.java, LookupResponse.java and LookupController.java are new, and the Java quickstart's own ApiClient.java, Retry.java and the ProductLookup/BuyBoxInfo records from its Lookup.java are reused (the client/retry files need only a package line added; Lookup.java is reused completely unchanged) - and tests all of it against a real embedded Spring Boot app and a fails-closed fake HTTP server so nothing here is just described.

Key Takeaways

  • Validate asin and marketplaceId with jakarta bean validation before the upstream call, so a bad request costs nothing and waits on no timeout.
  • A small in-process TTLCache answers a repeated lookup for free; it lives in one JVM, so several replicas behind a load balancer each keep their own copy unless you add a shared store.
  • ApiClient.java and Retry.java from the Java quickstart are reused with ONE mechanical change: a package line, needed because Spring Boot's component scan breaks when its own @SpringBootApplication class sits in the default package; Lookup.java (ProductLookup/BuyBoxInfo) is reused completely unchanged, and LookupResponse.java is the one new, trimmed response DTO the controller and cache actually hold.
  • The retry policy is the quickstart's own: 429 waits for free, a 500 is retried once (it is refunded), 502/503 are retried up to 4 times (each billed), and a 404 is a real answer, never retried.
  • java.net.ConnectException (the connection never completed - free) and java.net.http.HttpTimeoutException (the request reached the server before the client gave up - billed, not refunded) need separate catch clauses, or a dropped connection reaches the client as an unhandled 500.

Why wrap the API in a microservice instead of calling it directly?

A thin service in front of the API gives every caller in a larger system one place that enforces the request shape, one cache for ASINs several callers ask for repeatedly, and one retry policy, instead of each caller reimplementing the Java quickstart's ApiClient.java and Retry.java on its own. This post reuses that exact client and retry helper almost unchanged - java.net.http.HttpClient and a hand-rolled JSON reader need nothing async-specific to sit behind a Spring MVC controller, so there is no reactive sibling to maintain here.

pom.xml - parent spring-boot-starter-parent, two starters

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Environment and run

export SELLERMAGNET_API_KEY="your-key-here"
mvn spring-boot:run

How do I validate the ASIN and marketplace before spending a credit?

Put the shape checks on a request DTO and validate it before any network call. An ASIN is always 10 upper-case letters or digits, checked with a plain @Pattern; the marketplace ID must be one this wrapper actually supports (the full list of all 23 marketplace IDs is in the marketplace IDs list), which needs its own constraint since bean validation has no built-in "is this value in a set" annotation. A record cannot rewrite its own fields once built, so the controller trims and upper-cases the raw input BEFORE constructing LookupRequest, the same normalize-then-validate order the Python quickstart's own validator uses.

LookupRequest.java - validated before any network call

package com.sellermagnet.wrapper;

import jakarta.validation.constraints.Pattern;

/**
 * Request DTO for a lookup, validated with jakarta bean-validation annotations
 * before any network call - a bad ASIN or an unsupported marketplace never
 * reaches {@code ApiClient}, so it never spends a credit and never waits on
 * the 120-second timeout. Normalizing (trim/upper-case) happens in
 * {@link LookupController} BEFORE this record is built, since a record's
 * fields cannot rewrite themselves once constructed.
 */
public record LookupRequest(
        @Pattern(regexp = "^[A-Z0-9]{10}$", message = "asin must be 10 upper-case letters/digits")
        String asin,

        @KnownMarketplace
        String marketplaceId) {
}

KnownMarketplace.java, KnownMarketplaceValidator.java, MarketplaceIds.java - a custom bean-validation constraint

package com.sellermagnet.wrapper;

import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Bean-validation constraint: the marketplace ID must be one this wrapper
 * actually supports. The full list of all 23 marketplace IDs is in
 * https://sellermagnet-api.com/blog/amazon-marketplace-ids-list - this
 * wrapper only turns on the handful in {@link MarketplaceIds}.
 */
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = KnownMarketplaceValidator.class)
public @interface KnownMarketplace {
    String message() default "unknown marketplaceId";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

package com.sellermagnet.wrapper;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

public final class KnownMarketplaceValidator implements ConstraintValidator<KnownMarketplace, String> {
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value != null && MarketplaceIds.SUPPORTED.contains(value);
    }
}

package com.sellermagnet.wrapper;

import java.util.Set;

/**
 * The handful of marketplace IDs this wrapper turns on; the full list of
 * all 23 is in https://sellermagnet-api.com/blog/amazon-marketplace-ids-list
 */
final class MarketplaceIds {
    static final Set<String> SUPPORTED = Set.of(
            "ATVPDKIKX0DER",   // amazon.com
            "A1PA6795UKMFR9",  // amazon.de
            "A1F83G8C2ARO7P",  // amazon.co.uk
            "A13V1IB3VIYZZH"); // amazon.fr

    private MarketplaceIds() {
    }
}

How does the cache avoid paying twice for the same ASIN?

TTLCache wraps a ConcurrentHashMap keyed by "asin:marketplaceId", with each entry carrying its own expiry in System.nanoTime(). A lookup within the TTL (300 seconds here) returns the stored result with cached: true and makes no network call at all; a lookup after the TTL, or for a key never seen, falls through to the upstream call and refreshes the entry. This cache lives in the JVM that holds it: with several Spring Boot replicas behind a load balancer, each one keeps its own copy, so the same ASIN can still be fetched once per replica. That trade-off is deliberate here - a shared cache needs an external store a reader picks for their own deployment, which this post does not assume or name.

TTLCache.java - a per-JVM TTL cache

package com.sellermagnet.wrapper;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * A tiny in-process TTL cache, keyed by "asin:marketplaceId".
 *
 * Not a cross-process cache (no external cache store named here, by the
 * owner's infrastructure rule): one JVM instance holds its own map. Running
 * several replicas behind a load balancer means each keeps its own copy,
 * so the same ASIN can be fetched once per replica within the TTL - a
 * reader running several replicas needs a shared store of their own choice.
 */
final class TTLCache<V> {
    private record Entry<V>(long expiresAtNanos, V value) {
    }

    private final long ttlNanos;
    private final Map<String, Entry<V>> store = new ConcurrentHashMap<>();

    TTLCache(long ttlSeconds) {
        this.ttlNanos = ttlSeconds * 1_000_000_000L;
    }

    V get(String key) {
        Entry<V> hit = store.get(key);
        if (hit == null) {
            return null;
        }
        if (hit.expiresAtNanos() < System.nanoTime()) {
            store.remove(key);
            return null;
        }
        return hit.value();
    }

    void set(String key, V value) {
        store.put(key, new Entry<>(System.nanoTime() + ttlNanos, value));
    }

    int size() {
        return store.size();
    }

    /** Test-only convenience: starts the next scenario from an empty cache. */
    void clear() {
        store.clear();
    }
}

What does the controller itself look like?

ApiClientConfig wires one shared ApiClient bean for the whole application, with its base URL overridable so tests can point it at a local fake instead of the live API - the same constructor seam the Java quickstart's own Main.java already uses. The controller validates the path and query parameters first, checks the cache, and only then calls Retry.withRetry(4, ...) through that shared ApiClient. java.net.ConnectException and java.net.http.HttpTimeoutException are not ApiError - they are thrown by the JDK's HTTP stack itself - so they need their own catch clauses next to ApiError, or a dropped connection reaches the client as an unhandled 500 instead of the wrapper's own 502.

ApiClientConfig.java - one shared ApiClient bean, base URL overridable in tests

package com.sellermagnet.wrapper;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Builds the one shared {@code ApiClient} (unchanged from the Java
 * quickstart) for the whole application. {@code sellermagnet.api.base}
 * defaults to the live API but is overridden in tests to point at
 * {@code FakeServer} instead - the same constructor seam the quickstart's
 * own Main.java already uses to swap in a local server.
 */
@Configuration
class ApiClientConfig {
    @Bean
    ApiClient apiClient(
            @Value("${sellermagnet.api.base:https://sellermagnet-api.com/api/}") String base,
            @Value("${sellermagnet.api.key:${SELLERMAGNET_API_KEY:}}") String apiKey) {
        return new ApiClient(base, apiKey);
    }

    @Bean
    TTLCache<LookupResponse> lookupCache(
            @Value("${sellermagnet.cache.ttl-seconds:300}") long ttlSeconds) {
        return new TTLCache<>(ttlSeconds);
    }
}

LookupController.java - the Spring Boot microservice

package com.sellermagnet.wrapper;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.ConnectException;
import java.net.http.HttpConnectTimeoutException;
import java.net.http.HttpTimeoutException;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * The Spring Boot microservice wrapping the SellerMagnet API's product
 * lookup. Validates the request (LookupRequest, bean-validated) before any
 * network call, serves repeat lookups from a short-lived in-process cache,
 * and only then calls the upstream API through the reused {@code ApiClient}
 * / {@code Retry} from the Java quickstart, unchanged.
 */
@RestController
class LookupController {
    private final ApiClient client;
    private final Validator validator;
    private final TTLCache<LookupResponse> cache;

    LookupController(ApiClient client, Validator validator, TTLCache<LookupResponse> cache) {
        this.client = client;
        this.validator = validator;
        this.cache = cache;
    }

    @GetMapping("/lookup/{asin}")
    ResponseEntity<?> lookup(@PathVariable String asin, @RequestParam String marketplaceId) {
        // Normalize BEFORE validating/constructing the record: a record's fields
        // cannot rewrite themselves once built, so trim/upper happens here, the
        // same step the Python quickstart's own validator takes before constructing
        // its own request object.
        String normalizedAsin = asin == null ? "" : asin.strip().toUpperCase();
        String normalizedMarketplace = marketplaceId == null ? "" : marketplaceId.strip();
        LookupRequest request = new LookupRequest(normalizedAsin, normalizedMarketplace);

        Set<ConstraintViolation<LookupRequest>> violations = validator.validate(request);
        if (!violations.isEmpty()) {
            List<Map<String, String>> detail = violations.stream()
                    .map(v -> Map.of(
                            "loc", v.getPropertyPath().toString(),
                            "msg", v.getMessage(),
                            "type", v.getConstraintDescriptor().getAnnotation()
                                    .annotationType().getSimpleName()))
                    .toList();
            return ResponseEntity.status(422).body(Map.of("detail", detail)); // no network call made
        }

        String cacheKey = normalizedAsin + ":" + normalizedMarketplace;
        LookupResponse cached = cache.get(cacheKey);
        if (cached != null) {
            return ResponseEntity.ok(new LookupResponse(
                    cached.asin(), cached.title(), cached.price(), cached.currency(), true));
        }

        try {
            Map<String, Object> data = Retry.withRetry(4, () -> client.get(
                    "amazon-product-lookup",
                    Map.of("asin", normalizedAsin, "marketplaceId", normalizedMarketplace)));
            ProductLookup lookup = ProductLookup.fromJson(data);
            LookupResponse fresh = LookupResponse.from(lookup, false);
            cache.set(cacheKey, fresh);
            return ResponseEntity.ok(fresh);
        } catch (ApiError err) {
            if (err.status == 404) {
                return ResponseEntity.status(404).body(Map.of("detail", "asin not found on this marketplace"));
            }
            return ResponseEntity.status(502).body(Map.of("detail", "upstream lookup failed"));
        } catch (ConnectException | HttpConnectTimeoutException neverReachedServer) {
            // The connection itself never completed, so no credit was ever deducted - free.
            return ResponseEntity.status(502).body(Map.of("detail", "upstream unreachable"));
        } catch (HttpTimeoutException clientGaveUpWaiting) {
            // The request DID reach the server before the client's own timeout fired, so the
            // credit was already deducted server-side and is NOT refunded for an abandoned wait
            // (see the SellerMagnet API's credit-timing rule: deduction happens before the
            // upstream call, refunds exist only for a server-side 500, never for a client giveup).
            return ResponseEntity.status(502).body(Map.of("detail", "upstream request timed out"));
        } catch (Exception other) {
            return ResponseEntity.status(502).body(Map.of("detail", "upstream lookup failed"));
        }
    }
}

LookupResponse.java - the new, trimmed response the controller returns and the cache holds

package com.sellermagnet.wrapper;

/**
 * The new, trimmed response the controller returns and the cache holds - built
 * from the quickstart's own ProductLookup/BuyBoxInfo (Lookup.java, reused
 * unchanged) with {@code from(lookup, cached)}, so a cache hit only has to
 * flip one boolean before answering.
 */
record LookupResponse(String asin, String title, Double price, String currency, boolean cached) {
    static LookupResponse from(ProductLookup lookup, boolean cached) {
        return new LookupResponse(
                lookup.asin(), lookup.title(), lookup.buyBoxInfo().price(),
                lookup.buyBoxInfo().currencyCode(), cached);
    }
}

LookupResponse is the one genuinely new response type: a small record with the fields the trimmed JSON below actually shows (asin, title, price, currency, cached), built from the quickstart's own ProductLookup/BuyBoxInfo with LookupResponse.from(lookup, cached). TTLCache<LookupResponse> caches this trimmed shape, not the quickstart's own ProductLookup, so a cache hit only ever has to flip one boolean before answering.

Don't put a Spring Boot app in the default package

The first version of this wrapper kept every class, including Application.java, in the default package, to avoid adding anything to the reused ApiClient.java and Retry.java. It compiled, but every test run failed with a NoClassDefFoundError for an unrelated class, io.r2dbc.spi.ValidationDepth - caught by the test suite, not guessed. @SpringBootApplication's component scan uses the main class's own package as its base package; an empty package name scans the ENTIRE classpath, including Spring's own optional autoconfiguration classes for dependencies that were never added. Moving every class into a real package (com.sellermagnet.wrapper) fixed it; ApiClient.java and Retry.java only needed that one line added, nothing else changed.

A client timeout is not the same as a free connection error

java.net.ConnectException (and HttpConnectTimeoutException) only ever fire when the connection never completed at all (refused, unreachable), so nothing was billed. A java.net.http.HttpTimeoutException is different: it means the request DID reach the server before the client's own 120-second timeout fired, and the SellerMagnet API deducts the credit before the upstream call even starts - so a client that gives up waiting has still paid for an answer it will never see, and that credit is not refunded. ApiClient.java's hardcoded 120-second timeout matches the server's own limit on purpose; cutting it shorter does not save credits, it just means never seeing the answer already paid for.

Terminal flow diagram of a lookup request through bean validation, cache and the upstream API
A cache hit never reaches the upstream API; a cache miss stores the result before answering.

Trimmed response for a cache-miss lookup

{
  "asin": "B0CL61F39H",
  "title": "PlayStation®5 console (slim)",
  "price": 444.99,
  "currency": "USD",
  "cached": false
}
Every scenario the test suite covers, and what each one costs in credits.
ScenarioHTTP statusRetried?Billed?
Valid ASIN, cache miss200-Yes (1 credit)
Same lookup again within 300s200 (cached)noNo - 0 upstream calls
Malformed ASIN shape422noNo - rejected before the network
Unknown marketplaceId422noNo - rejected before the network
Lower-case ASIN, cache miss200-Yes - normalized then looked up
Upstream 404 (not on this marketplace)404noYes - a real answer
Upstream 429 (concurrency cap)200 (after a wait)yes - freeNo - the 429 itself
Upstream 500 (refunded)200 (after 1 retry)yes, capped at 1No - the 500 itself
Two upstream 500s in a row502no - stopsNo - the 500s
Upstream 502 / 503502yes, up to 4 attemptsYes - every attempt
Connection refused (never reached the server)502yes, up to 4 attemptsNo - nothing was billed
Terminal table of every tested scenario, its HTTP status, retry behaviour and credit cost
Every row is a real test against a real embedded Spring Boot app, not a described behaviour.

How do I fake the upstream API without spending credits in every test?

FakeServer.java is the same local com.sun.net.httpserver.HttpServer fake the Java mock-testing guide already built on top of the quickstart's own embedded TestServer.java: install(route) scripts exactly the next response, and the default route (no install) answers 500 "no route installed", so a forgotten scenario fails loudly instead of silently reaching for a plausible empty answer. @SpringBootTest(webEnvironment = RANDOM_PORT) starts a real embedded server and @DynamicPropertySource points sellermagnet.api.base at FakeServer's own random port - the real app, a real HTTP round trip through TestRestTemplate, with only the upstream API faked.

FakeServer.java - reused from the mock-testing-java post, generalizes the quickstart's embedded server

package com.sellermagnet.wrapper;

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

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * FakeServer generalizes the quickstart's own embedded TestServer.java (already shipped in
 * Main.java) into a per-test scriptable fake: install(Route) scripts exactly one response for
 * the next request(s), reset() restores a route that fails closed. ApiClient / Lookup /
 * Statistics / Retry / BatchLookup / Json / ApiError run against it completely unchanged -
 * the test seam is the constructor's own "base" argument, the same one the quickstart's own
 * Main.java already uses to point ApiClient at a local server instead of the live API.
 */
final class FakeServer {

    interface Route {
        /** status, JSON body string, optional Retry-After seconds (0 = not sent) */
        Response handle(String endpoint, Map<String, String> params);
    }

    record Response(int status, String body, int retryAfterSeconds) {
    }

    private static final Route BLOCKED = (endpoint, params) ->
            new Response(500, "{\"success\":false,\"message\":\"no route installed for " + endpoint + "\"}", 0);

    private final HttpServer server;
    private final Map<String, AtomicInteger> calls = new ConcurrentHashMap<>();
    private volatile Route route = BLOCKED;

    FakeServer() throws IOException {
        server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/", this::handle);
        server.setExecutor(null);
        server.start();
    }

    String base() {
        return "http://127.0.0.1:" + server.getAddress().getPort() + "/";
    }

    /** Scripts the next request(s). Call reset() when the test is done (prefer try/finally). */
    void install(Route r) {
        route = r;
    }

    void reset() {
        route = BLOCKED;
        calls.clear();
    }

    int callCount(String endpoint) {
        AtomicInteger n = calls.get(endpoint);
        return n == null ? 0 : n.get();
    }

    void stop() {
        server.stop(0);
    }

    private void handle(HttpExchange ex) throws IOException {
        String path = ex.getRequestURI().getPath().substring(1);
        calls.computeIfAbsent(path, k -> new AtomicInteger()).incrementAndGet();
        if (!"test-key".equals(ex.getRequestHeaders().getFirst("X-Api-Key"))) {
            respond(ex, 401, "{\"success\":false,\"message\":\"Invalid or inactive API key.\"}", 0);
            return;
        }
        Response r = route.handle(path, parseQuery(ex.getRequestURI().getQuery()));
        respond(ex, r.status(), r.body(), r.retryAfterSeconds());
    }

    private static Map<String, String> parseQuery(String query) {
        Map<String, String> out = new LinkedHashMap<>();
        if (query == null || query.isEmpty()) return out;
        for (String pair : query.split("&")) {
            int eq = pair.indexOf('=');
            if (eq < 0) continue;
            try {
                out.put(URLDecoder.decode(pair.substring(0, eq), "UTF-8"),
                        URLDecoder.decode(pair.substring(eq + 1), "UTF-8"));
            } catch (Exception ignored) {
                // decode failure: skip, never crash the fake over a malformed query string
            }
        }
        return out;
    }

    private void respond(HttpExchange ex, int status, String body, int retryAfterSeconds) throws IOException {
        if (retryAfterSeconds > 0) {
            ex.getResponseHeaders().add("Retry-After", String.valueOf(retryAfterSeconds));
        }
        ex.getResponseHeaders().add("Content-Type", "application/json");
        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
        ex.sendResponseHeaders(status, bytes.length);
        ex.getResponseBody().write(bytes);
        ex.close();
    }
}

LookupControllerScenarioTest.java - 11 scenarios against a real embedded Spring Boot app

package com.sellermagnet.wrapper;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;

import java.io.IOException;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Fails-closed scenario tests against the real Spring Boot app (a real
 * embedded server, a real HTTP round trip), with only the upstream
 * SellerMagnet API faked - FakeServer.java generalizes the Java
 * quickstart's own embedded TestServer.java the same way the
 * amazon-api-mock-testing-java post's FakeServer does. ApiClient.java and
 * Retry.java run completely unmodified, including their real backoff
 * waits, so a passing 429/500/502 test is proof the actual wait and
 * Retry-After handling work, not just that the code path was reached.
 */
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class LookupControllerScenarioTest {
    private static final String ASIN = "B0CL61F39H";
    private static final String MARKETPLACE = "ATVPDKIKX0DER";
    private static FakeServer fakeServer;

    @Autowired
    private TestRestTemplate rest;

    @Autowired
    private TTLCache<LookupResponse> cache;

    @BeforeAll
    static void startFakeServer() throws IOException {
        fakeServer = new FakeServer();
    }

    @AfterAll
    static void stopFakeServer() {
        fakeServer.stop();
    }

    @DynamicPropertySource
    static void pointAtFakeServer(DynamicPropertyRegistry registry) throws IOException {
        if (fakeServer == null) {
            fakeServer = new FakeServer();
        }
        registry.add("sellermagnet.api.base", fakeServer::base);
        registry.add("sellermagnet.api.key", () -> "test-key");
    }

    @BeforeEach
    void resetFakeServerAndCache() {
        fakeServer.reset();
        cache.clear();
    }

    private static String productJson(Object price) {
        String currency = "N/A".equals(price) ? "N/A" : "USD";
        String priceLiteral = (price instanceof String) ? "\"" + price + "\"" : String.valueOf(price);
        return "{\"success\":true,\"data\":{\"productInfo\":{\"asin\":\"" + ASIN + "\","
                + "\"title\":\"PlayStation5 console (slim)\",\"link\":\"https://www.amazon.com/dp/" + ASIN + "\","
                + "\"buyBoxInfo\":{\"price\":" + priceLiteral + ",\"currencyCode\":\"" + currency + "\",\"sellerId\":\"Amazon\"}}}}";
    }

    @Test
    void validLookupReturnsPriceAndIsNotCached() {
        fakeServer.install((endpoint, params) -> new FakeServer.Response(200, productJson(444.99), 0));

        ResponseEntity<Map> resp = rest.getForEntity(
                "/lookup/" + ASIN + "?marketplaceId=" + MARKETPLACE, Map.class);

        assertEquals(HttpStatus.OK, resp.getStatusCode());
        assertEquals(444.99, (Double) resp.getBody().get("price"));
        assertEquals(false, resp.getBody().get("cached"));
        assertEquals(1, fakeServer.callCount("amazon-product-lookup"));
    }

    @Test
    void secondLookupIsServedFromCacheWithoutASecondUpstreamCall() {
        fakeServer.install((endpoint, params) -> new FakeServer.Response(200, productJson(444.99), 0));

        rest.getForEntity("/lookup/" + ASIN + "?marketplaceId=" + MARKETPLACE, Map.class);
        ResponseEntity<Map> second = rest.getForEntity(
                "/lookup/" + ASIN + "?marketplaceId=" + MARKETPLACE, Map.class);

        assertEquals(true, second.getBody().get("cached"));
        assertEquals(1, fakeServer.callCount("amazon-product-lookup")); // still 1: the cache answered the second call
    }

    @Test
    void malformedAsinIsRejectedBeforeAnyUpstreamCall() {
        ResponseEntity<Map> resp = rest.getForEntity(
                "/lookup/not-an-asin?marketplaceId=" + MARKETPLACE, Map.class);

        assertEquals(422, resp.getStatusCode().value());
        assertEquals(0, fakeServer.callCount("amazon-product-lookup"));
    }

    @Test
    void unknownMarketplaceIdIsRejectedBeforeAnyUpstreamCall() {
        ResponseEntity<Map> resp = rest.getForEntity(
                "/lookup/" + ASIN + "?marketplaceId=A2Q3Y263D00KWC", Map.class);

        assertEquals(422, resp.getStatusCode().value());
        assertEquals(0, fakeServer.callCount("amazon-product-lookup"));
    }

    @Test
    void lowerCaseAsinIsNormalizedThenLookedUp() {
        fakeServer.install((endpoint, params) -> new FakeServer.Response(200, productJson(444.99), 0));

        ResponseEntity<Map> resp = rest.getForEntity(
                "/lookup/" + ASIN.toLowerCase() + "?marketplaceId=" + MARKETPLACE, Map.class);

        assertEquals(HttpStatus.OK, resp.getStatusCode());
        assertEquals(ASIN, resp.getBody().get("asin"));
    }

    @Test
    void upstream404PassesThroughAsARealAnswerNotA500() {
        fakeServer.install((endpoint, params) ->
                new FakeServer.Response(404, "{\"success\":false,\"message\":\"Product not found\"}", 0));

        ResponseEntity<Map> resp = rest.getForEntity(
                "/lookup/" + ASIN + "?marketplaceId=" + MARKETPLACE, Map.class);

        assertEquals(404, resp.getStatusCode().value());
        assertEquals(1, fakeServer.callCount("amazon-product-lookup")); // billed once, never retried
    }

    @Test
    void free429IsRetriedAndEventuallySucceeds() {
        fakeServer.install((endpoint, params) -> {
            if (fakeServer.callCount(endpoint) == 1) {
                return new FakeServer.Response(429, "{\"success\":false,\"message\":\"rate limited\"}", 1);
            }
            return new FakeServer.Response(200, productJson(444.99), 0);
        });

        ResponseEntity<Map> resp = rest.getForEntity(
                "/lookup/" + ASIN + "?marketplaceId=" + MARKETPLACE, Map.class);

        assertEquals(HttpStatus.OK, resp.getStatusCode());
        assertEquals(2, fakeServer.callCount("amazon-product-lookup"));
    }

    @Test
    void refunded500IsRetriedOnceAndSucceeds() {
        fakeServer.install((endpoint, params) -> {
            if (fakeServer.callCount(endpoint) == 1) {
                return new FakeServer.Response(500, "{\"success\":false,\"message\":\"internal error\"}", 0);
            }
            return new FakeServer.Response(200, productJson(444.99), 0);
        });

        ResponseEntity<Map> resp = rest.getForEntity(
                "/lookup/" + ASIN + "?marketplaceId=" + MARKETPLACE, Map.class);

        assertEquals(HttpStatus.OK, resp.getStatusCode());
        assertEquals(2, fakeServer.callCount("amazon-product-lookup"));
    }

    @Test
    void twoInternalErrorsInARowStopInsteadOfLooping() {
        fakeServer.install((endpoint, params) ->
                new FakeServer.Response(500, "{\"success\":false,\"message\":\"internal error\"}", 0));

        ResponseEntity<Map> resp = rest.getForEntity(
                "/lookup/" + ASIN + "?marketplaceId=" + MARKETPLACE, Map.class);

        assertEquals(502, resp.getStatusCode().value());
        assertEquals(2, fakeServer.callCount("amazon-product-lookup")); // 1st 500 retried once, 2nd 500 stops
    }

    @Test
    void repeated502ExhaustsRetriesAndFailsClosedAs502() {
        fakeServer.install((endpoint, params) ->
                new FakeServer.Response(502, "{\"success\":false,\"message\":\"upstream error\"}", 0));

        ResponseEntity<Map> resp = rest.getForEntity(
                "/lookup/" + ASIN + "?marketplaceId=" + MARKETPLACE, Map.class);

        assertEquals(502, resp.getStatusCode().value());
        assertEquals(4, fakeServer.callCount("amazon-product-lookup")); // billed on every one of the 4 attempts
    }

    @Test
    void negativeCentsOrNoFeaturedOfferPriceIsNeverCoercedToZero() {
        fakeServer.install((endpoint, params) -> new FakeServer.Response(200, productJson("N/A"), 0));

        ResponseEntity<Map> resp = rest.getForEntity(
                "/lookup/" + ASIN + "?marketplaceId=" + MARKETPLACE, Map.class);

        assertEquals(HttpStatus.OK, resp.getStatusCode());
        assertTrue(resp.getBody().get("price") == null); // "N/A" stays null, never 0.0
    }
}

A real connection-refused ConnectException cannot be scripted through FakeServer (it would have to answer, which is the opposite of what the test needs), so the twelfth scenario instantiates LookupController directly with NO Spring context at all, pointing a fresh ApiClient at a port nothing is listening on. A real ConnectException fires almost instantly on a refused connection, unlike ApiClient.java's own hardcoded 120-second request timeout, which this suite does not force with a real two-minute wait.

LookupControllerConnectionErrorTest.java - a real refused connection, no Spring context

package com.sellermagnet.wrapper;

import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.junit.jupiter.api.Test;
import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.net.ServerSocket;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * Connection-error scenario, run WITHOUT a Spring context: LookupController
 * is a plain class, so it is built here by hand and pointed at a port
 * nothing is listening on. A real java.net.ConnectException fires almost
 * instantly (connection refused), unlike a real 120-second client timeout,
 * which the Java quickstart's own ApiClient.java hardcodes and this post
 * reuses unmodified - so that second case is handled in LookupController's
 * catch clause (see the post's callout) but not forced here with a real
 * two-minute wait.
 */
class LookupControllerConnectionErrorTest {
    @Test
    void connectionErrorNeverReachedTheServerSoNothingWasBilled() throws IOException {
        int freePort;
        try (ServerSocket probe = new ServerSocket(0)) {
            freePort = probe.getLocalPort();
        }
        // probe is now closed again: nothing listens on freePort, so a real connection is refused.
        ApiClient client = new ApiClient("http://127.0.0.1:" + freePort + "/", "test-key");
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        TTLCache<LookupResponse> cache = new TTLCache<>(300);
        LookupController controller = new LookupController(client, validator, cache);

        ResponseEntity<?> resp = controller.lookup("B0CL61F39H", "ATVPDKIKX0DER");

        assertEquals(502, resp.getStatusCode().value());
    }
}

Real output: mvn test, all 12 scenarios, real retry waits included

$ mvn test
...
[INFO] Running com.sellermagnet.wrapper.LookupControllerScenarioTest
[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 38.60 s -- in com.sellermagnet.wrapper.LookupControllerScenarioTest
[INFO] Running com.sellermagnet.wrapper.LookupControllerConnectionErrorTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.05 s -- in com.sellermagnet.wrapper.LookupControllerConnectionErrorTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Real output: the packaged jar, a cache miss then a cache hit, one upstream call total

$ curl "http://127.0.0.1:8098/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER"
{"asin":"B0CL61F39H","title":"PlayStation5 console (slim)","price":444.99,"currency":"USD","cached":false}

$ curl "http://127.0.0.1:8098/lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER"   # again, within the 300s cache window
{"asin":"B0CL61F39H","title":"PlayStation5 console (slim)","price":444.99,"currency":"USD","cached":true}

$ curl -o /dev/null -w "%{http_code}\n" "http://127.0.0.1:8098/lookup/bad-asin?marketplaceId=ATVPDKIKX0DER"
422

upstream calls made: 1

This cache is per JVM instance

Running the service as several container replicas behind a load balancer means each one holds its own cache, so the same ASIN can be fetched once per replica within the TTL. That is a reasonable default for a single small service; a reader running several replicas should size the TTL around that, or swap in a shared store of their own choice.

Frequently Asked Questions

Why validate with a custom bean-validation constraint instead of a plain if-check?

Either works. A @Pattern on the ASIN needs nothing extra; the marketplace set-membership check has no built-in jakarta annotation, so a small @KnownMarketplace constraint keeps both checks declarative and both run through the same injected Validator.

Does the cache in this wrapper work across multiple server instances?

No. TTLCache wraps a plain in-process ConcurrentHashMap; each JVM keeps its own copy. Several replicas sharing one cache need an external store, which is outside this post's scope.

Which status codes does the wrapper retry?

429 is waited out for free, a 500 is retried once since it is refunded, and 502/503 are retried up to 4 attempts total since each is billed. A 404 is never retried.

Why does ApiClient.java/Retry.java need a package line added if they're reused unchanged?

Spring Boot's component scan uses the main class's own package as its base package; running from the default package scans the entire classpath, including Spring's own optional autoconfiguration classes, and breaks. Adding one package line was the only change; none of the client or retry logic was touched.

Can I reuse the asyncio or reactive quickstart instead of the sync Java client here?

There is no asyncio sibling for Java in this series: java.net.http.HttpClient is thread-safe and reusable as-is, so a plain Spring MVC controller fits it without extra plumbing, the same way it fits a plain script in the quickstart.

Bottom line: validate with jakarta bean validation before any network call, cache repeat lookups for free in a short-lived per-JVM TTLCache, and reuse the quickstart's own client and retry policy with the one mechanical change a real package needs. Every behaviour here, including the default-package scanning failure the test suite caught, came from running mvn test against real code with only the upstream HTTP layer faked - see the Java quickstart for the client's own retry details and the API documentation for every endpoint.

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime