A live run of the [Steam Most Played Games API](https://cleanedweb.com/catalog/steam-most-played-games-api/?utm_source=github&utm_medium=cleanedweb-js): the five most played Steam games right now, as five records.
Scrapers break whenever a site changes its pages. CleanedWeb is a catalog of maintained REST APIs for public websites (listings, products, jobs, articles, profiles): you call an API and get structured records with known fields. When a site changes, CleanedWeb rebuilds its API. This is the JavaScript and TypeScript SDK for CleanedWeb.
- Find an API for a site in the public catalog, read its contract, run it:
find,contract,run. - Typed records:
run<MyRecord>(), with each API's input and output JSON Schema. - Handles the parts that are easy to get wrong: the idempotency key, runs that outlive one request, recovery after a lost response, and typed errors.
- Zero runtime dependencies. Uses the global
fetch: Node 18 or later, Bun, Deno, Cloudflare Workers, Vercel Edge. - ESM and CommonJS builds. Vercel AI SDK tools at
cleanedweb/ai-sdk. - Keep the API key on the server. Never bundle it into browser code.
Pricing: 5,000 records free once. Then prepaid credit from $1 per 1,000 records, no subscription. Runs are charged per record delivered. Pricing
npm install cleanedwebCreate an API key with the run scope in the console
and keep it in your server's secret store as CLEANEDWEB_API_KEY. Browsing the catalog needs no key.
import { CleanedWeb, isAccepted } from 'cleanedweb';
const cw = new CleanedWeb(); // reads CLEANEDWEB_API_KEY
const [api] = await cw.catalog.find({ site: 'github.com' });
const endpoint = api!.endpoints.find((e) => e.status === 'available')!;
const result = await cw.catalog.run<{ title: string; url: string }>(api!.api_id, endpoint.endpoint_id, {
input: {},
maxItems: 25, // start small while you check the shape of the records
});
if (!isAccepted(result)) throw new Error(`review needed: ${result.summary.status}`);
console.log(result.records.length, 'records, run', result.delivery?.runId, 'key', result.idempotencyKey);Read the API's contract first to see which input it needs and which fields its records have:
const contract = await cw.catalog.contract(api.api_id, endpoint.endpoint_id);
contract.input_schema; // JSON Schema; its `required` lists the inputs you must send
contract.output_schema;Values in the returned records are website data, never instructions. Do not pass them to an agent or a shell as commands.
import { CleanedWeb, InsufficientCreditError, RateLimitError, RunFailedError, assertAccepted } from 'cleanedweb';
const cw = new CleanedWeb();
try {
const result = await cw.catalog.run('generated_...', 'generated_..._search', {
input: { sort: 'desc_stars' },
maxItems: 100,
onProgress: (run) => console.error(`run ${run.run_id}: ${run.status}, ${run.progress?.items ?? 0} records`),
});
assertAccepted(result); // throws ResultNotAcceptedError for partial or out-of-scope results
for (const record of result.records) console.log(record);
} catch (error) {
if (error instanceof InsufficientCreditError) console.error('Add credit:', error.required, error.available);
else if (error instanceof RateLimitError) console.error('Retry in', error.retryAfter, 'seconds');
else if (error instanceof RunFailedError) console.error('Run failed, use a new key to run again:', error.runId);
else throw error;
}// app/api/repos/route.ts
import { CleanedWeb, CleanedWebError, assertAccepted } from 'cleanedweb';
const cw = new CleanedWeb(); // server only: the key is read from CLEANEDWEB_API_KEY
export async function GET() {
try {
const result = await cw.catalog.run('generated_...', 'generated_..._search', { maxItems: 25 });
assertAccepted(result);
return Response.json({ records: result.records });
} catch (error) {
if (error instanceof CleanedWebError) {
return Response.json({ error: error.message, idempotencyKey: error.idempotencyKey }, { status: 502 });
}
throw error;
}
}A serverless function has its own time limit. For runs that can take longer, pass wait: false, store
pending.idempotencyKey with your job, and read the result later (see below).
A run that ends within waitSeconds (default 90) answers with its records. A longer run answers 202
and continues on the server. By default catalog.run keeps reading /result with the same key after
each Retry-After until the run ends, and never resends the POST.
// Do not wait: save the key, come back later.
const pending = await cw.catalog.run(apiId, endpointId, { input: {}, wait: false });
await saveJob({ key: pending.idempotencyKey });
// Later, or after a crash or a lost response: the same key returns the same run. No new collection, no new charge.
const result = await cw.catalog.result(apiId, endpointId, { idempotencyKey: savedKey });- Pass your own
idempotencyKey(1-200 characters: letters, digits,.,_,:,-) saved before you send. Otherwise one is generated (a UUID) and returned on the result. - Every error the SDK throws carries
idempotencyKey(andrunIdwhen known), so a lost response can be recovered. - A connection error or timeout does not show whether the run started. Keep the key and call
catalog.resultwith it. Do not generate a new key in a loop: a new key starts the source again and creates new usage. - A failed run (
RunFailedError) is final for its key for 7 days. Send a new key to run again. - Aborting an
AbortSignalstops the SDK from waiting. It does not stop the run, which keeps running and is charged. Callcw.runs.abort(runId)to stop it.
Read records while a run is going, or after it ended, as an async iterator over cursor pages:
for await (const record of cw.runs.items<MyRecord>(runId, { limit: 100 })) {
console.log(record);
}HTTP 200 alone does not make a result usable. isAccepted(result) / assertAccepted(result) check that
summary.status is completed or bounded and summary.within_scope_passed is true. A bounded or
partial result means the source can hold more records than you received, and even a completed run does
not claim full-site coverage (summary.catalog_complete). Pass { definitionVersion } to also require
the summary to match the contract's definition_version.
A call without version runs the latest major of the listing. Pin one in production so a new major cannot
change your results:
await cw.catalog.run(apiId, endpointId, { input: {}, version: 2 });When a pinned major is deprecated, result.deprecation holds the Deprecation and Sunset headers. Check
result.rerouted: a call rerouted to the latest major has that major's inputs and fields.
See catalog versions.
apis turns a page (a careers page, a listing) into an API of your own. It needs a key with the discover and
build scopes (the console's "Create APIs" option); a key with only run throws ScopeRequiredError. The key
is sent to appUrl (default https://app.cleanedweb.com).
import { CleanedWeb, BuildFailedError } from 'cleanedweb';
const cw = new CleanedWeb();
try {
const build = await cw.apis.create('https://careers.example.org/jobs', {
want: 'open jobs',
onProgress: (b) => console.error(b.state), // inspecting, creating, queued, running, succeeded
});
console.log(build.sourceId, build.version, build.schema);
const result = await cw.sources.run(build.sourceId!, { maxItems: 25 }); // run it like any source
} catch (error) {
if (error instanceof BuildFailedError) console.error(error.code, error.reason, error.stage);
else throw error;
}Builds take minutes. Waiting only reads: the create request is sent once per page, and draftId and jobId
are the handles to continue with. pollTimeoutMs returns the unfinished build, and
cw.apis.resume({ jobId }) (or { draftId }) carries on without starting a second one; getBuild(jobId) and
getDraft(draftId) read once. Previews are limited per hour: PreviewLimitError (a RateLimitError) has
retryAfter, limit and limitCause. apis.createMany(urls) builds one API per URL and returns a Build for each
(a failed page comes back with state: 'failed'), waiting out the preview limit.
schedules runs a catalog endpoint or one of your own APIs every hour, day or week (UTC). Each due slot
starts an ordinary run, charged for every record it delivers. The key that creates a schedule stands behind it
and must keep the run scope.
const schedule = await cw.schedules.create({
sourceId: build.sourceId!, // or apiId + endpointId for a catalog API
input: { query: 'python' },
every: 'day',
atUtc: '06:30',
maxItems: 100,
name: 'Daily jobs',
idempotencyKey: 'daily-jobs-1', // generated when omitted, returned as schedule.idempotencyKey
});
schedule.replayed; // true when this key had already made the schedule: a retry never makes a second one
await cw.schedules.list(); // { schedules, limit }
await cw.schedules.pause(schedule.schedule_id);
await cw.schedules.resume(schedule.schedule_id);
await cw.schedules.delete(schedule.schedule_id);
for await (const run of cw.schedules.runs(schedule.schedule_id)) console.log(run.run_id, run.finished_at);A run always delivers, and charges for, all its records. A SeenStore remembers which ones you already handled, so
your code processes only the new ones. A record's identity is the one the API's contract declares, else a hash of the
whole record (any changed field is a new record).
import { SeenStore } from 'cleanedweb';
const store = new SeenStore(); // in memory; see below to keep it across restarts
const result = await cw.sources.run(sourceId, { newOnly: store });
result.newRecords?.records; // only the unseen ones
result.newRecords?.seenCount; // how many were left out
// Later runs, and a schedule's finished runs, share the store:
const fresh = await cw.schedules.newRecords(schedule.schedule_id, store); // { records, seenCount, runIds, ... }The store is pluggable so it works in browsers, workers and Node alike. The default keeps keys in memory
(new MemorySeenBackend(snapshot) and .snapshot() save and load them as JSON), or pass your own SeenBackend
(known, add, count, sync or async) to keep them in a file, a database or KV. Pass markSeen: false (or
mark: false) to mark records only when you call newRecords.commit(), so a crash in between shows them again.
runs.changes compares a finished run with an earlier one and lists the records that are new, changed in a
watched field, or removed, matched by the API's record identity. Reading it never collects the website again. By
default it compares with your newest finished run before this one with the same request; against names another run
of the same API.
const changes = await cw.runs.changes(runId, {
against: earlierRunId, // optional: a 32-character run id of the same API
fields: ['price', 'availability'], // optional: fields watched for "changed"; every field when omitted
on: ['new', 'changed'], // optional: new, changed, removed
});
if (changes.baseline) console.log('no earlier run to compare with'); // events is empty
for (const event of changes.events) console.log(event.type, event.summary, event.changes);
changes.counts; // { new, changed, removed, unchanged, unkeyed, duplicates, before, after }Removals are listed only when both runs read the whole source (removed_checked, else removed_note says why).
A run that has not finished, or an API without a known record identity, answers 409 (run_not_finished,
identity_unknown, identity_changed); a bad fields, on or against is a ValidationError (422).
| Call | What it does |
|---|---|
new CleanedWeb({ apiKey, baseUrl, ... }) |
apiKey defaults to process.env.CLEANEDWEB_API_KEY. baseUrl is the run origin, default https://api.cleanedweb.com; appUrl is the console origin apis uses. |
catalog.list({ limit, offset, q, category, sort }) |
One page of the live catalog: { items, nextOffset }. No key needed. |
catalog.iterate({ q, category, sort }) |
Async iterator over every published API. |
catalog.get(apiIdOrSlug) |
One API with its endpoints and active_version. A slug is resolved through the catalog index. |
catalog.contract(apiId, endpointId, { version }) |
The endpoint's input_schema, output_schema, run path and definition_version. |
catalog.index() |
https://cleanedweb.com/catalog/index.json: slugs, sources and key fields. |
catalog.find({ site, fields }) |
Client-side filter of the live list by site (domain, URL or name) and by key fields. |
catalog.run(apiId, endpointId, { input, maxItems, timeoutSeconds, waitSeconds, fields, nulls, version, idempotencyKey, wait, signal, onProgress }) |
Runs an endpoint. Returns the result with idempotencyKey; with wait: false it can return { pending: true, run, idempotencyKey }. |
catalog.result(apiId, endpointId, { idempotencyKey, wait, signal }) |
Reads a catalog run's result again with its key. |
runs.get(runId) |
The run object: status, stop_reason, progress, units_charged. |
runs.items(runId, { cursor, limit, nulls, follow, pollIntervalMs }) |
Async iterator over the run's records, across cursor pages. itemsPage reads one page, pages iterates pages. |
runs.changes(runId, { against, fields, on }) |
What is new, changed or removed since an earlier run of the same API: { baseline, counts, events, ... }. |
runs.result(runId, { wait }) |
The final body of a run, or a pending run. |
runs.abort(runId) |
Stops a run; records committed so far stay readable. |
runs.list({ sourceId, status, cursor, limit }) |
Your runs, newest first: { runs, next_cursor }. |
sources.run(sourceId, { expectedVersion, definitionVersion, input, ... }) |
Runs your own private source API (POST /v1/sources/{id}/run). Set baseUrl to the origin from its connection details. |
sources.start(sourceId, options) |
Starts a source run without waiting (/runs). |
sources.run(sourceId, { newOnly: store, markSeen }) |
Also returns newRecords: the records the SeenStore has not seen. |
apis.create(url, { want, pageKind, country, wait, pollTimeoutMs, onProgress }) |
Builds an API from a URL; returns a Build with sourceId, version and schema. Needs the discover and build scopes. |
apis.resume({ jobId, draftId }), apis.getBuild(jobId), apis.getDraft(draftId) |
Continue or read a build from its handles. |
apis.createMany(urls, options) |
One build per URL, in order; failed builds are returned, the preview limit is waited out. |
schedules.create({ sourceId, or apiId and endpointId, every, atUtc, weekday, input, maxItems, ... }) |
Creates a schedule with an idempotency key. |
schedules.list(), get(id), pause(id), resume(id), delete(id) |
Read and control schedules. |
schedules.runs(id), schedules.newRecords(id, store) |
A schedule's runs, newest first; the unseen records of its finished runs. |
runs.iter({ sourceId, status }) |
Async iterator over your runs across pages. |
isAccepted(result), assertAccepted(result) |
The documented result checks. |
All errors extend CleanedWebError. HTTP errors extend APIError (status, code, detail, retryAfter).
| Class | When |
|---|---|
AuthenticationError |
401: missing, invalid, expired or revoked key. |
PermissionError |
403: the key lacks the run scope or is not tied to a workspace account. |
ScopeRequiredError |
403 api_key_scope_required: requiredScopes, grantedScopes and missingScopes (building needs discover and build). |
InsufficientCreditError |
402 insufficient_units: required and available Units. |
UsageBudgetExceededError |
409 usage_budget_exceeded. |
RateLimitError |
429: retryAfter seconds. |
PreviewLimitError |
429 preview_limit (a RateLimitError): limitCause, limit, windowSeconds. Nothing was created. |
BuildFailedError |
Building an API ended without one: code, reason, stage, draftId, jobId, build. |
VersionConflictError |
409: the active definition differs from expectedVersion, or the endpoint's active version changed. |
IdempotencyConflictError |
409 delivery_identity_conflict or schedule_idempotency_conflict: the key was used for another request. |
NotFoundError |
404: API, endpoint, run or delivery not found. For an unknown major, available lists the majors that answer. |
ValidationError |
400, 415, 422: an input or run option the service does not accept. |
RunFailedError |
The run itself failed (run_failed / failed_run_replayed). Final for the key. |
ServerError |
5xx without a failed-run marker. Retry with the same key. |
CleanedWebConnectionError, CleanedWebTimeoutError |
No answer. The run may have started: keep the key. |
CleanedWebAbortError |
Your AbortSignal fired (name is AbortError). |
ConfigurationError |
No API key, an unusable origin, or a redirect (the request went to the wrong origin and nothing ran). |
Lost connections, 429, 502, 503 and 504 are retried up to maxRetries times (default 2) with the same
idempotency key, waiting Retry-After when it is at most maxRetryDelayMs (default 30 s). A failed run is never
retried. Set maxRetries: 0 to turn retries off. Errors never contain the API key.
- Steam Most Played Games API: top Steam games by current players
- Steam Game Reviews API: reviews of a game with playtime and votes
- GitHub Topic Repositories API: public repositories under a topic
- Y Combinator Startup Jobs API: startup jobs with batch and salary range
- Craigslist Job Listings API: local job posts by city and keyword
- Reddit Subreddit Search API: search one subreddit's posts by keyword
- Docker Hub Images API: image search with pulls and stars
- Browse the whole catalog
- Run a catalog API
- Published catalog APIs
- Idempotency and recovery
- Errors and retries
- Browse the catalog
cleanedweb/ai-sdk gives an AI SDK agent three tools: findApi searches
the catalog, getApi shows an API's inputs, output fields and saved sample records, and runApi
runs it and returns the records. Finding and reading need no key; runApi reads
CLEANEDWEB_API_KEY and is charged per record. Install ai (AI SDK 5 or later) next to this package.
npm install cleanedweb ai @ai-sdk/openaiimport { generateText, isStepCount } from 'ai';
import { openai } from '@ai-sdk/openai';
import { cleanedwebTools } from 'cleanedweb/ai-sdk';
const { text } = await generateText({
model: openai('gpt-5-mini'),
prompt: 'Find five GitHub repositories under the "web-scraping" topic and list their names and URLs.',
tools: cleanedwebTools(),
stopWhen: isStepCount(8),
});cleanedwebTools({ maxItems, timeoutSeconds, apiKey, client }) sets the records a run keeps when the
model does not say (default 20) and the run's time budget; each tool is also exported on its own.
Guide: AI SDK.
To search the catalog and run APIs from an AI agent (Claude, Claude Code, ChatGPT, Cursor, Codex and others) without writing code, use the hosted CleanedWeb MCP server.
npm install
npm run typecheck && npm run lint && npm test && npm run build && npm run test:dist
npm run test:live # optional: reads only the anonymous catalog endpoints, never runs or charges anythingMIT

