Home / Blog / Amazon Product API in Bun: Native fetch, bun:test and Zero-Config TypeScript

Amazon Product API in Bun: Native fetch, bun:test and Zero-Config TypeScript

Call an Amazon product API from Bun with nothing but the standard fetch() it ships built in: no node-fetch, no axios, no tsc step. A small client puts the key in the X-Api-Key header, a 120-second AbortSignal in place of a timeout option fetch does not have, and a bun:test suite with a fails-closed fake fetch covers the billing edge cases before a single real credit is spent.

November 20, 2026
6 min read
SellerMagnet Team
Share & Bookmark
Code editor with the Bun client's AbortSignal.timeout line that replaces a timeout option fetch does not have

To call an Amazon product API from Bun, send a GET request with Bun's built-in fetch() to /api/amazon-product-lookup with an ASIN, a marketplace ID and your key in the X-Api-Key header, then read the JSON body. Bun runs .ts files directly (no tsc build step, no ts-node), ships fetch() and a test runner in the runtime itself, so this quickstart needs zero npm dependencies: one client, one retry helper, and a bun:test suite that fakes only the network.

Key Takeaways

  • Bun's fetch() has no timeout option (unlike Node's http.request or Python's requests): the 120-second budget comes from AbortSignal.timeout(120_000) passed as the signal option, the same pattern a browser fetch would use.
  • .env files load automatically (process.env and Bun.env both see them), so the API key never needs a loader package, just SELLERMAGNET_API_KEY=... bun run main.ts.
  • Send the key in the X-Api-Key header, not the api_key query parameter: a key left in a URL lands in shell history and proxy logs.
  • buyBoxInfo.price is a JSON number or the string "N/A"; check typeof price === "number" before using it; the sibling Python quickstart hits the same field.
  • Retry 429 and a lone 500 (refunded); stop after a second 500 in a row; retry 502/503 and a timeout (AbortError) up to 4 attempts; never retry 404 or a free 400, they are final, billed answers.

Prerequisites: Bun and an API key

  • Bun 1.0 or later; this code was built and run on Bun 1.4.4 for Linux, installed with the one-line curl -fsSL https://bun.sh/install | bash (no Node.js required alongside it).
  • No npm dependency for the client itself: fetch, URL and AbortSignal are all globals in the Bun runtime.
  • An API key: a free account includes 150 credits after e-mail verification, one credit per request.
  • The key in the SELLERMAGNET_API_KEY environment variable (or a .env file, which Bun loads with no extra package), so it never lands in your repository.

Install Bun and run the client directly

curl -fsSL https://bun.sh/install | bash   # installs to ~/.bun/bin, no Node.js required
mkdir amazon-bun && cd amazon-bun
# save client.ts, retry.ts and main.ts from this post - no npm install, no tsconfig needed
export SELLERMAGNET_API_KEY="your-key-here"
bun run main.ts                     # at most 1 credit per ASIN, see the credit math below
bun test test.ts                    # runs the fails-closed fake-fetch test suite, no credits spent

How do I call the Amazon product API from Bun?

Build the URL with URLSearchParams, send the key as a header, and set a 120-second AbortSignal because the API can take that long and plain fetch() never times out on its own. get() returns the decoded data object on a 200 with success: true, and raises an ApiError carrying the status, the API's own message and any Retry-After otherwise, the same shape as the Python and Swift clients.

client.ts - fetch, one exception type, no timeout option to lean on

// client.ts - a small client with one exception type, ported for Bun's native fetch
const API = "https://sellermagnet-api.com/api";

export class ApiError extends Error {
  status: number;
  retryAfter: number;
  constructor(status: number, message: string, retryAfter = 0) {
    super(`${status}: ${message}`);
    this.status = status;
    this.retryAfter = retryAfter;
  }
}

// Bun reads .env automatically and exposes it on both Bun.env and process.env;
// use process.env so the same source also runs unchanged under Node.
function apiKey(): string {
  const key = process.env.SELLERMAGNET_API_KEY;
  if (!key) throw new Error("SELLERMAGNET_API_KEY is not set");
  return key;
}

