home / skills / dasien / claudemultiagenttemplate / api-integration

This skill helps design robust API integrations by handling authentication, retries, and rate limits with clear error handling.

npx playbooks add skill dasien/claudemultiagenttemplate --skill api-integration

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
2.4 KB
---
name: "API Integration Patterns"
description: "Implement robust third-party API integrations with proper authentication, error handling, and rate limiting"
category: "integration"
required_tools: ["Read", "Write", "Edit", "WebSearch"]
---

## Purpose
Build reliable integrations with external APIs, handling authentication flows, retries, rate limits, and error conditions gracefully.

## When to Use
- Integrating third-party services
- Building API clients
- Consuming webhooks
- Managing API credentials

## Key Capabilities
1. **Authentication Handling** - OAuth, API keys, JWT
2. **Error Recovery** - Retries with exponential backoff
3. **Rate Limit Management** - Respect API quotas

## Example
```python
import requests
from time import sleep
import logging

class APIClient:
    def __init__(self, base_url, api_key):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'User-Agent': 'MyApp/1.0'
        })
    
    def make_request(self, method, endpoint, **kwargs):
        url = f"{self.base_url}/{endpoint}"
        max_retries = 3
        
        for attempt in range(max_retries):
            try:
                response = self.session.request(method, url, **kwargs)
                
                # Handle rate limiting
                if response.status_code == 429:
                    retry_after = int(response.headers.get('Retry-After', 60))
                    logging.warning(f"Rate limited. Waiting {retry_after}s")
                    sleep(retry_after)
                    continue
                
                response.raise_for_status()
                return response.json()
            
            except requests.exceptions.RequestException as e:
                if attempt == max_retries - 1:
                    raise
                # Exponential backoff
                wait = 2 ** attempt
                logging.warning(f"Request failed, retrying in {wait}s: {e}")
                sleep(wait)
        
        raise Exception("Max retries exceeded")
```

## Best Practices
- ✅ Implement exponential backoff for retries
- ✅ Respect rate limits (429 responses)
- ✅ Use timeouts on all requests
- ✅ Log all API interactions for debugging
- ✅ Validate webhook signatures
- ❌ Avoid: Infinite retry loops
- ❌ Avoid: Storing API keys in code

---

Overview

This skill teaches how to implement robust third-party API integrations with secure authentication, resilient error handling, and respectful rate limiting. It focuses on practical patterns for authentication flows (OAuth, API keys, JWT), retries with exponential backoff, and handling quota responses. The guidance applies to building API clients, webhook consumers, and long-running integrations.

How this skill works

The approach wraps HTTP clients in a small API client layer that centralizes headers, timeouts, and retry logic. It detects and responds to rate-limit signals (429 and Retry-After), performs exponential backoff on transient failures, and surfaces fatal errors after a bounded number of retries. It also recommends validating webhook signatures and keeping credential management out of source code.

When to use it

  • Integrating with third-party REST or GraphQL APIs
  • Building reusable API client libraries
  • Consuming and validating webhooks
  • Orchestrating calls across multiple external services
  • Managing short-lived tokens and rotating credentials

Best practices

  • Use timeouts on every request to avoid hung connections
  • Implement exponential backoff with jitter for transient errors
  • Respect 429 responses and honor Retry-After headers
  • Log requests, responses (sanitized), and retry attempts for debugging
  • Store credentials securely (secrets manager or environment variables), never in code
  • Validate webhook signatures and verify payloads before processing

Example use cases

  • A payment gateway client that handles OAuth token refresh and retries failed submissions
  • A background worker that polls an external service and respects API quotas using Retry-After
  • A webhook receiver that validates HMAC signatures before enqueuing jobs
  • A multi-service orchestrator that batches requests and applies per-service rate limits
  • A SDK wrapper that centralizes timeouts, headers, and standardized error mapping

FAQ

How many retries should I allow?

Use a small bounded number such as 3–5 retries, with exponential backoff and jitter. Fail fast for non-transient errors (4xx other than 429).

How do I handle rate limits across multiple processes?

Coordinate using a central rate-limit tracker (shared cache or token bucket) or rely on each process honoring Retry-After. For heavy loads, implement client-side token buckets to smooth bursts.