API Connections & Data Flow
Connect your AI systems with existing tools and services through APIs, webhooks, and MCP
Last reviewed
What You'll Learn#
API Fundamentals
- • API types, webhooks, and MCP, and when to use each
- • Authentication methods and security
- • Error handling and retry strategies
- • Rate limiting and performance optimization
Implementation
- • Building resilient API clients with native fetch
- • Verifying webhooks and validating data with Zod
- • Monitoring and alerting setup
- • Testing strategies for integrations
Types of API Integrations#
REST APIs
Standard HTTP APIs using JSON, often described by an OpenAPI spec
Pros:
- • Universal support
- • Official SDKs for most services
- • Great tooling
Cons:
- • Several requests for related data
- • Polling wastes calls
Examples:
Webhooks
Real-time event notifications pushed from external services
Pros:
- • Real-time updates
- • No polling
- • Event-driven
Cons:
- • Public endpoint required
- • Must verify signatures and dedupe retries
Examples:
MCP (Model Context Protocol)
Open standard for exposing tools and data to AI models and agents
Pros:
- • One server works with many AI clients
- • Tools are self-describing
- • Remote servers use OAuth
Cons:
- • Tools act with real permissions
- • Spec is still evolving quickly
Examples:
GraphQL
Query language for APIs with flexible data fetching
Pros:
- • Single endpoint
- • Fetch exactly the fields you need
- • Strong typing
Cons:
- • Learning curve
- • Caching and rate limits are query-based
Examples:
Server-Sent Events
One-way streaming from server to client over plain HTTP
Pros:
- • Simple to consume
- • Works through most proxies
- • Standard for streaming AI responses
Cons:
- • Server to client only
- • Some proxies buffer the stream
Examples:
WebSockets
Bidirectional real-time communication
Pros:
- • Two-way
- • Low latency
- • Persistent connection
Cons:
- • Connection management
- • Scaling challenges
Examples:
Authentication Methods#
API Keys
Simple secret token issued per account or per integration
Implementation: Send it in a header, never in the URL (URLs end up in logs)
Authorization: Bearer <your-api-key>OAuth 2.0 with PKCE
Industry standard for acting on behalf of a user with scoped access
Implementation: Authorization code flow with PKCE, short-lived access tokens, refresh tokens
Authorization: Bearer <access-token>JWT Tokens
Self-contained signed tokens with embedded claims
Implementation: Verify signature, issuer, audience, and expiry on every request
Authorization: Bearer <jwt>Webhook Signatures (HMAC)
Proves an incoming webhook really came from the provider
Implementation: HMAC the raw body with a shared secret, timing-safe compare, reject old timestamps
Stripe-Signature: t=1700000000,v1=5257a869...Basic Auth
Username and password encoded in base64 (not encrypted)
Implementation: HTTPS only; prefer API keys or OAuth for new integrations
Authorization: Basic base64(user:pass)Implementation Steps#
API Discovery & Documentation
Research and understand the target API capabilities
- Check for an official SDK, an OpenAPI spec, or an MCP server first
- Test endpoints with curl, Postman, or Bruno in a sandbox account
- Understand rate limits, pagination, and usage policies
- Identify authentication requirements and the scopes you actually need
Authentication Setup
Implement secure authentication for API access
- Request the narrowest scopes or restricted keys the provider offers
- Store secrets in environment variables or a secrets manager
- Implement token refresh logic for OAuth integrations
- Test authentication with a simple read-only request
Integration Implementation
Build the integration with proper error handling
- Use the official SDK when one exists; otherwise native fetch
- Validate responses and webhook payloads with a schema (for example, Zod)
- Set timeouts and retry 429 and 5xx responses with backoff and jitter
- Send idempotency keys on writes and dedupe webhook event IDs
Testing & Monitoring
Ensure reliability and performance
- Write unit tests with mocked HTTP (for example, MSW)
- Replay real sample webhooks with the provider CLI or dashboard
- Track latency, error rates, and quota usage per integration
- Alert on repeated failures, rate limiting, and failed webhook deliveries
API Client & Webhook Example#
// Example: a resilient API client plus a verified webhook receiver
// Node 20+, ES modules, native fetch. No extra HTTP library needed.
import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
import { z } from 'zod';
class ApiError extends Error {
constructor(status, retryAfterMs) {
super(`API request failed with status ${status}`);
this.name = 'ApiError';
this.status = status;
this.retryAfterMs = retryAfterMs;
}
}
const isRetryable = (error) =>
error.name === 'TimeoutError' ||
error.name === 'TypeError' || // network failure in fetch
(error instanceof ApiError && (error.status === 429 || error.status >= 500));
// 1. Outbound: call an API with timeouts, retries, and response validation
export async function apiRequest(path, { schema, retries = 3, ...init } = {}) {
const url = new URL(path, process.env.EXAMPLE_API_BASE_URL);
for (let attempt = 1; ; attempt++) {
try {
const res = await fetch(url, {
...init,
signal: AbortSignal.timeout(10_000),
headers: {
Authorization: `Bearer ${process.env.EXAMPLE_API_KEY}`,
'Content-Type': 'application/json',
...init.headers,
},
});
if (!res.ok) {
// Retry-After in seconds, if present; capped at one minute
const seconds = Number(res.headers.get('retry-after') ?? NaN);
throw new ApiError(res.status, seconds > 0 ? Math.min(seconds, 60) * 1000 : undefined);
}
const data = await res.json();
return schema ? schema.parse(data) : data;
} catch (error) {
if (attempt > retries || !isRetryable(error)) throw error;
const backoff = 500 * 2 ** (attempt - 1) * (0.5 + Math.random());
await sleep(error.retryAfterMs ?? backoff);
}
}
}
const Notification = z.object({ id: z.string(), status: z.enum(['queued', 'sent']) });
export const sendNotification = (message) =>
apiRequest('/v1/notifications', {
method: 'POST',
headers: { 'Idempotency-Key': randomUUID() },
body: JSON.stringify({ message }),
schema: Notification,
});
// 2. Inbound: verify a signed webhook (format: "t=<unix>,v1=<hex hmac>")
// If the provider ships an SDK helper (e.g. Stripe's constructEvent), use that.
const TOLERANCE_SECONDS = 300;
export function verifySignature(rawBody, header, secret) {
const parts = Object.fromEntries(
(header ?? '').split(',').map((kv) => kv.trim().split('=', 2)),
);
const timestamp = Number(parts.t);
if (!parts.v1 || !Number.isInteger(timestamp)) return false;
if (Math.abs(Date.now() / 1000 - timestamp) > TOLERANCE_SECONDS) return false;
const expected = createHmac('sha256', secret)
.update(`${timestamp}.${rawBody}`)
.digest();
const received = Buffer.from(parts.v1, 'hex');
return received.length === expected.length && timingSafeEqual(received, expected);
}
const WebhookEvent = z.object({
id: z.string(),
type: z.string(),
data: z.record(z.string(), z.unknown()),
});
// Works with any framework that gives you a standard Request (Hono, Next.js, etc.)
export async function handleWebhook(request) {
const rawBody = await request.text(); // raw body: do not parse before verifying
const ok = verifySignature(rawBody, request.headers.get('x-signature'), process.env.WEBHOOK_SECRET);
if (!ok) return new Response('Invalid signature', { status: 400 });
const event = WebhookEvent.parse(JSON.parse(rawBody));
// Dedupe on event.id, enqueue a background job, then return 200 quickly.
return Response.json({ received: true, id: event.id });
}Best Practices#
Security
- Never hardcode API keys; load them from environment variables or a secrets manager
- Verify webhook signatures over the raw body with a timing-safe compare
- Validate and sanitize every external input before using it
- Never log tokens, keys, or personal data
- Use least-privilege scopes and rotate keys regularly
Performance
- Prefer webhooks over polling when the provider supports them
- Cache frequently read, rarely changing data
- Batch requests when the API supports it
- Paginate large lists instead of fetching everything at once
- Monitor and optimize API response times
Reliability
- Retry 429 and 5xx responses with exponential backoff and jitter
- Honor Retry-After headers and published rate limits
- Set a timeout on every request
- Make writes idempotent with idempotency keys and event ID dedupe
- Use circuit breakers for services that keep failing
Monitoring
- Track API response times and error rates
- Monitor API quota usage and limits
- Watch webhook delivery failures in each provider dashboard
- Implement health checks for critical integrations
- Create dashboards for operational visibility
Popular APIs for Automation#
Stripe
PaymentsComplete payment processing platform
Resend
EmailDeveloper-focused email API with a free tier
Twilio
CommunicationsSMS, voice, and messaging APIs
Slack
CollaborationTeam messaging with a Web API, events, and a hosted MCP server
Claude API
AIAnthropic API for Claude models, with tool use for calling your own APIs
Google Maps Platform
LocationMapping and location services
Next Steps#
Now that you can integrate with external services, learn how to secure and monitor your automation systems.