apollo-sdk-patterns

0
0
Source

Apply production-ready Apollo.io SDK patterns. Use when implementing Apollo integrations, refactoring API usage, or establishing team coding standards. Trigger with phrases like "apollo sdk patterns", "apollo best practices", "apollo code patterns", "idiomatic apollo", "apollo client wrapper".

Install

mkdir -p .claude/skills/apollo-sdk-patterns && curl -L -o skill.zip "https://mcp.directory/api/skills/download/8516" && unzip -o skill.zip -d .claude/skills/apollo-sdk-patterns && rm skill.zip

Installs to .claude/skills/apollo-sdk-patterns

About this skill

Apollo SDK Patterns

Overview

Production-ready patterns for Apollo.io API integration. Apollo has no official SDK — these patterns wrap the REST API (https://api.apollo.io/api/v1/) with type safety, retry logic, pagination, and bulk operations. All requests use the x-api-key header.

Prerequisites

  • Completed apollo-install-auth setup
  • TypeScript 5+ with strict mode

Instructions

Step 1: Type-Safe Client with Zod Validation

// src/apollo/client.ts
import axios, { AxiosInstance } from 'axios';
import { z } from 'zod';

const ConfigSchema = z.object({
  apiKey: z.string().min(10, 'API key too short'),
  baseURL: z.string().url().default('https://api.apollo.io/api/v1'),
  timeout: z.number().default(30_000),
});

let instance: AxiosInstance | null = null;

export function getApolloClient(config?: Partial<z.input<typeof ConfigSchema>>): AxiosInstance {
  if (instance) return instance;

  const parsed = ConfigSchema.parse({
    apiKey: config?.apiKey ?? process.env.APOLLO_API_KEY,
    ...config,
  });

  instance = axios.create({
    baseURL: parsed.baseURL,
    timeout: parsed.timeout,
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': parsed.apiKey,
    },
  });

  return instance;
}

// Reset for testing
export function resetClient() { instance = null; }

Step 2: Custom Error Classes

// src/apollo/errors.ts
import { AxiosError } from 'axios';

export class ApolloApiError extends Error {
  constructor(
    message: string,
    public statusCode: number,
    public endpoint: string,
    public retryable: boolean,
    public requestId?: string,
  ) {
    super(message);
    this.name = 'ApolloApiError';
  }

  static fromAxios(err: AxiosError): ApolloApiError {
    const status = err.response?.status ?? 0;
    const body = err.response?.data as any;
    return new ApolloApiError(
      body?.message ?? err.message,
      status,
      err.config?.url ?? 'unknown',
      [429, 500, 502, 503, 504].includes(status),
      err.response?.headers?.['x-request-id'],
    );
  }
}

export class ApolloRateLimitError extends ApolloApiError {
  constructor(
    public retryAfterMs: number,
    endpoint: string,
  ) {
    super(`Rate limited on ${endpoint}`, 429, endpoint, true);
    this.name = 'ApolloRateLimitError';
  }
}

Step 3: Retry with Exponential Backoff

// src/apollo/retry.ts
import { ApolloApiError } from './errors';

export async function withRetry<T>(
  fn: () => Promise<T>,
  opts: { maxRetries?: number; baseMs?: number; maxMs?: number } = {},
): Promise<T> {
  const { maxRetries = 3, baseMs = 1000, maxMs = 30_000 } = opts;

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (err) {
      const isRetryable = err instanceof ApolloApiError && err.retryable;
      if (!isRetryable || attempt === maxRetries) throw err;

      const jitter = Math.random() * 500;
      const delay = Math.min(baseMs * 2 ** attempt + jitter, maxMs);
      await new Promise((r) => setTimeout(r, delay));
    }
  }
  throw new Error('Unreachable');
}

Step 4: Async Pagination Iterator

Apollo endpoints return pagination.total_entries and accept page/per_page. The People Search API limits to 500 pages (50,000 records).

// src/apollo/paginator.ts
import { getApolloClient } from './client';
import { withRetry } from './retry';

export async function* paginate<T>(
  endpoint: string,
  body: Record<string, unknown>,
  itemKey: string = 'people',
  perPage: number = 100,
  maxPages: number = 500,
): AsyncGenerator<T[], void, undefined> {
  const client = getApolloClient();
  let page = 1;
  let totalPages = Infinity;

  while (page <= Math.min(totalPages, maxPages)) {
    const { data } = await withRetry(() =>
      client.post(endpoint, { ...body, page, per_page: perPage }),
    );

    const items: T[] = data[itemKey] ?? [];
    totalPages = data.pagination?.total_pages ?? 1;
    if (items.length === 0) break;

    yield items;
    page++;
  }
}

// Usage:
// for await (const batch of paginate('/mixed_people/api_search', {
//   q_organization_domains_list: ['stripe.com'],
// })) {
//   await processBatch(batch);
// }

Step 5: Bulk Enrichment with Rate Awareness

Apollo's Bulk People Enrichment endpoint handles up to 10 records per call.

// src/apollo/bulk-enrich.ts
import { getApolloClient } from './client';
import { withRetry } from './retry';

interface EnrichmentDetail {
  email?: string;
  linkedin_url?: string;
  first_name?: string;
  last_name?: string;
  organization_domain?: string;
}

export async function bulkEnrichPeople(
  details: EnrichmentDetail[],
  opts: { revealPersonalEmails?: boolean; revealPhoneNumber?: boolean } = {},
): Promise<any[]> {
  const client = getApolloClient();
  const results: any[] = [];

  // Apollo bulk endpoint accepts max 10 at a time
  for (let i = 0; i < details.length; i += 10) {
    const batch = details.slice(i, i + 10);

    const { data } = await withRetry(() =>
      client.post('/people/bulk_match', {
        details: batch,
        reveal_personal_emails: opts.revealPersonalEmails ?? false,
        reveal_phone_number: opts.revealPhoneNumber ?? false,
      }),
    );

    results.push(...(data.matches ?? []));

    // Brief pause between batches to respect rate limits
    if (i + 10 < details.length) {
      await new Promise((r) => setTimeout(r, 500));
    }
  }

  return results;
}

Output

  • src/apollo/client.ts — Zod-validated singleton with x-api-key header
  • src/apollo/errors.tsApolloApiError + ApolloRateLimitError with retryable flag
  • src/apollo/retry.ts — Exponential backoff with jitter
  • src/apollo/paginator.ts — Async generator for paginated endpoints (500-page limit)
  • src/apollo/bulk-enrich.ts — Batch enrichment via /people/bulk_match (10 per call)

Error Handling

PatternWhen to Use
Singleton clientAlways — one client instance per process
Retry429 rate limits, 5xx server errors
PaginationSearch results > 100 records
Bulk enrichmentMultiple contacts need email/phone data
Custom errorsTyped catch blocks distinguishing auth vs rate limit vs server

Examples

Full Pipeline: Search, Paginate, Enrich

import { paginate } from './apollo/paginator';
import { bulkEnrichPeople } from './apollo/bulk-enrich';

async function enrichLeadsAtCompany(domain: string) {
  const allPeople: any[] = [];
  for await (const batch of paginate('/mixed_people/api_search', {
    q_organization_domains_list: [domain],
    person_seniorities: ['vp', 'director', 'c_suite'],
  })) {
    allPeople.push(...batch);
  }
  console.log(`Found ${allPeople.length} decision-makers at ${domain}`);

  // Bulk enrich only those without email
  const toEnrich = allPeople
    .filter((p) => !p.email && p.linkedin_url)
    .map((p) => ({ linkedin_url: p.linkedin_url }));

  const enriched = await bulkEnrichPeople(toEnrich);
  console.log(`Enriched ${enriched.length} contacts`);
}

Resources

Next Steps

Proceed to apollo-core-workflow-a for lead search implementation.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

8227

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

4926

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

14217

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4615

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

11514

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

11410

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,1421,171

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

969933

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

683829

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

691549

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

797540

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

697374

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.