instantly-sdk-patterns

2
1
Source

Apply production-ready Instantly SDK patterns for TypeScript and Python. Use when implementing Instantly integrations, refactoring SDK usage, or establishing team coding standards for Instantly. Trigger with phrases like "instantly SDK patterns", "instantly best practices", "instantly code patterns", "idiomatic instantly".

Install

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

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

About this skill

Instantly SDK Patterns

Overview

Production-ready patterns for Instantly API v2 integrations. Instantly has no official SDK — all integrations use direct REST calls to https://api.instantly.ai/api/v2/. These patterns provide type safety, retry logic, pagination, and multi-tenant support.

Prerequisites

  • Completed instantly-install-auth setup
  • Familiarity with async/await and TypeScript generics
  • Understanding of REST API pagination patterns

Instructions

Step 1: Type-Safe Client with Error Classification

// src/instantly/client.ts
import "dotenv/config";

export class InstantlyClient {
  private baseUrl: string;
  private apiKey: string;

  constructor(options?: { apiKey?: string; baseUrl?: string }) {
    this.apiKey = options?.apiKey || process.env.INSTANTLY_API_KEY || "";
    this.baseUrl = options?.baseUrl || "https://api.instantly.ai/api/v2";
    if (!this.apiKey) throw new Error("INSTANTLY_API_KEY is required");
  }

