
rest-api
by Lordsisodia
SISO Agency Internal Platform - Task management and day tracking system with LifeLock integration
SKILL.md
name: rest-api category: integration-connectivity/api-integrations version: 1.0.0 description: REST API integration patterns, best practices, and error handling for building robust API clients author: blackbox5/core verified: true tags: [api, rest, integration, http, fetch]
REST API Integration Skills
Why REST API Integration Matters:
- Most modern services expose REST APIs (GitHub, Stripe, Twitter, etc.)
- Proper error handling prevents cascading failures
- Rate limit awareness prevents service disruption
- Consistent patterns reduce cognitive load
- Security best practices protect sensitive data
Core Concepts:
- Resources: Entities exposed by the API (users, posts, products)
- HTTP Methods: GET (read), POST (create), PUT/PATCH (update), DELETE (remove)
- Status Codes: Indicate outcome (200 success, 400 client error, 500 server error)
- Authentication: API keys, OAuth tokens, JWT
- Pagination: Handling large datasets across multiple requests
Integration Challenges:
- Network failures and timeouts
- Rate limiting and throttling
- Authentication token expiration
- Malformed responses or API changes
- Partial failures and retry logic
- Always start with discovery - Read API documentation, explore endpoints, understand authentication
- Use proper error handling - Never assume requests succeed; handle all error cases
- Respect rate limits - Implement throttling and backoff strategies
- Log appropriately - Record requests, responses, and errors for debugging
- Validate responses - Check status codes and response structure before processing
- Use TypeScript types - Define interfaces for request/response data
- Implement retries - Use exponential backoff for transient failures
Claude will help you create API clients, handle authentication, implement error handling, and build robust integrations.
<best_practices> Use TypeScript for type safety and better developer experience Implement exponential backoff for retries (wait 1s, 2s, 4s, 8s, etc.) Set appropriate timeouts to prevent hanging requests Validate responses against expected schema Log requests and responses (with sensitive data sanitized) Use environment variables for API keys and configuration Handle pagination gracefully for list endpoints Cache responses when data doesn't change frequently Monitor API usage and set up alerts for anomalies Use official SDKs when available Implement circuit breakers for failing services Document API contracts and integration patterns Use HTTP/2 when available for better performance Hardcode credentials or API keys in source code Ignore error responses or status codes Make unlimited requests without rate limiting Assume API responses will always match documentation Retry indefinitely without backoff Expose sensitive data in logs or error messages Use HTTP instead of HTTPS Ignore pagination limits Make requests without timeouts Trust user input without validation Swallow errors silently Mix authentication methods inconsistently </best_practices>
<anti_patterns> Hardcoded Credentials Embedding API keys or tokens directly in source code Security vulnerability, credentials exposed in version control Use environment variables or secret management services No Error Handling Assuming API calls always succeed Application crashes, poor user experience, silent failures Wrap all API calls in try-catch blocks, handle all status codes Infinite Retries Retrying failed requests without backoff or limits API rate limit exhaustion, cascading failures Implement exponential backoff with maximum retry limit Ignoring Rate Limits Making requests without respecting API rate limits Temporary or permanent API access suspension Track request counts, implement throttling, respect rate limit headers Assumed Response Structure Assuming API responses will always match documentation Runtime errors when API changes or returns unexpected data Validate responses against schema, handle unexpected data gracefully </anti_patterns>
async function getUser(userId: string): Promise {
const response = await fetch(https://api.example.com/users/${userId}, {
method: 'GET',
headers: {
'Authorization': Bearer ${process.env.API_KEY},
'Content-Type': 'application/json',
},
signal: AbortSignal.timeout(30000), // 30 second timeout
});
if (!response.ok) {
if (response.status === 404) {
throw new Error('User not found');
} else if (response.status === 401) {
throw new Error('Authentication failed');
} else if (response.status >= 500) {
throw new Error('Server error, please try again later');
}
throw new Error(Request failed with status ${response.status});
}
const data = await response.json(); return data as User; } ]]>
interface CreatePostResponse { id: string; title: string; content: string; createdAt: string; }
async function createPostWithRetry(
data: CreatePostRequest,
maxRetries: number = 3
): Promise {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch('https://api.example.com/posts', {
method: 'POST',
headers: {
'Authorization': Bearer ${process.env.API_KEY},
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
signal: AbortSignal.timeout(30000),
});
if (response.ok) {
return await response.json() as CreatePostResponse;
}
// Don't retry client errors (4xx)
if (response.status >= 400 && response.status < 500) {
const error = await response.json();
throw new Error(error.message || 'Client error');
}
// Retry server errors (5xx)
if (attempt < maxRetries - 1) {
const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw new Error(`Server error: ${response.status}`);
} catch (error) {
if (attempt === maxRetries - 1) {
throw error;
}
// Retry network errors
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw new Error('Max retries exceeded'); } ]]>
interface PaginatedResponse { data: T[]; hasMore: boolean; nextCursor?: string; }
async function getAllUsers(options: ListOptions = {}): Promise<User[]> { const allUsers: User[] = []; let cursor: string | undefined;
do { const params = new URLSearchParams({ limit: String(options.limit || 100), ...(cursor && { startingAfter: cursor }), });
const response = await fetch(
`https://api.example.com/users?${params}`,
{
headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
},
signal: AbortSignal.timeout(30000),
}
);
if (!response.ok) {
throw new Error(`Failed to fetch users: ${response.status}`);
}
const result = await response.json() as PaginatedResponse<User>;
allUsers.push(...result.data);
cursor = result.nextCursor;
} while (cursor);
return allUsers; } ]]>
<error_handling> Network Timeout Set appropriate timeout (30-60 seconds) Implement retry logic with exponential backoff Log timeout incidents for monitoring Provide user feedback if operation takes time Authentication Failure (401) Verify API key/token is valid Check token hasn't expired Implement token refresh if using OAuth Ensure credentials are stored securely Rate Limit Exceeded (429) Parse rate limit headers (Retry-After, X-RateLimit-Reset) Implement request throttling Use exponential backoff before retrying Consider caching to reduce request frequency Resource Not Found (404) Verify resource ID is correct Check if resource was deleted Provide clear error message to user Offer to list available resources Server Error (5xx) Implement retry logic with exponential backoff Set maximum retry limit (3-5 attempts) Log error details for debugging Provide user feedback about service issues Malformed Response Validate response against expected schema Handle unexpected data gracefully Log response for debugging Contact API provider if structure changed </error_handling>
<rate_limiting> Limit requests per time window (e.g., 1000/hour) Track request count, reset at window boundary Limit requests in rolling time window Track timestamps, count requests in window Requests consume tokens, tokens refill over time Parse X-RateLimit-Remaining and X-RateLimit-Reset headers <best_practices> Parse rate limit headers from responses Implement client-side throttling Use exponential backoff when limited Queue requests when approaching limits Monitor usage and set up alerts </best_practices> </rate_limiting>
<output_format> When working with REST APIs, Claude will:
- Create TypeScript interfaces for request/response types
- Implement error handling with proper categorization
- Add retry logic with exponential backoff
- Set timeouts to prevent hanging requests
- Handle authentication securely
- Implement pagination for list endpoints
- Add logging (sanitized) for debugging
- Provide usage examples for each endpoint
- Document edge cases and error scenarios
- Include tests for critical functionality
All code will be production-ready, type-safe, and follow security best practices. </output_format>
<related_skills> GraphQL integration patterns Webhook handling and verification OAuth authentication flows API testing strategies </related_skills>
<see_also> MDN Web Docs - Fetch API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API REST API Tutorial https://restfulapi.net/ HTTP Status Codes https://httpstatuses.com/ OAuth 2.0 Specification https://oauth.net/2/ OpenAPI Specification https://swagger.io/specification/ Rate Limiting Best Practices https://cloud.google.com/architecture/rate-limiting-strategies-techniques </see_also>
Score
Total Score
Based on repository quality metrics
SKILL.mdファイルが含まれている
ライセンスが設定されている
100文字以上の説明がある
GitHub Stars 100以上
3ヶ月以内に更新がある
10回以上フォークされている
オープンIssueが50未満
プログラミング言語が設定されている
1つ以上のタグが設定されている
Reviews
Reviews coming soon