Home / Blog / Wrap an Amazon Product API in an Express Microservice: Caching and Validation

Wrap an Amazon Product API in an Express Microservice: Caching and Validation

Wrap the SellerMagnet API in a small Express.js microservice: plain checks validate the ASIN and marketplace before any network call, a short-lived in-process cache answers repeat lookups for free, and the quickstart's own client and retry policy are reused unchanged. Every scenario is run against a fails-closed fake HTTP layer, not described by hand.

December 03, 2026
7 min read
SellerMagnet Team
Share & Bookmark
Terminal window validating a lookup request before any network call in an Express route

An Express microservice in front of the SellerMagnet API validates every request with a plain check 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 - models.js and cache.js are new, app.js is the Express route, and the TypeScript quickstart's own client.js, retry.js, types.js and lookup.js are reused unchanged - and tests all of it against a fails-closed fake HTTP layer so nothing here is just described.

Key Takeaways

  • Validate asin and marketplaceId before the upstream call, so a bad request costs nothing and waits on no timeout.
  • A small in-process TTLCache (a plain Map) answers a repeated lookup for free; it lives in one Node process, so several PM2 cluster workers or container replicas each keep their own copy unless you add a shared store.
  • 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.
  • A plain fetch failure (DNS, refused connection, our own AbortSignal timeout) throws a TypeError, not an ApiError - retry.js's withRetry only retries ApiError instances, so a dropped connection reaches the route after exactly one attempt, with nothing billed.
  • client.js, retry.js, types.js and lookup.js do not change between a GraphQL loader, a Jest test harness and an Express route: the same fetch-based client works in all three.

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 TypeScript quickstart's client.js and retry.js on its own. This post reuses that exact client and retry helper unchanged - a plain fetch-based client fits an Express route the same way it fits a GraphQL loader or a Jest test harness, so there is no separate framework-specific client to maintain here.

Dependencies

npm install express
export SELLERMAGNET_API_KEY="your-key-here"

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

Put the shape checks in one function and call it before any network call. An ASIN is always 10 upper-case letters or digits; the marketplaceId must be one this wrapper actually supports (the full list of all 23 marketplace IDs is in the marketplace IDs list). A failing check throws before the Express route ever opens a connection, so a malformed request never waits on the 120-second timeout and never costs a credit. Two fields do not need a validation library like zod or joi: a regex and a Set membership check are enough, and there is one fewer dependency to pin.

models.js - validated before any network call

// models.js - request/response validation for the Express wrapper, with
// plain checks (no schema library needed for two fields).
//
// Keeping these checks in the wrapper (not in the upstream call) fails
// closed: a bad ASIN or marketplace ID never reaches the network, so it
// never spends a credit and never waits on a timeout.

const ASIN_RE = /^[A-Z0-9]{10}$/;

// The handful of marketplace IDs covered by this wrapper; the full list of
// all 23 is in https://sellermagnet-api.com/blog/amazon-marketplace-ids-list
const MARKETPLACE_IDS = new Set([
  "ATVPDKIKX0DER",  // amazon.com
  "A1PA6795UKMFR9", // amazon.de
  "A1F83G8C2ARO7P", // amazon.co.uk
  "A13V1IB3VIYZZH", // amazon.fr
]);

export class RequestValidationError extends Error {
  /** @param {{loc: string[], msg: string}[]} errors */
  constructor(errors) {
    super("invalid lookup request");
    this.name = "RequestValidationError";
    this.errors = errors;
  }
}

/**
 * @param {string} rawAsin
 * @param {string} rawMarketplaceId
 * @returns {{asin: string, marketplaceId: string}}
 */
export function validateLookupRequest(rawAsin, rawMarketplaceId) {
  const errors = [];

  const asin = (rawAsin ?? "").trim().toUpperCase();
  if (!ASIN_RE.test(asin)) {
    errors.push({ loc: ["asin"], msg: "asin must be 10 upper-case letters/digits" });
  }

  const marketplaceId = (rawMarketplaceId ?? "").trim();
  if (!MARKETPLACE_IDS.has(marketplaceId)) {
    errors.push({ loc: ["marketplaceId"], msg: `unknown marketplaceId: ${marketplaceId}` });
  }

  if (errors.length > 0) throw new RequestValidationError(errors);
  return { asin, marketplaceId };
}

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