export async function get(endpoint: string, params: Record<string, string | number>): Promise<any> {
  const url = new URL(`${API}/${endpoint}`);
  for (const [k, v] of Object.entries(params)) url.searchParams.set(k, String(v));
  // Bun's fetch has no built-in per-request timeout option (unlike Node's { timeout }),
  // so the 120s budget is enforced with AbortSignal.timeout, same as plain browser fetch.
  const resp = await fetch(url, {
    headers: { "X-Api-Key": apiKey() },
    signal: AbortSignal.timeout(120_000),
  });
  let body: any = {};
  try {
    body = await resp.json();
  } catch {
    body = {}; // e.g. an HTML page from a proxy
  }
  if (resp.status === 200 && body?.success) return body.data;
  const retryAfterHeader = resp.headers.get("Retry-After");
  const retryAfter = retryAfterHeader ? parseFloat(retryAfterHeader) || 0 : 0;
  throw new ApiError(resp.status, body?.message ?? "request failed", retryAfter);
}

export async function lookup(asin: string, marketplaceId: string) {
  const data = await get("amazon-product-lookup", { asin, marketplaceId });
  const p = data.productInfo;
  const price = p.buyBoxInfo?.price;
  return {
    asin: p.asin,
    title: p.title,
    price: typeof price === "number" ? price : null, // "N/A" = no featured offer
    currency: p.buyBoxInfo?.currencyCode ?? null,
    rank: p.bestsellerRanks?.main_category?.rank ?? null,
    url: p.link,
  };
}

if (import.meta.main) {
  const result = await lookup("B0CL61F39H", "ATVPDKIKX0DER");
  console.log(result);
}

A non-2xx response is not always JSON: a proxy in front of the API can answer a 429 or 502 with an HTML page. resp.json() throwing is caught and treated as an empty body, so the status code still decides the outcome instead of a SyntaxError crashing the program. body?.success also guards against a 200 whose body is simply missing the field.

Which errors should a Bun client retry?

Only the ones a second try can fix. A 429 from the per-key concurrency cap is free and carries Retry-After. A lone 500 is refunded, so one retry costs nothing, but a second 500 in a row stops the loop rather than retrying forever. 502 and 503 are billed on every attempt, so cap the attempts and honour Retry-After. AbortSignal.timeout raises a DOMException named AbortError, not an ApiError, since no HTTP response ever arrived; this client retries that like any other transport failure, up to the same attempt cap. A 404 is a real, billed answer: the ASIN is not on that marketplace, and retrying only buys the same answer again.

Status codes, billing and the right Bun client reaction (November 2026).
StatusMeaningChargedClient action
200successYesDecode data
400bad parameter or uncovered marketplaceOnly an endpoint's own 400Fix the call
401 / 403key or creditsNoStop the run
404not on this marketplaceYesRecord, never retry
429concurrency cap fullNoWait Retry-After, retry
500internal error, no Retry-AfterNo, refundedRetry once
502 / 503retryable error / unavailableYesWait, retry, cap at 4
AbortError (timeout)no answer in 120 sYesReport, retry like a transport error

retry.ts - retries only what a second attempt can fix

// retry.ts - retries only where a second attempt can help
import { ApiError, get } from "./client";

const RETRYABLE = new Set([429, 500, 502, 503]);

export async function getWithRetry(endpoint: string, params: Record<string, string | number>, attempts = 4): Promise<any> {
  let internalErrors = 0;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return await get(endpoint, params);
    } catch (err) {
      if (err instanceof ApiError) {
        if (err.status === 500) internalErrors += 1;
        if (!RETRYABLE.has(err.status) || attempt === attempts || internalErrors > 1) {
          throw err; // a second 500 in a row: report it, don't loop
        }
        const backoff = Math.min(2 ** attempt, 30) + Math.random();
        await sleep(Math.max(backoff, err.retryAfter) * 1000);
        continue;
      }
      // Transport-level failure (timeout/AbortError, DNS, connection reset): worth a retry too,
      // same as requests.ConnectionError/Timeout in the Python client.
      if (attempt === attempts) throw err;
      await sleep(Math.min(2 ** attempt, 30) * 1000);
    }
  }
  throw new Error("unreachable");
}

function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
Sequence diagram of a Bun client retrying a free 429 after Retry-After, then recording a billed 404 without retrying
Wait and retry a free 429; record a billed 404 and move on.

How do I test a fetch client in Bun without spending credits?

Override globalThis.fetch before the test file imports the client, and fail closed: any call that reaches the fake without a scripted route throws, so an untested code path can never quietly hit the real API. bun:test ships in the runtime (no Jest, no ts-jest config) and runs the whole suite in milliseconds because there is no real network and no process-startup cost per test.

test.ts (excerpt) - a fails-closed fake fetch feeding bun:test

