@getanyapi/sdk

中文文档
0.154.0发布于 2026/11/16MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 4万

Official typed TypeScript SDK for AnyAPI: any API, one wallet, USD, no subscriptions.

原始使用文档
文档目录10 节
  1. Quickstart
  2. Not found vs error
  3. Discovery
  4. Pagination
  5. Request options (context-cost savers)
  6. Errors and retries
  7. Waiting out a run that is still in flight
  8. Agent signup
  9. Docs
  10. License

@getanyapi/sdk

Official typed TypeScript SDK for AnyAPI: any API, one wallet, USD, no subscriptions. Reach hundreds of scraping and data APIs through one interface and one key; pay per request in real US dollars. Zero runtime dependencies (global fetch), ESM + CJS, Node 18+ and edge runtimes.

npm install @getanyapi/sdk

Quickstart

import { AnyAPI } from "@getanyapi/sdk";

// Reads ANYAPI_API_KEY from the environment when apiKey is omitted.
const client = new AnyAPI({ apiKey: process.env.ANYAPI_API_KEY });

const res = await client.reddit.search({ query: "mechanical keyboard" });
if (res.output.found) {
  for (const post of res.output.data.posts) console.log(post.title, post.score);
}
console.log("charged", res.costUsd, "USD");

Every SKU is a typed method under its platform namespace (client.amazon.reviews(...), client.google.search(...)). You can also call any SKU generically by slug with full typing:

const rev = await client.run("amazon.reviews", {
  product: "B07FZ8S74R",
  limit: 3,
});

Not found vs error

A successful call always resolves. For most SKUs the payload is wrapped in a found flag: output.found is false when the upstream had no matching entity (this is not an error). Use unwrap to get the data or throw ResultNotFoundError when empty:

import { unwrap, ResultNotFoundError } from "@getanyapi/sdk";

const res = await client.amazon.reviews({ product: "B07FZ8S74R" });
try {
  const data = unwrap(res); // the typed data payload, or throws
} catch (e) {
  if (e instanceof ResultNotFoundError) {
    // empty result (found: false), not an HTTP failure
  }
}

ResultNotFoundError extends NotFoundError, so catch (NotFoundError) catches both an HTTP 404 and an empty result; catch ResultNotFoundError to handle only empty results. If a future committed schema uses a bare output, generated typing returns its data object directly rather than relying on a hard-coded SKU list.

Discovery

const apis = await client.catalog({ category: "search" });
const matches = await client.search({
  query: "web search",
  platform: "google",
  limit: 10,
});
const api = await client.describe(matches.results[0]!.slug);
console.log(api.pricing.from, api.pricing.failoverMaxUsd, api.inputSchema);

catalog is category-only browsing. Ranked queries always use search, which returns results, total, and ranking; describe includes schemas. Discovery prices are nested USD flat/linear offers, lanes are anonymous, and provider is always "AnyAPI". The gateway owns validation, routing, lane order, failover, pricing relationships, health semantics, and billing. This handwritten discovery client safety-scans the response, projects known fields, preserves schemas as opaque JSON, and ignores safe additions. It does not recompute gateway business rules. Generated per-SKU methods remain a separate OpenAPI-driven surface.

Every catalog and search result carries the gateway-authored method, path, and execution mode. Lanes carry their public source identity and complete health sample counts when health is available. Eligible APIs may carry tryMaxItems; ranked search carries the gateway's failover facts. describe also returns latency, either the complete trailing-window p50/p95/p99 distribution or null when no sample is available.

Pagination

Paginated SKUs expose an iterator that yields items across pages and follows the cursor for you. Call .pages() on it to walk whole results instead (each carries its own costUsd).

// Flatten items across pages, capped at 100 total.
for await (const post of client.reddit.iterSearch(
  { query: "coffee" },
  { maxItems: 100 },
)) {
  console.log(post.title);
}

// Or walk pages to read per-page cost.
for await (const page of client.reddit
  .iterSearch({ query: "coffee" })
  .pages()) {
  console.log(page.costUsd);
}

Request options (context-cost savers)

Pass a second argument to shape the response. These trim what comes back but do NOT change the price:

await client.google.search(
  { query: "coffee" },
  {
    fields: ["title", "link"], // keep only these keys on each item
    maxItems: 5, // cap result rows returned
    summary: true, // structural outline instead of full data
  },
);

Per-call transport overrides: timeoutMs, maxRetries, maxInProgressWaitMs, and an AbortSignal via signal.