TTLCache is a plain Map keyed by asin:marketplaceId, with each entry carrying its own expiry. 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 process that holds it: running the service under PM2 in cluster mode (or behind several container replicas) means each worker keeps its own copy, so the same ASIN can still be fetched once per worker. 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.

cache.js - a per-process TTL cache

// cache.js - 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 Node process holds its own Map. A
// reader running the service behind a cluster of several Node processes
// (PM2 cluster mode, several container replicas) needs a shared store of
// their own choice; that trade-off is called out in the post, not hidden.

export class TTLCache {
  /** @param {number} ttlMs */
  constructor(ttlMs = 300_000) {
    this.ttlMs = ttlMs;
    /** @type {Map<string, {expiresAt: number, value: any}>} */
    this.store = new Map();
  }

  /** @param {string} key */
  get(key) {
    const hit = this.store.get(key);
    if (!hit) return undefined;
    if (hit.expiresAt < Date.now()) {
      this.store.delete(key);
      return undefined;
    }
    return hit.value;
  }

  /** @param {string} key @param {any} value */
  set(key, value) {
    this.store.set(key, { expiresAt: Date.now() + this.ttlMs, value });
  }

  get size() {
    return this.store.size;
  }
}

What does the Express route itself look like?

The route validates the path and query parameters first, checks the cache, and only then calls withRetry around the quickstart's own lookupProduct, which in turn uses the shared client.js. A plain fetch failure - the connection was refused, DNS failed, or our own AbortSignal fired after 120 seconds - surfaces as a TypeError, not an ApiError: withRetry only retries ApiError instances, so that branch needs its own handling, or a dropped connection reaches the client as an unhandled 500 instead of the wrapper's own 502.

app.js - the Express microservice

// app.js - Express microservice wrapping the SellerMagnet API's product
// lookup.
//
// Validates the request (models.js) before any network call, serves repeat
// lookups from a short-lived in-process cache (cache.js), and only then
// calls the upstream API through the quickstart's own client.js/retry.js/
// lookup.js, unchanged.

import express from "express";

import { TTLCache } from "./cache.js";
import { RequestValidationError, validateLookupRequest } from "./models.js";
import { withRetry } from "./retry.js";
import { lookupProduct } from "./lookup.js";
import { ApiError } from "./client.js";

export function createApp() {
  const app = express();
  const cache = new TTLCache(300_000); // 300s, one per process

  app.get("/lookup/:asin", async (req, res) => {
    let asin, marketplaceId;
    try {
      ({ asin, marketplaceId } = validateLookupRequest(req.params.asin, req.query.marketplaceId));
    } catch (err) {
      if (err instanceof RequestValidationError) {
        return res.status(422).json({ detail: err.errors }); // bad shape: no network call made
      }
      throw err;
    }

    const cacheKey = `${asin}:${marketplaceId}`;
    const cached = cache.get(cacheKey);
    if (cached !== undefined) {
      return res.json({ ...cached, cached: true });
    }

    let product;
    try {
      product = await withRetry(() => lookupProduct(asin, marketplaceId));
    } catch (err) {
      if (err instanceof ApiError) {
        if (err.status === 404) {
          return res.status(404).json({ detail: "asin not found on this marketplace" });
        }
        return res.status(502).json({ detail: "upstream lookup failed" });
      }
      // a plain fetch/network failure (DNS, refused connection, AbortError on
      // our own 120s timeout) is not an ApiError - it never got an HTTP
      // response at all, so it needs its own branch next to ApiError, or it
      // reaches the client as an unhandled 500 instead of this wrapper's 502.
      return res.status(502).json({ detail: "upstream unreachable" });
    }

    const result = {
      asin: product.asin,
      title: product.title,
      price: product.buyBoxInfo.price, // number, or null for "N/A" - never 0
      currency: product.buyBoxInfo.currencyCode,
      cached: false,
    };
    cache.set(cacheKey, result);
    res.json(result);
  });

  return app;
}

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

The plain-fetch-failure branch above only ever fires when the request never reached the server at all (DNS failure, refused connection), so nothing was billed. Our own AbortSignal.timeout(120_000) in client.js firing is different in one way that matters for billing on some upstream failure modes: if the server had already started processing before the connection dropped, the credit can already be deducted and is not refunded. Keep the client timeout at 120 seconds, matching the server, rather than cutting it short to "fail fast".