// test.ts (excerpt) - the fails-closed fake fetch and two representative scenarios
import { describe, expect, test } from "bun:test";
import { ApiError, lookup } from "./client";
import { getWithRetry } from "./retry";

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

let route: ((endpoint: string, params: URLSearchParams) => { status: number; body: any }) | null = null;

function install(r: typeof route) {
  route = r;
}

globalThis.fetch = async (url: any, init: any) => {
  if (!route) throw new Error("fakefetch: install(route) first - no real request may leave the harness");
  if (init?.headers?.["X-Api-Key"] !== "test-key") throw new Error("missing X-Api-Key header");
  const u = new URL(String(url));
  const res = route(u.pathname.split("/").pop()!, u.searchParams);
  return new Response(JSON.stringify(res.body), { status: res.status });
};

test("a SECOND consecutive 500 stops instead of looping forever", async () => {
  install(() => ({ status: 500, body: { success: false, message: "internal" } }));
  await expect(getWithRetry("amazon-product-lookup", { asin: "X" }, 4)).rejects.toBeInstanceOf(ApiError);
});

test("N/A price string becomes null, not NaN", async () => {
  install(() => ({ status: 200, body: { success: true,
    data: { productInfo: { asin: "X", title: "T", link: "u", buyBoxInfo: { price: "N/A" } } } } }));
  const r = await lookup("X", "ATVPDKIKX0DER");
  expect(r.price).toBeNull();
});
JSON field shapes and the TypeScript types that map them safely (November 2026).
FieldEndpointJSON valueTypeScript type
buyBoxInfo.pricelookup444.99 or "N/A"number | null
titlelookupalways a stringstring
bestsellerRanks.main_category.ranklookupmissing when unrankednumber | null
Retry-After headeranyseconds as text or absentnumber (parseFloat, default 0)
resp.json() on a proxy pageanyHTML, not JSONcaught, read as {} not a crash
Table mapping SellerMagnet API response fields to the TypeScript types the Bun client gives them, including number-or-null for a price that can be the string N/A
A price field is a number or null in this client's own types, never "N/A" as a string.

What does a multi-ASIN run look like end to end?

main.ts looks up three ASINs with getWithRetry, prints one row per product and counts the credits actually charged. The run below replays recorded, illustrative responses through the same fake-fetch harness as the test suite (so it can never drift from the real code): a 429 the client retries for free, a 500 that is refunded and retried once, and a 404 that is recorded without a second attempt.

main.ts - three ASINs, one row each, one bad row never loses the batch

// main.ts - look up a few products, one row per ASIN, never losing the batch to one bad row
import { ApiError } from "./client";
import { getWithRetry } from "./retry";

const MARKETPLACE_US = "ATVPDKIKX0DER";
const MARKETPLACE_UK = "A1F83G8C2ARO7P";

type Row = { asin: string; marketplaceId: string };

const ROWS: Row[] = [
  { asin: "B0CL61F39H", marketplaceId: MARKETPLACE_US }, // happy path, but the key is rate-limited first
  { asin: "B0CLTBHXWQ", marketplaceId: MARKETPLACE_UK }, // a transient 500, refunded and retried once
  { asin: "B0NOTAREAL", marketplaceId: MARKETPLACE_US }, // 404: a real answer, never retried
];

function fmt(asin: string, marketplaceId: string, price: number | null, currency: string | null, title: string) {
  const priceStr = price === null ? "N/A" : `${price.toFixed(2)} ${currency}`;
  return `${asin}  ${marketplaceId.padEnd(15)} ${priceStr.padEnd(14)} ${title.slice(0, 40)}`;
}

export async function main() {
  console.log("asin        marketplace     price          title");
  let credits = 0;
  for (const row of ROWS) {
    try {
      const data = await getWithRetry("amazon-product-lookup", { asin: row.asin, marketplaceId: row.marketplaceId });
      const p = data.productInfo;
      const price = typeof p.buyBoxInfo?.price === "number" ? p.buyBoxInfo.price : null;
      console.log(fmt(p.asin, row.marketplaceId, price, p.buyBoxInfo?.currencyCode ?? null, p.title));
      credits += 1;
    } catch (e) {
      if (e instanceof ApiError) {
        console.error(`${row.asin}: ${e.status} ${e.message.replace(/^\d+:\s*/, "")}`);
        if (e.status !== 400 && e.status !== 401 && e.status !== 403) credits += 1; // 404/500-eventually/etc billed once each here
      } else {
        console.error(`${row.asin}: transport error - ${(e as Error).message}`);
      }
    }
  }
  console.log(`credits charged: ${credits}`);
}