  async request<T>(path: string, options: RequestInit = {}): Promise<T> {
    const url = `${this.baseUrl}${path}`;
    const res = await fetch(url, {
      ...options,
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${this.apiKey}`,
        ...options.headers,
      },
    });

    if (!res.ok) {
      const body = await res.text();
      throw new InstantlyApiError(res.status, path, body);
    }

    return res.json() as Promise<T>;
  }

  // Typed convenience methods
  async getCampaigns(params?: { limit?: number; status?: number; search?: string }) {
    const qs = new URLSearchParams();
    if (params?.limit) qs.set("limit", String(params.limit));
    if (params?.status !== undefined) qs.set("status", String(params.status));
    if (params?.search) qs.set("search", params.search);
    return this.request<Campaign[]>(`/campaigns?${qs}`);
  }

  async getCampaign(id: string) {
    return this.request<Campaign>(`/campaigns/${id}`);
  }

  async createCampaign(data: CreateCampaignInput) {
    return this.request<Campaign>("/campaigns", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }

  async activateCampaign(id: string) {
    return this.request<void>(`/campaigns/${id}/activate`, { method: "POST" });
  }

  async pauseCampaign(id: string) {
    return this.request<void>(`/campaigns/${id}/pause`, { method: "POST" });
  }

  async getAccounts(params?: { limit?: number; status?: number }) {
    const qs = new URLSearchParams();
    if (params?.limit) qs.set("limit", String(params.limit));
    if (params?.status !== undefined) qs.set("status", String(params.status));
    return this.request<Account[]>(`/accounts?${qs}`);
  }

  async addLead(data: CreateLeadInput) {
    return this.request<Lead>("/leads", {
      method: "POST",
      body: JSON.stringify(data),
    });
  }

  async listLeads(filter: ListLeadsInput) {
    return this.request<Lead[]>("/leads/list", {
      method: "POST",
      body: JSON.stringify(filter),
    });
  }

  async getCampaignAnalytics(ids: string[]) {
    const qs = ids.map((id) => `ids=${id}`).join("&");
    return this.request<CampaignAnalytics[]>(`/campaigns/analytics?${qs}`);
  }
}

// Error classification
export class InstantlyApiError extends Error {
  public retryable: boolean;

  constructor(public status: number, public path: string, public body: string) {
    super(`Instantly ${status} on ${path}: ${body}`);
    this.name = "InstantlyApiError";
    this.retryable = status === 429 || status >= 500;
  }
}

Step 2: TypeScript Interfaces

// src/instantly/types.ts
export interface Campaign {
  id: string;
  name: string;
  status: number; // 0=Draft,1=Active,2=Paused,3=Completed,4=Running Subsequences
  campaign_schedule: CampaignSchedule;
  sequences: Sequence[];
  daily_limit: number | null;
  stop_on_reply: boolean;
  email_gap: number;
  timestamp_created: string;
}

export interface CampaignSchedule {
  start_date: string | null;
  end_date: string | null;
  schedules: Array<{
    name: string;
    timing: { from: string; to: string };
    days: Record<string, boolean>;
    timezone: string;
  }>;
}

export interface Sequence {
  steps: SequenceStep[];
}

export interface SequenceStep {
  type: "email";
  delay: number;
  delay_unit?: "minutes" | "hours" | "days";
  variants: Array<{ subject: string; body: string; v_disabled?: boolean }>;
}

export interface Account {
  email: string;
  first_name: string;
  last_name: string;
  status: number;
  warmup_status: string;
  daily_limit: number | null;
  provider_code: number;
  warmup: { limit: number; increment: string; advanced: Record<string, unknown> };
}

export interface Lead {
  id: string;
  email: string | null;
  first_name: string | null;
  last_name: string | null;
  company_name: string | null;
  status: number; // 1=Active,2=Paused,3=Completed,-1=Bounced,-2=Unsubscribed,-3=Skipped
  campaign: string | null;
  email_open_count: number;
  email_reply_count: number;
}

export interface CreateCampaignInput {
  name: string;
  campaign_schedule: CampaignSchedule;
  sequences: Sequence[];
  daily_limit?: number;
  stop_on_reply?: boolean;
  email_gap?: number;
  open_tracking?: boolean;
  link_tracking?: boolean;
}

export interface CreateLeadInput {
  campaign?: string;
  list_id?: string;
  email: string;
  first_name?: string;
  last_name?: string;
  company_name?: string;
  custom_variables?: Record<string, string>;
  skip_if_in_workspace?: boolean;
  verify_leads_on_import?: boolean;
}

export interface ListLeadsInput {
  campaign?: string;
  list_id?: string;
  limit?: number;
  starting_after?: string;
}

export interface CampaignAnalytics {
  campaign_id: string;
  total_leads: number;
  emails_sent: number;
  emails_opened: number;
  emails_replied: number;
  emails_bounced: number;
}

Step 3: Retry with Exponential Backoff

// src/instantly/retry.ts
export async function withRetry<T>(
  operation: () => Promise<T>,
  maxRetries = 3,
  baseDelayMs = 1000
): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await operation();
    } catch (err) {
      if (attempt === maxRetries) throw err;
      if (err instanceof InstantlyApiError && !err.retryable) throw err;

      const delay = baseDelayMs * Math.pow(2, attempt);
      const jitter = Math.random() * delay * 0.1;
      console.warn(`Retry ${attempt + 1}/${maxRetries} in ${delay}ms...`);
      await new Promise((r) => setTimeout(r, delay + jitter));
    }
  }
  throw new Error("Unreachable");
}

// Usage
const campaigns = await withRetry(() => client.getCampaigns({ limit: 50 }));

Step 4: Cursor-Based Pagination

// src/instantly/paginate.ts
export async function* paginate<T extends { id: string }>(
  client: InstantlyClient,
  path: string,
  pageSize = 100
): AsyncGenerator<T[], void, void> {
  let startingAfter: string | undefined;

  while (true) {
    const qs = new URLSearchParams({ limit: String(pageSize) });
    if (startingAfter) qs.set("starting_after", startingAfter);

    const page = await client.request<T[]>(`${path}?${qs}`);
    if (page.length === 0) break;

    yield page;
    startingAfter = page[page.length - 1].id;

    if (page.length < pageSize) break;
  }
}

// Usage — iterate all campaigns
for await (const batch of paginate<Campaign>(client, "/campaigns")) {
  for (const campaign of batch) {
    console.log(campaign.name, campaign.status);
  }
}

Step 5: Multi-Tenant Factory (Agency Pattern)

// src/instantly/factory.ts
const clients = new Map<string, InstantlyClient>();

export function getClientForWorkspace(workspaceId: string, apiKey: string): InstantlyClient {
  if (!clients.has(workspaceId)) {
    clients.set(workspaceId, new InstantlyClient({ apiKey }));
  }
  return clients.get(workspaceId)!;
}

// Usage — agency managing multiple client workspaces
const clientA = getClientForWorkspace("acme", process.env.ACME_API_KEY!);
const clientB = getClientForWorkspace("globex", process.env.GLOBEX_API_KEY!);

Python Client

# instantly/client.py
import os, time, httpx
from dataclasses import dataclass
from typing import Optional

@dataclass
class InstantlyClient:
    api_key: str = ""
    base_url: str = "https://api.instantly.ai/api/v2"

    def __post_init__(self):
        self.api_key = self.api_key or os.getenv("INSTANTLY_API_KEY", "")
        self._client = httpx.Client(
            base_url=self.base_url,
            headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
            timeout=30.0,
        )

    def get(self, path: str, params: Optional[dict] = None):
        r = self._client.get(path, params=params)
        r.raise_for_status()
        return r.json()

    def post(self, path: str, json_data: Optional[dict] = None):
        r = self._client.post(path, json=json_data)
        r.raise_for_status()
        return r.json()

    def patch(self, path: str, json_data: dict):
        r = self._client.patch(path, json=json_data)
        r.raise_for_status()
        return r.json()

    def delete(self, path: str):
        r = self._client.delete(path)
        r.raise_for_status()

    def list_campaigns(self, limit: int = 50):
        return self.get("/campaigns", params={"limit": limit})

    def get_campaign_analytics(self, campaign_id: str):
        return self.get("/campaigns/analytics", params={"id": campaign_id})

Error Handling

PatternUse CaseBenefit
Error classificationAll API callsretryable flag prevents retrying 400/403 errors
Exponential backoff429 / 5xx errorsRespects rate limits automatically
Cursor paginationLarge datasetsMemory-efficient iteration
Multi-tenant factoryAgency/multi-workspaceIsolated clients per workspace

Resources


Content truncated.

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.

11240

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.

9033

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".

18828

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.

5519

designing-database-schemas

jeremylongshore

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

12516

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5513

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,6851,428

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."

1,2631,324

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.

1,5331,147

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.

1,355809

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.

1,263727

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.

1,481684