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

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

Wrap the SellerMagnet API in a small FastAPI microservice: pydantic validates the ASIN and marketplace before any network call, a short-lived in-process cache answers repeat lookups for free, and the async client retries only the status codes worth retrying. Every scenario, including two real bugs the tests caught, is run against a fails-closed fake HTTP layer, not described by hand.

December 02, 2026
6 min read
SellerMagnet Team
Share & Bookmark
Terminal window validating a lookup request with pydantic before any network call

A FastAPI microservice in front of the SellerMagnet API validates every request with pydantic 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.py, cache.py, a client.py built on httpx.AsyncClient, and the FastAPI app itself - and tests all of it, including two real bugs the tests found, against a fails-closed fake HTTP layer so nothing here is just described.

Key Takeaways

  • Validate asin and marketplace_id with pydantic 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 worker process, so several workers each keep their own copy unless you add a shared store.
  • The retry policy is the async sibling's: 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.
  • Raising a bare pydantic ValidationError from an endpoint leaks a non-JSON-serializable object into FastAPI's error response; the fix strips it down to loc/msg/type.
  • An uncaught httpx.ConnectError or httpx.TimeoutException bypasses the wrapper's own error handling and reaches the client as a raw 500; catch it explicitly and answer 502.

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 Python quickstart's sellermagnet.py and retry.py on its own. The async sibling used here is the one the asyncio and httpx guide already tested and published as asyncio_api.py / async_retry.py; this post reuses that exact client, renamed client.py, unchanged.

Dependencies

pip install fastapi "uvicorn[standard]" httpx pydantic
export SELLERMAGNET_API_KEY="your-key-here"

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

Put the shape checks in a pydantic model and construct it before any network call. An ASIN is always 10 upper-case letters or digits; the marketplace ID must be one this wrapper actually supports (the full list of all 23 marketplace IDs is in the marketplace IDs list). A failing validator raises before client.py ever opens a connection, so a malformed request never waits on the 120-second timeout and never costs a credit.

models.py - validated before any network call

"""Request/response validation for the FastAPI wrapper, with pydantic v2.

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.
"""
import re

from pydantic import BaseModel, field_validator