if (import.meta.main) await main();

Program output (illustrative data, replayed through the fake-fetch harness)

asin        marketplace     price          title
B0CL61F39H  ATVPDKIKX0DER   444.99 USD     PlayStation®5 console (slim)
B0CLTBHXWQ  A1F83G8C2ARO7P  34.99 GBP      Echo Dot (5th Gen, 2022 release)
B0NOTAREAL: 404 Invalid product
credits charged: 3

Credit math for that run: 3 requests shown, 3 credits charged. The first ASIN's initial 429 cost nothing; the second's transient 500 was refunded, so only its successful retry was billed; the 404 on the third is itself a billed, final answer. A 502 or 503 would have cost a credit on every one of up to 4 attempts instead. To test without spending real credits, override globalThis.fetch exactly as test.ts does, which is also how this program's own output above was generated.

Frequently Asked Questions

Is there an official Bun SDK for the SellerMagnet API?

No, and none is needed. Every endpoint is a plain GET with query parameters and a JSON body, so Bun's built-in fetch() and a couple of small .ts files cover it with zero npm dependencies.

Does this client also run on Node.js, not just Bun?

Yes, unchanged: fetch, URL and AbortSignal are Node.js globals since Node 18, and the code uses nothing Bun-specific. Running it under Bun just skips Node's slower cold start and the ts-node/tsx step .ts files need on plain Node.

Why does fetch() never time out in Bun by itself?

Because the Fetch standard fetch() has no built-in timeout option at all, on Bun, Node or in a browser. Pass signal: AbortSignal.timeout(120_000) to cap a request at 120 seconds, matching the time the API itself can take to answer.

How do I know if a thrown error is an API error or a timeout?

Check instanceof ApiError first: that type only exists for a response the API actually sent. Anything else, including the AbortError from AbortSignal.timeout, is a transport failure where no HTTP response arrived at all, so it carries no status code or billing information to read.

Why did bun:test say my fetch mock leaked into another test file?

globalThis.fetch = ... in one test file affects the whole process bun:test runs test files in, not just that file, if several files assign it without resetting. Scope the fake inside the file that needs it and restore or reinstall the route per test with beforeEach, as this post's test.ts does with install(route).

Bottom line: Bun's own fetch() plus an AbortSignal timeout, a key in the X-Api-Key header, number | null types that treat "N/A" as the absence of a price, and retries for 429, a lone 500, 502, 503 and a timeout that never resend a 404 or a free 400. Related runtimes: Python, Node.js/TypeScript; every endpoint is in the API documentation.

Related Articles

Continue exploring topics related to this article.

Terminal showing a buybox_pagerduty_alert.py script sending a trigger event to PagerDuty
Python Amazon API Alerts

Amazon Buy Box Lost PagerDuty Alert: Trigger and Resolve One Incident via the Events API v2

Turn a confirmed Amazon Buy Box loss into a PagerDuty incident with the Events API v2, then auto-resolve the same incident the moment you get the Buy Box back - using one dedup_key per ASIN so a flapping listing never opens a new incident for every check, in Python.

Nov 20, 2026 Read
Terminal showing an Apache Airflow DAG checking an Amazon Buy Box price via the SellerMagnet API
Python Amazon API Airflow

Amazon Price Tracking in Apache Airflow: XCom, Variables and the catchup Trap

Run a daily Amazon Buy Box price check as an Apache Airflow TaskFlow DAG. The SellerMagnet side is unchanged from the Python quickstart (sellermagnet.py/retry.py, byte-identical); the real content is Airflow-specific: the API key as a Connection instead of a bare environment variable, the price baseline in a Variable (the only state the DAG needs), XCom carrying just a small dict between tasks (never the raw response), and a catchup default that quietly flips between Airflow 2.x and Airflow 3.

Nov 20, 2026 Read
Terminal showing a Python price-watch script pushing Amazon Buy Box metrics to Datadog's v2 series API
Python Amazon API Monitoring

Amazon Buy Box Price Monitoring with Datadog Custom Metrics

Push Amazon Buy Box price, availability and offer-count metrics from the SellerMagnet API to Datadog as custom metrics via the v2 /series intake. sellermagnet.py / retry.py need zero changes from the Python quickstart. The real trap: Datadog's v2 payload wants an INTEGER metric type and a timestamp inside a strict +10min/-1h window, and a single bad timestamp in a batch can fail the whole POST, taking every other tracked ASIN's metrics down with it.

Nov 20, 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