How to use Claude Code to build, test, and debug API integrations. REST APIs, GraphQL, webhooks, and third-party service connections made easy.
Building API Integrations with Claude Code
API integrations are tedious. Authentication, error handling, rate limiting, documentation parsing—it's a lot.
Claude Code handles all of it.
Why Claude Code Excels at APIs
API development involves:
- Reading documentation
- Understanding data structures
- Handling edge cases
- Writing boilerplate
- Debugging errors
Claude Code understands API patterns deeply and generates production-ready integration code.
REST API Integrations
Building a Client
Create a TypeScript client for the Stripe API that handles:
- Authentication with API key
- Creating customers
- Creating payment intents
- Listing transactions
- Proper error handling
- Rate limiting
Use axios and follow our existing patterns.
Claude Code generates a complete, typed client.
Consuming an API
I need to integrate with this API: [paste documentation]
Create functions to:
1. Authenticate
2. Fetch user data
3. Update user profiles
4. Handle pagination
5. Retry on failure
Follow REST best practices.
Testing APIs
Write integration tests for our PaymentService that:
- Mock external API calls
- Test success scenarios
- Test error handling
- Test rate limit handling
- Use Jest and nock
GraphQL Integrations
Schema-First Development
Here's our GraphQL schema:
[paste schema]
Generate TypeScript types for all queries and mutations.
Use graphql-codegen patterns.
Building Resolvers
Create resolvers for the User type that:
- Fetch from our PostgreSQL database
- Handle nested relationships (posts, comments)
- Implement DataLoader for N+1 prevention
- Add proper authentication checks
Client-Side Queries
Using Apollo Client, create hooks for:
- Fetching user profile (with caching)
- Updating user settings (optimistic updates)
- Real-time notifications (subscriptions)
Follow our existing Apollo setup in src/lib/apollo.ts.
Webhook Integrations
Receiving Webhooks
Create a webhook handler for Stripe events:
- Verify webhook signatures
- Handle payment_intent.succeeded
- Handle payment_intent.failed
- Handle subscription events
- Idempotent processing
- Proper error responses
Use Express middleware pattern.
Sending Webhooks
Add webhook dispatch to our order system:
- Send webhooks on order created
- Send webhooks on order shipped
- Send webhooks on order delivered
- Retry failed deliveries
- Log all attempts
- Allow URL configuration per customer
Third-Party Service Integrations
CRM Integration
Integrate our app with HubSpot CRM:
- Sync contacts on user signup
- Update deal stages on purchases
- Log activities for user actions
- Two-way sync for contact updates
Use their official Node SDK.
Payment Processing
Add Stripe payment processing:
- Create checkout sessions
- Handle payment success/failure
- Store payment methods
- Process refunds
- Subscription management
Follow PCI compliance best practices.
Email Service
Integrate SendGrid for transactional emails:
- Welcome emails
- Password reset
- Order confirmations
- Dynamic templates
- Track delivery status
Use environment variables for API keys.
Authentication Providers
Add Google OAuth login:
- Configure OAuth credentials
- Handle authorization flow
- Exchange tokens
- Fetch user profile
- Link to existing accounts
Use Passport.js with our Express setup.
API Error Handling
Comprehensive Error Handler
Create a robust API error handling system:
- Catch and classify errors (4xx, 5xx, network)
- Retry transient failures with backoff
- Log errors with context
- User-friendly error messages
- Error reporting to Sentry
Apply to all our API clients.
Specific Error Scenarios
Handle these API error cases:
- 401: Refresh token and retry
- 429: Exponential backoff with jitter
- 500: Retry up to 3 times
- Network timeout: Retry with increased timeout
- Invalid response: Log and throw typed error
Rate Limiting
Implementing Rate Limits
Add rate limiting to our API:
- 100 requests per minute per user
- 1000 requests per hour per user
- Use Redis for distributed counting
- Return proper 429 responses
- Include retry-after header
Respecting Rate Limits
Update our external API client to:
- Track rate limit headers
- Pre-emptively slow down near limits
- Queue requests when limited
- Distribute requests over time
- Log rate limit events
Authentication Patterns
API Key Management
Create an API key system for our service:
- Generate secure API keys
- Hash keys in database
- Key scopes/permissions
- Key rotation support
- Usage tracking per key
OAuth Implementation
Implement OAuth 2.0 for our API:
- Authorization code flow
- Token endpoint
- Refresh tokens
- Scope management
- Token revocation
JWT Handling
Add JWT authentication:
- Issue tokens on login
- Validate on each request
- Refresh token rotation
- Blacklist compromised tokens
- Include user claims
API Documentation
Generate OpenAPI Spec
Generate OpenAPI 3.0 documentation for our API routes:
- All endpoints in src/api/
- Request/response schemas from types
- Authentication requirements
- Example requests and responses
- Error response schemas
Interactive Documentation
Set up Swagger UI for our API:
- Mount at /api/docs
- Auto-generate from OpenAPI spec
- Try-it-out functionality
- Authentication support
- Group by tag
Real-World Integration Examples
Slack Integration
Build a Slack integration:
- Slash commands for key actions
- Post notifications to channels
- Interactive messages with buttons
- OAuth installation flow
- Store tokens per workspace
GitHub Integration
Integrate with GitHub:
- Webhook for push events
- Comment on PRs from our system
- Create issues programmatically
- Sync repository metadata
- Handle organization events
Calendar Integration
Add Google Calendar integration:
- OAuth for calendar access
- Create events on booking
- Check availability
- Handle event updates
- Sync cancellations
Testing API Integrations
Mock External Services
Create mocks for our external API dependencies:
- Stripe (payments)
- SendGrid (email)
- Twilio (SMS)
- S3 (storage)
Use nock for HTTP mocking.
Make mocks realistic with proper responses.
Integration Tests
Write integration tests that:
- Use real test API keys (sandbox mode)
- Test full workflows end-to-end
- Clean up test data after
- Handle rate limits in tests
- Run in CI/CD safely
Contract Testing
Implement contract tests for our API:
- Pact for provider/consumer contracts
- Verify we match published contracts
- Publish contracts on changes
- Break build on contract violations
API Performance
Caching Strategies
Add caching to our API integrations:
- Cache GET responses in Redis
- Cache invalidation on writes
- Cache-Control headers
- Stale-while-revalidate pattern
- Cache key generation
Batch Operations
Optimize our API calls with batching:
- Batch multiple creates into one request
- Use bulk endpoints where available
- DataLoader for GraphQL
- Queue and batch background jobs
Connection Pooling
Set up connection pooling for API clients:
- HTTP keep-alive
- Connection limits per host
- Timeout configuration
- Health checking
Debugging APIs
Logging
Add comprehensive API logging:
- Log all outgoing requests
- Log response status and timing
- Redact sensitive data
- Correlation IDs across services
- Structured JSON logs
Debugging Session
This API call is failing intermittently:
[describe the issue]
[paste relevant code]
[paste error message]
Help me debug:
1. What could cause this?
2. How can I reproduce it?
3. What logging should I add?
4. What's the fix?
Best Practices
Claude Code follows API best practices:
- Type Safety: Full TypeScript types for requests/responses
- Error Handling: Comprehensive error catching and classification
- Retry Logic: Smart retries with exponential backoff
- Rate Limiting: Respect and implement rate limits
- Security: Secure credential handling, no hardcoding
- Logging: Detailed logs for debugging
- Testing: Mocked and integration tests
- Documentation: Generated API docs
The Bottom Line
API integrations that would take days take hours with Claude Code.
It understands patterns, handles edge cases, and generates production-ready code.
Need help building API integrations? Cedar Operations specializes in system integration and automation. Book a consultation →
Related reading: