apify-sdk-patterns
Production-ready patterns for Apify SDK and apify-client in TypeScript. Use when building Actors with Crawlee, managing datasets/KV stores, or implementing robust client wrappers with retry and validation. Trigger: "apify SDK patterns", "apify best practices", "apify client wrapper", "crawlee patterns", "idiomatic apify".
What this skill does
# Apify SDK Patterns
## Overview
Production patterns for both the `apify` SDK (building Actors) and `apify-client` (calling Actors remotely). Covers Crawlee crawler selection, data storage, proxy configuration, and typed client wrappers.
## Prerequisites
- `apify-client` and/or `apify` + `crawlee` installed
- `APIFY_TOKEN` configured
- TypeScript recommended
## Pattern 1: Typed Client Singleton
```typescript
// src/apify/client.ts
import { ApifyClient } from 'apify-client';
let instance: ApifyClient | null = null;
export function getApifyClient(): ApifyClient {
if (!instance) {
const token = process.env.APIFY_TOKEN;
if (!token) throw new Error('APIFY_TOKEN is required');
instance = new ApifyClient({ token });
}
return instance;
}
// Reset for testing
export function resetClient(): void {
instance = null;
}
```
## Pattern 2: Crawlee Crawler Selection
Choose the right crawler for the job:
```typescript
import { CheerioCrawler, PlaywrightCrawler, PuppeteerCrawler } from 'crawlee';
// CHEERIO — Fast, lightweight, no JavaScript rendering
// Use for: static HTML, server-rendered pages, APIs
const cheerioCrawler = new CheerioCrawler({
async requestHandler({ request, $, enqueueLinks }) {
const title = $('title').text();
await Actor.pushData({ url: request.url, title });
await enqueueLinks({ strategy: 'same-domain' });
},
});
// PLAYWRIGHT — Full browser, all engines, modern API
// Use for: SPAs, JavaScript-heavy pages, complex interactions
const playwrightCrawler = new PlaywrightCrawler({
launchContext: { launchOptions: { headless: true } },
async requestHandler({ page, request, enqueueLinks }) {
await page.waitForSelector('h1');
const title = await page.title();
const content = await page.$eval('main', el => el.textContent);
await Actor.pushData({ url: request.url, title, content });
await enqueueLinks({ strategy: 'same-domain' });
},
});
// PUPPETEER — Chromium-only browser automation
// Use for: when you need Chromium specifically or legacy Puppeteer code
const puppeteerCrawler = new PuppeteerCrawler({
async requestHandler({ page, request }) {
const title = await page.title();
await Actor.pushData({ url: request.url, title });
},
});
```
## Pattern 3: Actor Lifecycle with Error Handling
```typescript
import { Actor } from 'apify';
import { CheerioCrawler, log } from 'crawlee';
// Actor.main() wraps init + exit + error handling
await Actor.main(async () => {
const input = await Actor.getInput<{
startUrls: { url: string }[];
maxPages?: number;
proxyConfig?: { useApifyProxy: boolean; groups?: string[] };
}>();
if (!input?.startUrls?.length) {
throw new Error('Input must include at least one startUrl');
}
// Configure proxy if requested
const proxyConfiguration = input.proxyConfig?.useApifyProxy
? await Actor.createProxyConfiguration({
groups: input.proxyConfig.groups,
})
: undefined;
const crawler = new CheerioCrawler({
proxyConfiguration,
maxRequestsPerCrawl: input.maxPages ?? 50,
maxConcurrency: 10,
async requestHandler({ request, $, enqueueLinks }) {
log.info(`Processing ${request.url}`);
await Actor.pushData({
url: request.url,
title: $('title').text().trim(),
h1: $('h1').first().text().trim(),
paragraphs: $('p').map((_, el) => $(el).text().trim()).get(),
});
await enqueueLinks({ strategy: 'same-domain' });
},
async failedRequestHandler({ request }, error) {
log.error(`Request failed: ${request.url}`, { error: error.message });
await Actor.pushData({
url: request.url,
error: error.message,
'#isFailed': true,
});
},
});
await crawler.run(input.startUrls.map(s => s.url));
log.info(`Crawler finished. ${crawler.stats.state.requestsFinished} pages processed.`);
});
```
## Pattern 4: Dataset Operations
```typescript
import { Actor } from 'apify';
import { ApifyClient } from 'apify-client';
// --- Inside an Actor (apify SDK) ---
// Push single item
await Actor.pushData({ url: 'https://example.com', title: 'Example' });
// Push batch
await Actor.pushData([
{ url: 'https://a.com', price: 10 },
{ url: 'https://b.com', price: 20 },
]);
// Store named output in key-value store
await Actor.setValue('SUMMARY', {
totalItems: 100,
avgPrice: 15.50,
crawledAt: new Date().toISOString(),
});
// Get value back
const summary = await Actor.getValue('SUMMARY');
// --- From external app (apify-client) ---
const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
// List dataset items with pagination
const { items, total } = await client
.dataset('DATASET_ID')
.listItems({ limit: 1000, offset: 0 });
// Push items to a named dataset
const dataset = await client.datasets().getOrCreate('my-results');
await client.dataset(dataset.id).pushItems([
{ url: 'https://example.com', data: 'scraped content' },
]);
// Download entire dataset
const csv = await client.dataset(dataset.id).downloadItems('csv');
const json = await client.dataset(dataset.id).downloadItems('json');
```
## Pattern 5: Key-Value Store Operations
```typescript
import { ApifyClient } from 'apify-client';
const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
// Create or get a named store
const store = await client.keyValueStores().getOrCreate('my-config');
const storeClient = client.keyValueStore(store.id);
// Set a record (any content type)
await storeClient.setRecord({
key: 'CONFIG',
value: { retries: 3, timeout: 30000 },
contentType: 'application/json',
});
// Get a record
const record = await storeClient.getRecord('CONFIG');
console.log(record?.value); // { retries: 3, timeout: 30000 }
// Store binary data (screenshots, PDFs)
await storeClient.setRecord({
key: 'screenshot.png',
value: screenshotBuffer,
contentType: 'image/png',
});
// List all keys
const { items: keys } = await storeClient.listKeys();
```
## Pattern 6: Proxy Configuration
```typescript
import { Actor } from 'apify';
// Datacenter proxy (included in subscription, fast)
const dcProxy = await Actor.createProxyConfiguration({
groups: ['BUYPROXIES94952'],
});
// Residential proxy (pay per GB, high success rate)
const resProxy = await Actor.createProxyConfiguration({
groups: ['RESIDENTIAL'],
countryCode: 'US',
});
// Google SERP proxy (specialized for Google)
const serpProxy = await Actor.createProxyConfiguration({
groups: ['GOOGLE_SERP'],
});
// Use with any crawler
const crawler = new CheerioCrawler({
proxyConfiguration: dcProxy,
// ...
});
```
## Pattern 7: Router for Multi-Page Actors
```typescript
import { Actor } from 'apify';
import { CheerioCrawler, createCheerioRouter } from 'crawlee';
const router = createCheerioRouter();
// Default route — listing pages
router.addDefaultHandler(async ({ request, $, enqueueLinks }) => {
// Extract links to detail pages
const detailLinks = $('a.product-link')
.map((_, el) => $(el).attr('href'))
.get();
await enqueueLinks({
urls: detailLinks,
label: 'DETAIL',
});
});
// Detail route — individual item pages
router.addHandler('DETAIL', async ({ request, $ }) => {
await Actor.pushData({
url: request.url,
name: $('h1.product-name').text().trim(),
price: parseFloat($('.price').text().replace('$', '')),
description: $('div.description').text().trim(),
});
});
await Actor.main(async () => {
const crawler = new CheerioCrawler({
requestHandler: router,
});
await crawler.run(['https://example-store.com/products']);
});
```
## Pattern 8: Safe Result Wrapper
```typescript
type Result<T> = { data: T; error: null } | { data: null; error: Error };
async function safeActorCall<T>(
client: ApifyClient,
actorId: string,
input: Record<string, unknown>,
): Promise<Result<T[]>> {
try {
const run = await client.actor(actorId).call(input, { timeout: 300 });
if (run.status !== 'SUCCEEDED') {
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.