Errors and retries

ClassHTTPMeaning
BadRequestError400Input failed validation
AuthenticationError401Missing or invalid API key
InsufficientBalanceError402Wallet balance or per-key cap exceeded
NotFoundError404Slug or resource does not exist
ResultNotFoundError-unwrap on an empty found-data result
RateLimitedError429Too many requests (retried automatically)
UpstreamError502An upstream backend failed
ConnectionError0Network or transport failure
TimeoutError0Request exceeded its timeout (not retried)

All extend AnyAPIError (with status and requestId). Retries cover 429, one specific 409 (below), and network failures proven to happen before a request was sent, with jittered exponential backoff honoring Retry-After. Default maxRetries is 2 (up to 3 attempts); set it on the client or per request. Timeouts are never retried. Connection failures during or after a billed POST /v1/run are not retried because the call may already have been charged. When the send phase is unknown, the SDK does not retry. Configure with new AnyAPI({ timeoutMs, maxRetries }).

Waiting out a run that is still in flight

Settlement is detached from your connection, so a run keeps going after a connection drops. When you re-issue a call whose Idempotency-Key is still executing, the gateway answers 409 with code: "idempotency_in_progress" and Retry-After: 30. The SDK waits that full delay and retries, so you get the original run's replayed result (replayed: true, no second charge) instead of an error.

The 8s ordinary-backoff ceiling does not apply here; a separate whole-call budget does. maxInProgressWaitMs (default 60000) caps the TOTAL time one run() may block on these waits, across every retry. A wait that does not fit the remaining budget is refused and the 409 is thrown rather than truncated into an attempt that would fail anyway. Set maxInProgressWaitMs: 0 to surface the 409 immediately and handle it yourself.

No other 409 retries: idempotency_conflict (the same key with different input) and idempotency_needs_review are caller-side problems a retry cannot fix.

Automatic network retry of a billed run() requires structured runtime evidence that the request body was not sent:

RuntimeAutomatic billed-run network retryEvidence available to the SDK
Node 18+ with built-in undici fetchYesDNS and connect codes, connect-phase timeouts, or an undici socket reporting zero bytes written
Bun 1.3.11YesConnectionRefused, which Bun 1.3.11 emits only while establishing the origin or proxy connection
Cloudflare WorkersNoretryable: true means transient, not undelivered; it can appear after the origin received the full body
DenoNoFetch exposes only prose without a structured connection code
BrowsersNoFetch generally exposes an opaque TypeError

On a runtime without strict non-delivery evidence, the SDK makes no automatic network retry for a billed run(). HTTP 429 retry is unchanged. Handle other retries explicitly only when your application can establish non-delivery.

Agent signup

Bootstrap a key with no account (for autonomous agents):

import { agentSignup } from "@getanyapi/sdk";

const { secret, capUsd } = await agentSignup({ label: "my-agent" });
const client = new AnyAPI({ apiKey: secret });

The key ships with a small starter balance and a per-key spend cap; to go past the cap, a human authorizes an AnyAPI wallet over OAuth, as described in agent self-signup.

Docs

Full API reference and catalog: getanyapi.com/docs.

License

MIT

版本与发布记录

@getanyapi/sdk 共发布 434 个版本,首次发布于 2026/07/06;过去 12 个月发布了 434 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.154.0latest2026/11/16今天
0.153.12026/11/16今天
0.153.02026/11/16今天
0.152.142026/11/16今天
0.152.132026/11/16今天
0.152.122026/11/16今天

关于 @getanyapi/sdk 的常见问题

@getanyapi/sdk 是什么?

Official typed TypeScript SDK for AnyAPI: any API, one wallet, USD, no subscriptions.

如何安装 @getanyapi/sdk?

在项目目录运行 npm install @getanyapi/sdk,或使用 pnpm add / yarn add / bun add。

@getanyapi/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@getanyapi/sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@getanyapi/sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@getanyapi/sdk 可以商用吗?

@getanyapi/sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@getanyapi/sdk 的下载量有多少?

根据 npm 官方下载统计,@getanyapi/sdk 在 2026/10/17 – 2026/11/15 这 30 天内被下载 39,819 次,日均约 1,327 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@getanyapi/sdk 还在维护吗?

最新版本 0.154.0 发布于 2026/11/16(今天);至今共发布 434 个版本,其中过去 12 个月发布了 434 个;首次发布于 2026/07/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。