Terminal flow diagram of a lookup request through 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\u00ae5 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
No featured offer (price "N/A")200-Yes - decodes to null, not 0
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 error (never reached the server)502no - not an ApiErrorNo - 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 fails-closed fake HTTP layer, not a described behaviour.

app.test.js - 12 scenarios against a fails-closed fake HTTP layer

// app.test.js - fails-closed scenario tests for the Express wrapper, with
// every upstream call faked through nock (no real network, no spent
// credits). Each test name is one row of the scenario checklist in the post.

import { jest } from "@jest/globals";
import nock from "nock";
import request from "supertest";

process.env.SELLERMAGNET_API_KEY = "test-key";

const { createApp } = await import("../app.js");

const ASIN = "B0CL61F39H";
const MARKETPLACE = "ATVPDKIKX0DER";
const UPSTREAM = "https://sellermagnet-api.com";

function productBody(price = 444.99) {
  return {
    success: true,
    data: {
      productInfo: {
        asin: ASIN,
        title: "PlayStation5 console (slim)",
        link: `https://www.amazon.com/dp/${ASIN}`,
        buyBoxInfo: { price, currencyCode: "USD", sellerId: "A2L77EE7U53NWQ" },
      },
    },
  };
}

let app;

// retry.js's own backoff is small on purpose for a test harness (2**attempt
// * 100ms, capped at 4 attempts = under 1.5s worst case), so these tests let
// the real timers run rather than faking global setTimeout - faking it would
// also race fetch's own AbortSignal timeout in client.js.
jest.setTimeout(20_000);

beforeEach(() => {
  app = createApp();
  nock.cleanAll();
  nock.disableNetConnect();
  nock.enableNetConnect("127.0.0.1"); // supertest's own local server, not the upstream API
});

afterEach(() => {
  expect(nock.isDone()).toBe(true); // every scripted call must actually fire
  nock.enableNetConnect();
});

test("valid ASIN, cache miss: 200, one upstream call, not cached", async () => {
  const scope = nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE }).reply(200, productBody());
  const res = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
  expect(res.status).toBe(200);
  expect(res.body).toEqual({ asin: ASIN, title: "PlayStation5 console (slim)",
    price: 444.99, currency: "USD", cached: false });
  expect(scope.isDone()).toBe(true);
});

test("same lookup again within 300s: served from cache, zero upstream calls", async () => {
  nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE }).reply(200, productBody());
  const first = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
  const second = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
  expect(first.body.cached).toBe(false);
  expect(second.body.cached).toBe(true);
  expect(second.body.price).toBe(444.99);
});

test("malformed ASIN shape: 422, rejected before the network", async () => {
  const res = await request(app).get("/lookup/short").query({ marketplaceId: MARKETPLACE });
  expect(res.status).toBe(422);
  expect(res.body.detail[0].loc).toEqual(["asin"]);
});

test("unknown marketplaceId: 422, rejected before the network", async () => {
  const res = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: "A-UNKNOWN" });
  expect(res.status).toBe(422);
  expect(res.body.detail[0].loc).toEqual(["marketplaceId"]);
});

test("lower-case ASIN, cache miss: normalized then looked up", async () => {
  nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE }).reply(200, productBody());
  const res = await request(app).get(`/lookup/${ASIN.toLowerCase()}`).query({ marketplaceId: MARKETPLACE });
  expect(res.status).toBe(200);
  expect(res.body.asin).toBe(ASIN);
});

test("no featured offer price N/A decodes to null, not 0", async () => {
  nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE }).reply(200, productBody("N/A"));
  const res = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
  expect(res.body.price).toBeNull();
});

test("upstream 404 (not on this marketplace): 404, not retried, billed", async () => {
  const scope = nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE })
    .reply(404, { success: false, message: "Product not found." });
  const res = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
  expect(res.status).toBe(404);
  expect(scope.isDone()).toBe(true);
});

test("upstream 429 (concurrency cap): retried for free, eventually 200", async () => {
  nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE })
    .reply(429, { success: false, message: "Too many concurrent requests." }, { "Retry-After": "0" });
  nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE }).reply(200, productBody());
  const res = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
  expect(res.status).toBe(200);
});

test("upstream 500 (refunded): retried once, then 200", async () => {
  nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE })
    .reply(500, { success: false, message: "Internal error." });
  nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE }).reply(200, productBody());
  const res = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
  expect(res.status).toBe(200);
});