ASIN_RE = re.compile(r"^[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
MARKETPLACE_IDS = {
    "ATVPDKIKX0DER",   # amazon.com
    "A1PA6795UKMFR9",  # amazon.de
    "A1F83G8C2ARO7P",  # amazon.co.uk
    "A13V1IB3VIYZZH",  # amazon.fr
}


class LookupRequest(BaseModel):
    asin: str
    marketplace_id: str

    @field_validator("asin")
    @classmethod
    def asin_shape(cls, value: str) -> str:
        value = value.strip().upper()
        if not ASIN_RE.match(value):
            raise ValueError("asin must be 10 upper-case letters/digits")
        return value

    @field_validator("marketplace_id")
    @classmethod
    def marketplace_known(cls, value: str) -> str:
        if value not in MARKETPLACE_IDS:
            raise ValueError(f"unknown marketplace_id: {value}")
        return value


class LookupResponse(BaseModel):
    asin: str
    title: str
    price: float | None
    currency: str | None
    cached: bool

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

TTLCache is a plain dict keyed by asin:marketplace_id, 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: with several FastAPI worker processes behind a load balancer, each one 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.py - a per-process TTL cache

"""A tiny in-process TTL cache, keyed by (asin, marketplace_id).

Not a cross-process cache (no external cache store named here, by the owner's
infrastructure rule): one FastAPI worker process holds its own dict. A reader
running several worker processes needs a shared store of their own choice;
that trade-off is called out in the post, not hidden.
"""
import time
from typing import Any


class TTLCache:
    def __init__(self, ttl_seconds: float = 300.0):
        self.ttl = ttl_seconds
        self._store: dict[str, tuple[float, Any]] = {}

    def get(self, key: str) -> Any | None:
        hit = self._store.get(key)
        if hit is None:
            return None
        expires_at, value = hit
        if expires_at < time.monotonic():
            del self._store[key]
            return None
        return value

    def set(self, key: str, value: Any) -> None:
        self._store[key] = (time.monotonic() + self.ttl, value)

    def __len__(self) -> int:
        return len(self._store)

What does client.py retry, and what does it never retry?

client.py is the async sibling of the quickstart's sellermagnet.py and retry.py, built on httpx.AsyncClient so the FastAPI route can await it inside the same event loop instead of blocking a worker thread. A 429 (the free concurrency limiter) is waited out without spending one of the retry attempts; a 500 is refunded, so one retry costs nothing, but a second 500 in a row stops instead of looping; 502 and 503 are billed on every attempt, so they are capped at 4 attempts total; a 404 means the ASIN is not on that marketplace and is never retried.

client.py - async client with the quickstart's retry policy

"""Async client for the SellerMagnet API, shared by the FastAPI wrapper.

Same contract as the quickstart's sellermagnet.py (ApiError, a 120s-timeout
client, the same success/data response-shape check), built on
httpx.AsyncClient so the wrapper can await it inside FastAPI's own event
loop without blocking a worker thread per request.
"""
import asyncio
import os
import random

import httpx

API = "https://sellermagnet-api.com/api"


class ApiError(Exception):
    def __init__(self, status: int, message: str, retry_after: float = 0.0):
        super().__init__(f"{status}: {message}")
        self.status, self.retry_after = status, retry_after


def new_client() -> httpx.AsyncClient:
    return httpx.AsyncClient(
        base_url=API,
        headers={"X-Api-Key": os.environ["SELLERMAGNET_API_KEY"]},
        timeout=120.0,
    )


async def aget(client: httpx.AsyncClient, endpoint: str, **params) -> dict:
    resp = await client.get(f"/{endpoint}", params=params)
    try:
        body = resp.json()
    except ValueError:                      # e.g. an HTML page from a proxy
        body = {}
    if resp.status_code == 200 and body.get("success"):
        return body["data"]
    try:
        wait = float(resp.headers.get("Retry-After", 0))
    except ValueError:
        wait = 0.0
    raise ApiError(resp.status_code, body.get("message", "request failed"), wait)


RETRYABLE = {500, 502, 503}      # 429 is the free concurrency/rate limiter: handled separately below
MAX_WAITS = 6                    # free 429 waits before giving up


async def aget_with_retry(client: httpx.AsyncClient, endpoint: str, attempts: int = 4, **params) -> dict:
    internal_errors = 0
    waits = 0
    attempt = 1
    while True:
        try:
            return await aget(client, endpoint, **params)
        except ApiError as err:
            if err.status == 429:                       # free: wait Retry-After, never spend an attempt
                waits += 1
                if waits > MAX_WAITS:
                    raise
                await asyncio.sleep(max(err.retry_after, 1.0))
                continue
            internal_errors += err.status == 500
            if err.status not in RETRYABLE or attempt == attempts or internal_errors > 1:
                raise                                    # a second 500 in a row: report it, don't loop
            backoff = min(2 ** attempt, 30) + random.uniform(0, 1)
            await asyncio.sleep(max(backoff, err.retry_after))
            attempt += 1
        except (httpx.ConnectError, httpx.TimeoutException):
            if attempt == attempts:
                raise
            await asyncio.sleep(min(2 ** attempt, 30))
            attempt += 1
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.

What does the FastAPI route itself look like?

The route builds LookupRequest first, checks the cache, and only then calls aget_with_retry. The first version of this route raised the bare pydantic ValidationError as the HTTPException detail; FastAPI's own JSON encoder failed on it, because ValidationError.errors() carries the raw exception object in ctx["error"], which json.dumps() cannot serialize - caught by the test for a malformed ASIN, not guessed. The fix strips each error down to loc, msg and type. A second bug the tests caught: httpx.ConnectError and httpx.TimeoutException were not caught at all, so a connection failure reached the client as an unhandled 500 instead of the wrapper's own 502; both are now caught next to ApiError.

app.py - the FastAPI microservice

"""FastAPI microservice wrapping the SellerMagnet API's product lookup.

Validates the request (models.py) before any network call, serves repeat
lookups from a short-lived in-process cache, and only then calls the
upstream API through the shared async client (client.py), with the same
retry policy as the asyncio quickstart.
"""
from contextlib import asynccontextmanager

import httpx
from fastapi import FastAPI, HTTPException
from pydantic import ValidationError

from cache import TTLCache
from client import ApiError, aget_with_retry, new_client
from models import LookupRequest, LookupResponse


@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.client = new_client()        # one shared client, opened once per worker process
    try:
        yield
    finally:
        await app.state.client.aclose()


app = FastAPI(title="Amazon Lookup Wrapper", lifespan=lifespan)
cache = TTLCache(ttl_seconds=300.0)


@app.get("/lookup/{asin}", response_model=LookupResponse)
async def lookup(asin: str, marketplace_id: str) -> LookupResponse:
    try:
        request = LookupRequest(asin=asin, marketplace_id=marketplace_id)
    except ValidationError as err:
        # err.errors() carries a raw exception object in ctx["error"], which json.dumps()
        # cannot serialize - take only the plain strings FastAPI's own 422 body uses.
        detail = [{"loc": e["loc"], "msg": e["msg"], "type": e["type"]} for e in err.errors()]
        raise HTTPException(status_code=422, detail=detail)    # bad shape: no network call made
    cache_key = f"{request.asin}:{request.marketplace_id}"
    cached = cache.get(cache_key)
    if cached is not None:
        return LookupResponse(**cached, cached=True)
    try:
        data = await aget_with_retry(
            app.state.client, "amazon-product-lookup",
            asin=request.asin, marketplaceId=request.marketplace_id,
        )
    except ApiError as err:
        if err.status == 404:
            raise HTTPException(status_code=404, detail="asin not found on this marketplace")
        raise HTTPException(status_code=502, detail="upstream lookup failed")
    except (httpx.ConnectError, httpx.TimeoutException):
        raise HTTPException(status_code=502, detail="upstream unreachable")
    product = data["productInfo"]
    price = product["buyBoxInfo"].get("price")
    result = {
        "asin": product["asin"],
        "title": product["title"],
        "price": price if isinstance(price, (int, float)) else None,   # "N/A" -> None, never 0
        "currency": product["buyBoxInfo"].get("currencyCode"),
    }
    cache.set(cache_key, result)
    return LookupResponse(**result, cached=False)

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 marketplace_id422noNo - rejected before the network
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
Upstream free gate 400502noNo - the 400 itself
Upstream 502 / 503502yes, up to 4 attemptsYes - every attempt
Connection error / timeout502yes, up to 4 attemptsNo extra cost either way
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.

test_app.py - 11 scenarios against a fails-closed fake HTTP layer

"""Fails-closed scenario tests for the FastAPI wrapper, with every upstream
call faked through respx (no real network, no spent credits). Each test name
is one row of the scenario checklist in the post.
"""
import os

os.environ.setdefault("SELLERMAGNET_API_KEY", "test-key")

import httpx
import pytest
import respx
from fastapi.testclient import TestClient

import app as app_module
import cache as cache_module

ASIN = "B0CL61F39H"
MARKETPLACE = "ATVPDKIKX0DER"
LOOKUP_URL = "https://sellermagnet-api.com/api/amazon-product-lookup"

PRODUCT_BODY = {
    "success": True,
    "data": {"productInfo": {
        "asin": ASIN, "title": "PlayStation5 console (slim)",
        "buyBoxInfo": {"price": 444.99, "currencyCode": "USD"},
    }},
}


@pytest.fixture(autouse=True)
def fresh_cache(monkeypatch):
    # every test gets its own empty cache and never really sleeps on a retry
    app_module.cache = cache_module.TTLCache(ttl_seconds=300.0)
    monkeypatch.setattr(app_module, "cache", app_module.cache)
    monkeypatch.setattr("client.asyncio.sleep", _no_sleep)
    yield


async def _no_sleep(_seconds):
    return None


@respx.mock
def test_valid_lookup_returns_price_and_is_not_cached():
    respx.get(LOOKUP_URL).mock(return_value=httpx.Response(200, json=PRODUCT_BODY))
    with TestClient(app_module.app) as client:
        resp = client.get(f"/lookup/{ASIN}", params={"marketplace_id": MARKETPLACE})
    assert resp.status_code == 200
    body = resp.json()
    assert body == {"asin": ASIN, "title": "PlayStation5 console (slim)",
                     "price": 444.99, "currency": "USD", "cached": False}


@respx.mock
def test_second_lookup_is_served_from_cache_without_a_second_call():
    route = respx.get(LOOKUP_URL).mock(return_value=httpx.Response(200, json=PRODUCT_BODY))
    with TestClient(app_module.app) as client:
        first = client.get(f"/lookup/{ASIN}", params={"marketplace_id": MARKETPLACE})
        second = client.get(f"/lookup/{ASIN}", params={"marketplace_id": MARKETPLACE})
    assert first.json()["cached"] is False
    assert second.json()["cached"] is True
    assert route.call_count == 1          # the cache hit never reached the network


@respx.mock
def test_malformed_asin_is_rejected_before_any_upstream_call():
    route = respx.get(LOOKUP_URL).mock(return_value=httpx.Response(200, json=PRODUCT_BODY))
    with TestClient(app_module.app) as client:
        resp = client.get("/lookup/not-an-asin", params={"marketplace_id": MARKETPLACE})
    assert resp.status_code == 422
    assert route.call_count == 0          # fails closed: a bad shape never spends a credit


@respx.mock
def test_unknown_marketplace_id_is_rejected_before_any_upstream_call():
    route = respx.get(LOOKUP_URL).mock(return_value=httpx.Response(200, json=PRODUCT_BODY))
    with TestClient(app_module.app) as client:
        resp = client.get(f"/lookup/{ASIN}", params={"marketplace_id": "NOT-REAL"})
    assert resp.status_code == 422
    assert route.call_count == 0


@respx.mock
def test_upstream_404_passes_through_as_a_real_answer_not_a_500():
    route = respx.get(LOOKUP_URL).mock(
        return_value=httpx.Response(404, json={"success": False, "message": "not found"}))
    with TestClient(app_module.app) as client:
        resp = client.get(f"/lookup/{ASIN}", params={"marketplace_id": MARKETPLACE})
    assert resp.status_code == 404
    assert route.call_count == 1          # a 404 is a real answer; it must not be retried


@respx.mock
def test_upstream_free_gate_400_passes_through_without_a_retry():
    route = respx.get(LOOKUP_URL).mock(
        return_value=httpx.Response(400, json={"success": False, "message": "Invalid marketplaceId"}))
    with TestClient(app_module.app) as client:
        resp = client.get(f"/lookup/{ASIN}", params={"marketplace_id": MARKETPLACE})
    assert resp.status_code == 502         # the wrapper's own contract: not 200, never fabricated
    assert route.call_count == 1           # free gate error: one attempt, no retry budget spent


@respx.mock
def test_connection_error_is_retried_then_fails_closed():
    route = respx.get(LOOKUP_URL).mock(side_effect=httpx.ConnectError("connection refused"))
    with TestClient(app_module.app) as client:
        resp = client.get(f"/lookup/{ASIN}", params={"marketplace_id": MARKETPLACE})
    assert resp.status_code == 502
    assert route.call_count == 4           # all 4 attempts used, never silently treated as a miss


@respx.mock
def test_free_429_is_retried_and_eventually_succeeds():
    route = respx.get(LOOKUP_URL).mock(side_effect=[
        httpx.Response(429, headers={"Retry-After": "2"},
                        json={"success": False, "message": "concurrency cap"}),
        httpx.Response(200, json=PRODUCT_BODY),
    ])
    with TestClient(app_module.app) as client:
        resp = client.get(f"/lookup/{ASIN}", params={"marketplace_id": MARKETPLACE})
    assert resp.status_code == 200
    assert resp.json()["cached"] is False
    assert route.call_count == 2


@respx.mock
def test_refunded_500_is_retried_once_and_succeeds():
    route = respx.get(LOOKUP_URL).mock(side_effect=[
        httpx.Response(500, json={"success": False, "message": "internal error"}),
        httpx.Response(200, json=PRODUCT_BODY),
    ])
    with TestClient(app_module.app) as client:
        resp = client.get(f"/lookup/{ASIN}", params={"marketplace_id": MARKETPLACE})
    assert resp.status_code == 200
    assert route.call_count == 2


@respx.mock
def test_repeated_502_exhausts_retries_and_fails_closed_as_502():
    respx.get(LOOKUP_URL).mock(
        return_value=httpx.Response(502, json={"success": False, "message": "upstream down"}))
    with TestClient(app_module.app) as client:
        resp = client.get(f"/lookup/{ASIN}", params={"marketplace_id": MARKETPLACE})
    assert resp.status_code == 502          # never a fabricated 200 after retries run out


@respx.mock
def test_two_internal_errors_in_a_row_stop_instead_of_looping():
    route = respx.get(LOOKUP_URL).mock(
        return_value=httpx.Response(500, json={"success": False, "message": "internal error"}))
    with TestClient(app_module.app) as client:
        resp = client.get(f"/lookup/{ASIN}", params={"marketplace_id": MARKETPLACE})
    assert resp.status_code == 502
    assert route.call_count == 2            # one retry on the first 500, then stop on the second

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

GET /lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER
 -> {'asin': 'B0CL61F39H', 'title': 'PlayStation5 console (slim)', 'price': 444.99, 'currency': 'USD', 'cached': False}
GET /lookup/B0CL61F39H?marketplace_id=ATVPDKIKX0DER  (again, within the 300s cache window)
 -> {'asin': 'B0CL61F39H', 'title': 'PlayStation5 console (slim)', 'price': 444.99, 'currency': 'USD', 'cached': True}
upstream calls made: 1

This cache is per worker process

Running the service with several worker processes (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 pydantic instead of just catching the upstream's error?

A pydantic check runs before any network call, so a malformed ASIN or an unsupported marketplace costs nothing and waits on no timeout; letting the upstream reject it still spends a request.

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

No. TTLCache is a plain in-process dict; each worker process keeps its own copy. Several 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.

What broke when the tests ran against the real code?

Two bugs: raising a bare pydantic ValidationError as the HTTPException detail crashed on a non-serializable object, and an uncaught httpx.ConnectError reached the client as a raw 500 instead of a 502.

Is this the same retry policy as the asyncio and httpx guide?

Yes. client.py is that guide's asyncio_api.py and async_retry.py unchanged, so every retry and billing rule documented there applies here too.

Bottom line: validate with pydantic before any network call, cache repeat lookups for free in a short-lived per-process TTLCache, and reuse the asyncio quickstart's retry policy through a shared async client. Every behaviour here, including the two bugs the test suite caught, came from running pytest against real code with only the HTTP layer faked - see the asyncio and httpx guide 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