To call an Amazon product API in Deno, send a GET request with the built in fetch to /api/amazon-product-lookup with an ASIN, a marketplace ID and your key in the X-Api-Key header, then run the file directly with deno run and no tsc, no package.json and no node_modules. Deno executes .ts files as-is and refuses filesystem, network and environment access by default, so every script in this post states exactly which host and which variables it needs on the command line. The same client shape exists for TypeScript on Node and as a Supabase Edge Function (itself a Deno runtime); this quickstart is the plain, general purpose Deno client the other two build on.
Key Takeaways
- No install and no build step: Deno runs .ts files directly;
deno checktype-checks them without emitting JS. - Secrets are read with Deno.env.get('NAME'), never process.env (that global does not exist unless --unstable-node-globals is set).
- Deno denies network, env, filesystem and subprocess access by default; a missing --allow-net or --allow-env throws NotCapable before any request is sent.
- buyBoxInfo.price (lookup) is a number or the string "N/A"; decode it to number|null, same as every other language in this series.
- deno compile bundles the script and the Deno runtime into one native binary, so a scheduled job or a teammate's machine needs no Deno install at all.
Prerequisites: Deno 2 and an API key
- Deno 2 or later (
curl -fsSL https://deno.land/install.sh | sh, or a package manager); no Node, no npm. - An API key, a free account includes 150 credits after e-mail verification, one credit per request.
- The key in the
SELLERMAGNET_API_KEYenvironment variable, so it never lands in your repository.
No install needed: save the files and run with deno
deno --version # 2.x or later; no npm, no node_modules
mkdir amazon-deno && cd amazon-deno
export SELLERMAGNET_API_KEY="your-key-here"
# save client.ts, retry.ts, lookup.ts, bulk.ts and test.ts here
deno check client.ts retry.ts lookup.ts bulk.ts # type-check, no build output
deno test --allow-env test.ts # runs the tested scenarios below
deno run --allow-net=sellermagnet-api.com \
--allow-env=SELLERMAGNET_API_KEY,SELLERMAGNET_API_BASE lookup.ts
Why does deno run refuse my own client's request?
Deno's permission model denies network, environment, filesystem and subprocess access by default, unlike Node where a script can read process.env or open a socket the moment it starts. Running client.ts with no flags fails before a single byte reaches the network, with a NotCapable error naming the exact permission missing. Pass only the two permissions the client actually uses, scoped to one host and two variable names, not a blanket --allow-all.
Real deno run output with no permission flags (Deno 2.9.8)
$ deno run smoke.ts
error: Uncaught (in promise) NotCapable: Requires env access to "SELLERMAGNET_API_BASE", run again with the --allow-env flag
const API_BASE = Deno.env.get("SELLERMAGNET_API_BASE") ?? "https://sellermagnet-api.com/api/";
^
at Object.getEnv [as get] (ext:deno_os/30_os.js:1:1291)
at file:///amazon-deno/client.ts:8:27
| Flag | Why | Rule |
|---|---|---|
| --allow-net=sellermagnet-api.com | the client's only fetch target | no wildcard host |
| --allow-env=SELLERMAGNET_API_KEY,SELLERMAGNET_API_BASE | the two variables the client reads | no blanket --allow-env |
| (no --allow-read / --allow-write / --allow-run) | the client never touches the filesystem or a subprocess | omit entirely |
How do I call the Amazon product API in Deno?
Build one small get helper around fetch and reuse it from every endpoint wrapper. AbortSignal.timeout(120_000) sets a 120 second timeout without an AbortController, since the server allows a request that long and an abandoned request is still billed. A transport level failure (DNS, a refused connection, the abort firing) never reaches the server, so it is tagged status: 0 and treated as retryable the same as a 503, never as a non-retryable 4xx.
client.ts - one fetch wrapper, X-Api-Key header, 120 s timeout
// client.ts - one fetch wrapper, X-Api-Key header, 120 s timeout.
// Deno needs no npm install and no tsconfig: this file runs as-is with `deno run`.
// Deno.env.get() is Deno's own way to read environment variables (process.env does not
// exist unless --unstable-node-globals is passed); Deno additionally requires each
// permission (--allow-net, --allow-env) to be granted explicitly on the command line, or
// the runtime throws a PermissionDenied error before this code ever sends a request.
const API_BASE = Deno.env.get("SELLERMAGNET_API_BASE") ?? "https://sellermagnet-api.com/api/";
export interface ApiErrorShape {
status: number;
message: string;
retryAfter: number; // seconds, 0 when the header was absent
}
/** Thrown for any non-2xx response or a failed JSON decode. */
export class ApiError extends Error {
status: number;
retryAfter: number;
constructor({ status, message, retryAfter }: ApiErrorShape) {
super(`${status}: ${message}`);
this.name = "ApiError";
this.status = status;
this.retryAfter = retryAfter;
}
}
/**
* Sends one GET to the API and returns the decoded `data` field.
* @param endpoint e.g. "amazon-product-lookup"
*/
export async function get<T>(endpoint: string, params: Record<string, string>): Promise<T> {
const url = new URL(API_BASE + endpoint);
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
// AbortSignal.timeout() is a built-in on Deno's runtime fetch; no AbortController needed.
let response: Response;
try {
response = await fetch(url, {
headers: { "X-Api-Key": Deno.env.get("SELLERMAGNET_API_KEY") ?? "" },
signal: AbortSignal.timeout(120_000), // the server allows a request this long
});
} catch (err) {
// A DNS failure, a refused connection or an aborted-by-timeout request never reaches
// the server, so it is never billed; surface it as its own status so callers can tell
// it apart from a real HTTP response.
throw new ApiError({ status: 0, message: `transport: ${err instanceof Error ? err.message : String(err)}`, retryAfter: 0 });
}
const retryAfter = Number.parseInt(response.headers.get("retry-after") ?? "0", 10) || 0;
let body: { success?: boolean; data?: T; message?: string };
try {
body = await response.json(); // a proxy's own error page is HTML, not JSON
} catch {
throw new ApiError({ status: response.status, message: response.statusText, retryAfter });
}
if (response.ok && body.success) return body.data as T;
throw new ApiError({ status: response.status, message: body.message ?? response.statusText, retryAfter });
}
Trimmed lookup response (documented example: B0CL61F39H on amazon.com)
{
"success": true,
"data": {
"productInfo": {
"asin": "B0CL61F39H",
"title": "PlayStation(R)5 console (slim)",
"buyBoxInfo": {"price": 444.99, "currencyCode": "USD", "sellerId": "Amazon"},
"link": "https://www.amazon.com/dp/B0CL61F39H"
}
}
}
lookupProduct decodes buyBoxInfo.price into a real TypeScript number | null, so a product with no featured offer comes back with price: null instead of failing the call or silently showing 0. Because this is real .ts, the compiler (not just an editor reading JSDoc) rejects a caller that forgets the null case.
lookup.ts - typed product lookup with an N/A safe price
// lookup.ts - typed wrapper for product lookup. decodePrice turns the endpoint's
// number-or-"N/A" into number|null, matching the shape every other language quickstart in
// this series uses so the three price formats stay comparable across posts.
import { get } from "./client.ts";
export interface BuyBoxInfo {
price: number | null;
currencyCode: string;
sellerId: string | null;
}
export interface ProductInfo {
asin: string;
title: string;
buyBoxInfo: BuyBoxInfo;
link: string;
}
function decodePrice(raw: number | "N/A" | null | undefined): number | null {
return typeof raw === "number" ? raw : null;
}
export async function lookupProduct(asin: string, marketplaceId: string): Promise<ProductInfo> {
const data = await get<{ productInfo: Record<string, unknown> }>("amazon-product-lookup", {
asin,
marketplace_id: marketplaceId,
});
const info = data.productInfo as Record<string, unknown>;
const buyBoxInfo = (info.buyBoxInfo ?? {}) as Record<string, unknown>;
return {
asin: String(info.asin),
title: String(info.title ?? ""),
buyBoxInfo: {
price: decodePrice(buyBoxInfo.price as number | "N/A" | null | undefined),
currencyCode: String(buyBoxInfo.currencyCode ?? ""),
sellerId: (buyBoxInfo.sellerId as string) ?? null,
},
link: String(info.link ?? ""),
};
}
| Status | Meaning | Charged | Client action |
|---|---|---|---|
200 | Success | Yes | Decode data |
400 | Bad or missing parameter | Only an endpoint's own 400 | Fix the call |
401 / 403 | Key or credits | No | Stop |
404 | Not found on this marketplace | Yes | Record, never retry |
429 | Concurrency or per-IP limit | No | Wait Retry-After |
500 | Internal error, no Retry-After | No, refunded | Retry once |
502 / 503 | Upstream / breaker | Yes | Wait, then retry |
retry.ts - retries that respect billing, including a transport-level status 0
// retry.ts - retries that respect billing: 429/500(once)/502/503 only. A transport-level
// failure (status 0, see client.ts) is retried the same as a 503 - it never reached the
// server, so a retry never pays twice. 400/401/403/404 are never retried.
import { ApiError } from "./client.ts";
const RETRYABLE = new Set([0, 429, 500, 502, 503]);
export async function withRetry<T>(call: () => Promise<T>, attempts = 4): Promise<T> {
let seen500 = false;
for (let attempt = 1; ; attempt++) {
try {
return await call();
} catch (err) {
if (!(err instanceof ApiError)) throw err;
const give500Twice = err.status === 500 && seen500;
if (!RETRYABLE.has(err.status) || give500Twice || attempt === attempts) throw err;
seen500 = seen500 || err.status === 500;
const backoff = 2 ** attempt * 100; // ms, small for the test harness
const wait = Math.max(backoff, err.retryAfter * 1000);
await new Promise((resolve) => setTimeout(resolve, wait));
}
}
}

Run many lookups with a concurrency-limited pool
There is no batch endpoint: product lookup takes one ASIN per request, so bulk work is a small worker pool kept under the per-key concurrency cap, not a bigger payload. runWithConcurrency below runs a fixed number of async workers over an array with plain Promises, no library; a single failing ASIN is recorded on its own row instead of rejecting the whole batch. For pacing thousands of ASINs end to end see the bulk ASIN lookup guide.
bulk.ts - a concurrency-limited pool; one ASIN failing never loses the rest
// bulk.ts - there is no batch endpoint, so bulk work is a small concurrency-limited pool,
// not a bigger payload. Deno's fetch shares the same per-IP limiter the API documents for
// every language, so an unlimited Promise.all over 200 ASINs trips 429s exactly like it
// would from Python or Go; runWithConcurrency caps how many lookups run at once and keeps
// going past a single ASIN's failure instead of rejecting the whole batch.
import { lookupProduct, type ProductInfo } from "./lookup.ts";
import { withRetry } from "./retry.ts";
import { ApiError } from "./client.ts";
export interface BulkResult {
asin: string;
product?: ProductInfo;
error?: string;
}
export async function runWithConcurrency(
asins: string[],
marketplaceId: string,
limit = 5,
): Promise<BulkResult[]> {
const results: BulkResult[] = new Array(asins.length);
let next = 0;
async function worker() {
while (true) {
const i = next++;
if (i >= asins.length) return;
const asin = asins[i];
try {
const product = await withRetry(() => lookupProduct(asin, marketplaceId));
results[i] = { asin, product };
} catch (err) {
results[i] = { asin, error: err instanceof ApiError ? err.message : String(err) };
}
}
}
const workers = Array.from({ length: Math.min(limit, asins.length) }, () => worker());
await Promise.all(workers);
return results;
}

How do I test a Deno Amazon API client without real credits?
Deno.test is built in, no test runner to install. The harness below replaces globalThis.fetch with a queue of canned responses and fails closed: a call past the end of the queue throws instead of silently reaching the real API, so a bug that sends one more request than expected is caught by the test, not by a credit bill. Every scenario in the table (a numeric price, "N/A", every status in the table above, a transport failure, an HTML error page from a proxy, and the concurrency pool's isolation and cap) runs against the unmodified client.ts/retry.ts/lookup.ts/bulk.ts above.
test.ts - Deno.test suite, fakes only globalThis.fetch, fails closed
// test.ts - Deno.test suite. Fakes only globalThis.fetch (fails closed on an unmatched
// call), the same convention this repo's other fake-fetch harnesses use, so every assertion
// exercises the real client.ts/retry.ts/lookup.ts/bulk.ts unmodified.
import { assertEquals, assertRejects } from "jsr:@std/assert@1";
import { ApiError } from "./client.ts";
import { lookupProduct } from "./lookup.ts";
import { withRetry } from "./retry.ts";
import { runWithConcurrency } from "./bulk.ts";
type FakeRule = (url: URL) => Response | Promise<Response>;
function installFakeFetch(rules: FakeRule[]): { calls: URL[]; restore: () => void } {
const original = globalThis.fetch;
const calls: URL[] = [];
let i = 0;
// @ts-ignore - test-only override of the global
globalThis.fetch = async (input: string | URL | Request) => {
const url = new URL(input instanceof Request ? input.url : input);
calls.push(url);
if (i >= rules.length) {
throw new Error(`fails closed: unmatched fetch call #${i} to ${url}`);
}
const rule = rules[i++];
return await rule(url);
};
return { calls, restore: () => { globalThis.fetch = original; } };
}
function jsonResponse(status: number, body: unknown, headers: Record<string, string> = {}) {
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });
}
Deno.env.set("SELLERMAGNET_API_KEY", "test-key");
const MP = "ATVPDKIKX0DER";
Deno.test("lookupProduct decodes a numeric buy box price", async () => {
const fake = installFakeFetch([
() => jsonResponse(200, { success: true, data: { productInfo: { asin: "B0CL61F39H", title: "Console", buyBoxInfo: { price: 444.99, currencyCode: "USD", sellerId: "Amazon" }, link: "https://x" } } }),
]);
try {
const product = await lookupProduct("B0CL61F39H", MP);
assertEquals(product.buyBoxInfo.price, 444.99);
} finally { fake.restore(); }
});
Deno.test("lookupProduct turns N/A into null, not 0", async () => {
const fake = installFakeFetch([
() => jsonResponse(200, { success: true, data: { productInfo: { asin: "B0X", title: "No offer", buyBoxInfo: { price: "N/A", currencyCode: "USD", sellerId: null }, link: "https://x" } } }),
]);
try {
const product = await lookupProduct("B0X", MP);
assertEquals(product.buyBoxInfo.price, null);
} finally { fake.restore(); }
});
Deno.test("400 is a free gate failure, never retried", async () => {
const fake = installFakeFetch([
() => jsonResponse(400, { success: false, message: "bad asin" }),
]);
try {
await assertRejects(() => withRetry(() => lookupProduct("bad", MP)), ApiError, "400");
assertEquals(fake.calls.length, 1);
} finally { fake.restore(); }
});
Deno.test("401 and 403 stop immediately, no retry", async () => {
const fake = installFakeFetch([
() => jsonResponse(401, { success: false, message: "bad key" }),
]);
try {
await assertRejects(() => withRetry(() => lookupProduct("B0X", MP)), ApiError, "401");
assertEquals(fake.calls.length, 1);
} finally { fake.restore(); }
});
Deno.test("404 is billed and recorded, never retried", async () => {
const fake = installFakeFetch([
() => jsonResponse(404, { success: false, message: "not found" }),
]);
try {
await assertRejects(() => withRetry(() => lookupProduct("B0MISSING", MP)), ApiError, "404");
assertEquals(fake.calls.length, 1);
} finally { fake.restore(); }
});
Deno.test("429 is free and retried until it succeeds", async () => {
const fake = installFakeFetch([
() => jsonResponse(429, { success: false, message: "rate limited" }, { "retry-after": "0" }),
() => jsonResponse(200, { success: true, data: { productInfo: { asin: "B0X", title: "T", buyBoxInfo: { price: 1, currencyCode: "USD", sellerId: "A" }, link: "https://x" } } }),
]);
try {
const product = await withRetry(() => lookupProduct("B0X", MP));
assertEquals(product.asin, "B0X");
assertEquals(fake.calls.length, 2);
} finally { fake.restore(); }
});
Deno.test("500 is refunded and retried exactly once, then a second 500 gives up", async () => {
const fake = installFakeFetch([
() => jsonResponse(500, { success: false, message: "internal" }),
() => jsonResponse(500, { success: false, message: "internal" }),
]);
try {
await assertRejects(() => withRetry(() => lookupProduct("B0X", MP)), ApiError, "500");
assertEquals(fake.calls.length, 2);
} finally { fake.restore(); }
});
Deno.test("502/503 are billed but retried, capped at 4 attempts", async () => {
const fake = installFakeFetch([
() => jsonResponse(502, { success: false, message: "bad gateway" }),
() => jsonResponse(503, { success: false, message: "breaker open" }),
() => jsonResponse(502, { success: false, message: "bad gateway" }),
() => jsonResponse(503, { success: false, message: "breaker open" }),
]);
try {
await assertRejects(() => withRetry(() => lookupProduct("B0X", MP)), ApiError, "503");
assertEquals(fake.calls.length, 4);
} finally { fake.restore(); }
});
Deno.test("a transport failure (status 0) is retried the same as a 503", async () => {
const fake = installFakeFetch([
() => { throw new TypeError("network error"); },
() => jsonResponse(200, { success: true, data: { productInfo: { asin: "B0X", title: "T", buyBoxInfo: { price: 1, currencyCode: "USD", sellerId: "A" }, link: "https://x" } } }),
]);
try {
const product = await withRetry(() => lookupProduct("B0X", MP));
assertEquals(product.asin, "B0X");
} finally { fake.restore(); }
});
Deno.test("a proxy's HTML error page is treated as a non-2xx, not a crash", async () => {
const fake = installFakeFetch([
() => new Response("<html>502 Bad Gateway</html>", { status: 502, headers: { "content-type": "text/html" } }),
() => jsonResponse(200, { success: true, data: { productInfo: { asin: "B0X", title: "T", buyBoxInfo: { price: 1, currencyCode: "USD", sellerId: "A" }, link: "https://x" } } }),
]);
try {
const product = await withRetry(() => lookupProduct("B0X", MP));
assertEquals(product.asin, "B0X");
} finally { fake.restore(); }
});
Deno.test("bulk: one ASIN failing never loses the rest of the batch", async () => {
const fake = installFakeFetch([
() => jsonResponse(200, { success: true, data: { productInfo: { asin: "B0GOOD1", title: "T1", buyBoxInfo: { price: 1, currencyCode: "USD", sellerId: "A" }, link: "https://x" } } }),
() => jsonResponse(404, { success: false, message: "not found" }),
() => jsonResponse(200, { success: true, data: { productInfo: { asin: "B0GOOD2", title: "T2", buyBoxInfo: { price: 2, currencyCode: "USD", sellerId: "A" }, link: "https://x" } } }),
]);
try {
const results = await runWithConcurrency(["B0GOOD1", "B0BAD", "B0GOOD2"], MP, 1);
assertEquals(results.map((r) => r.asin), ["B0GOOD1", "B0BAD", "B0GOOD2"]);
assertEquals(results[1].error?.includes("404"), true);
assertEquals(results[0].product?.asin, "B0GOOD1");
assertEquals(results[2].product?.asin, "B0GOOD2");
} finally { fake.restore(); }
});
Deno.test("bulk: concurrency limit caps in-flight requests, never serializes to 1", async () => {
let inFlight = 0;
let maxInFlight = 0;
const fake = installFakeFetch(Array.from({ length: 6 }, () => async () => {
inFlight++;
maxInFlight = Math.max(maxInFlight, inFlight);
await new Promise((r) => setTimeout(r, 20));
inFlight--;
return jsonResponse(200, { success: true, data: { productInfo: { asin: "B0X", title: "T", buyBoxInfo: { price: 1, currencyCode: "USD", sellerId: "A" }, link: "https://x" } } });
}));
try {
await runWithConcurrency(["A", "B", "C", "D", "E", "F"], MP, 3);
assertEquals(maxInFlight, 3);
} finally { fake.restore(); }
});
Deno.test("fails closed: an unmatched fetch call throws instead of silently passing", async () => {
const fake = installFakeFetch([]);
try {
await assertRejects(() => lookupProduct("B0X", MP), Error, "fails closed");
} finally { fake.restore(); }
});
Real output from deno test --allow-env test.ts (Deno 2.9.8, this machine)
Check test.ts
running 13 tests from ./test.ts
lookupProduct decodes a numeric buy box price ... ok (25ms)
lookupProduct turns N/A into null, not 0 ... ok (1ms)
400 is a free gate failure, never retried ... ok (3ms)
401 and 403 stop immediately, no retry ... ok (737µs)
404 is billed and recorded, never retried ... ok (1ms)
429 is free and retried until it succeeds ... ok (231ms)
500 is refunded and retried exactly once, then a second 500 gives up ... ok (210ms)
502/503 are billed but retried, capped at 4 attempts ... ok (1s)
a transport failure (status 0) is retried the same as a 503 ... ok (203ms)
a proxy's HTML error page is treated as a non-2xx, not a crash ... ok (202ms)
bulk: one ASIN failing never loses the rest of the batch ... ok (1ms)
bulk: concurrency limit caps in-flight requests, never serializes to 1 ... ok (44ms)
fails closed: an unmatched fetch call throws instead of silently passing ... ok (2ms)
ok | 13 passed | 0 failed (2s)
Ship it as one binary with deno compile
deno compile bundles the script, its imports and the Deno runtime itself into one native executable, so a server, a cron box or a teammate's laptop can run the lookup with no Deno install at all, just the binary. The permission flags move to compile time and are baked into the result; a compiled binary with --allow-net=sellermagnet-api.com still refuses to reach any other host at runtime.
One command, one portable binary
deno compile \
--allow-net=sellermagnet-api.com \
--allow-env=SELLERMAGNET_API_KEY,SELLERMAGNET_API_BASE \
--output amazon-lookup lookup-cli.ts
./amazon-lookup B0CL61F39H ATVPDKIKX0DER # runs with no Deno install on this machine
Frequently Asked Questions
Do I need a tsconfig.json or a build step?
No. Deno runs .ts files directly and type-checks with deno check; there is no tsc, no bundler and no node_modules in this quickstart.
Why Deno.env.get instead of process.env?
process.env does not exist in Deno by default. Deno.env.get('NAME') is the documented way to read an environment variable, and it requires an explicit --allow-env grant naming that variable.
What happens if I forget --allow-net?
Deno throws a NotCapable error naming the missing permission before the request is attempted; nothing is sent and nothing is billed.
Is there a Deno SDK for the SellerMagnet API?
No, and none is needed. Every endpoint is a plain GET with query parameters and a JSON body, so the built in fetch and a handful of TypeScript interfaces cover it.
Do the old PA-API libraries work from Deno via npm: specifiers?
No. PA-API 5 answers every call with an AccessDenied error that points to Amazon's Creators API, which is for affiliates with qualifying sales, regardless of the runtime making the call.
Can I schedule this without installing Deno on the target machine?
Yes: deno compile produces a single native binary with the runtime and permissions baked in, so the target machine only needs that one file.
Bottom line: real TypeScript with no build step, a fetch client scoped to exactly the host and two environment variables it needs, retries for 429, 500, 502, 503 and a transport failure, a concurrency-limited pool instead of a batch call that does not exist, and a deno compile binary for machines with no Deno install. The same client pattern exists for TypeScript on Node and Python; more snippets are on the code examples page, and every endpoint is in the API documentation.