test("two upstream 500s in a row: stops after the second, 502", async () => {
  nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE }).times(2)
    .reply(500, { success: false, message: "Internal error." });
  const res = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
  expect(res.status).toBe(502);
});

test("upstream 502/503: retried up to 4 attempts, each billed, then 200", async () => {
  nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE }).times(3)
    .reply(502, { success: false, message: "Bad gateway." });
  nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE }).reply(200, productBody());
  const res = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
  expect(res.status).toBe(200);
});

test("connection error (never reached the server): 502, not retried, nothing billed", async () => {
  const scope = nock(UPSTREAM).get("/api/amazon-product-lookup")
    .query({ asin: ASIN, marketplaceId: MARKETPLACE })
    .replyWithError("connection refused");
  const res = await request(app).get(`/lookup/${ASIN}`).query({ marketplaceId: MARKETPLACE });
  expect(res.status).toBe(502);
  expect(scope.isDone()).toBe(true); // exactly the 1 scripted call fired, no retry
});

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

GET /lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER\n -> {"asin":"B0CL61F39H","title":"PlayStation5 console (slim)","price":444.99,"currency":"USD","cached":false}\nGET /lookup/B0CL61F39H?marketplaceId=ATVPDKIKX0DER  (again, within the 300s cache window)\n -> {"asin":"B0CL61F39H","title":"PlayStation5 console (slim)","price":444.99,"currency":"USD","cached":true}\nupstream calls made: 1

This cache is per worker process

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

Frequently Asked Questions

Why validate with a plain function instead of a library like zod or joi?

Either works. For two fields - an ASIN regex and a marketplaceId Set membership check - a small function avoids an extra dependency; a larger request shape is a better fit for a schema library.

Does the cache in this wrapper work across multiple Node processes?

No. TTLCache wraps a plain in-process Map; each worker process keeps its own copy. Several PM2 cluster workers 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 a plain fetch failure need its own branch instead of ApiError handling?

A refused connection, a DNS failure, or our own AbortSignal firing throws a TypeError straight from fetch, not the wrapper's ApiError. withRetry only retries ApiError instances, so without a separate branch for it, a dropped connection reaches the client as an unhandled 500 instead of the wrapper's own 502.

Can I reuse the GraphQL post's DataLoader instead of this TTLCache?

Not as a drop-in: DataLoader's cache is scoped to one GraphQL request and must be created fresh per request, so it dedupes repeated keys within one request rather than answering repeat lookups across requests the way this TTLCache does.

Bottom line: validate before any network call, cache repeat lookups for free in a short-lived per-process TTLCache, and reuse the quickstart's own client and retry policy unchanged. Every behaviour here came from running npm test against real code with only the HTTP layer faked - see the TypeScript quickstart for the client's own retry details and the API documentation for every endpoint.

Related Articles

Continue exploring topics related to this article.

Terminal window validating a lookup request before any network call in a Gin route handler
Amazon API Performance Go

Wrap an Amazon Product API in a Go Gin Microservice: Caching and Validation

Wrap the SellerMagnet API in a small Gin microservice: a regex and a set membership check validate the ASIN and marketplace before any network call, a mutex-guarded TTL cache answers repeat lookups for free, and the Go quickstart's own client.go, get.go, lookup.go and retry.go are reused unchanged. Every scenario, including a goroutine race on the cache, runs with -race against a fails-closed fake http.RoundTripper, not described by hand.

Dec 03, 2026 Read
Code editor validating a lookup request before any network call in a Ktor route handler
Amazon API Performance Kotlin

Wrap an Amazon Product API in a Kotlin Ktor Microservice: Caching and Validation

Wrap the SellerMagnet API in a small Ktor microservice: a regex and a set membership check validate the ASIN and marketplace before any network call, a ConcurrentHashMap-backed TTL cache answers repeat lookups for free, and the Kotlin quickstart's own Client.kt and Models.kt are reused unchanged. Every scenario, including a concurrent cache read from Netty's coroutine pool, runs against a fails-closed fake HTTP server through Ktor's own embedded test engine, not described by hand.

Dec 02, 2026 Read
Code editor showing a Spring Boot controller validating a lookup request with a bean constraint before any network call
Amazon API Performance Java

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.

Dec 02, 2026 Read
Back to Blog

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