Introduction to API Integration

A comprehensive guide to understanding APIs, implementation strategies, and testing tools

What are APIs and Why Use Them?

APIs (Application Programming Interfaces) are the backbone of modern software communication. They define how different software components should interact, allowing applications to share data and functionality seamlessly.

Why APIs Matter

Seamless Integration

Connect your systems with external services without rebuilding from scratch. APIs act as bridges between different platforms.

Faster Development

Leverage existing functionality instead of building everything from ground up. Reduce development time by 60-80%.

Real-Time Data

Access live data from external systems, ensuring your application always has the most current information.

Scalability

Build modular systems that can grow and adapt. APIs enable microservice architectures and cloud scaling.

Real-World API Use Cases

  • E-commerce: Integrate payment processing (Stripe, PayPal), shipping calculations (FedEx, UPS), and inventory management
  • Marketing: Connect with email platforms (Mailchimp), social media (Facebook, Twitter), and analytics tools (Google Analytics)
  • Customer Service: Sync with CRM systems (Salesforce), support tickets (Zendesk), and communication tools (Slack)
  • Financial Services: Real-time exchange rates, banking integrations, fraud detection services

How to Implement APIs: Step-by-Step Guide

1
Research & Planning

Understand the API: Read documentation, identify required endpoints, understand authentication methods

Define Requirements: What data do you need? How often? What's your error handling strategy?

Example Planning Questions:
  • Do I need real-time data or is periodic sync acceptable?
  • What's the API rate limit and how will I handle it?
  • What happens if the API is temporarily unavailable?
2
Authentication Setup

Obtain API Credentials: Register for API keys, tokens, or OAuth credentials

Secure Storage: Never hardcode credentials. Use environment variables or secure vaults

# Environment Variables Example
REBUSAI_API_KEY=sk_live_1234567890abcdef
REBUSAI_API_URL=https://api.rebusai.com/v1

# Python Implementation
import os
api_key = os.environ.get('REBUSAI_API_KEY')
if not api_key:
    raise ValueError("API key not found in environment variables")
3
Basic Implementation

Start Simple: Implement one endpoint first, then expand

Handle Responses: Parse JSON, handle different status codes

# Python Example - Basic API Call
import requests
import json

class AffiliateAPIClient:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.rebusai.com/v1/affiliate"
        self.headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }
    
    def get_affiliates(self, page=1):
        try:
            response = requests.get(
                f"{self.base_url}/affiliates/",
                headers=self.headers,
                params={'page': page},
                timeout=30
            )
            
            if response.status_code == 200:
                return response.json()
            else:
                print(f"Error: {response.status_code} - {response.text}")
                return None
                
        except requests.exceptions.RequestException as e:
            print(f"Network error: {e}")
            return None
4
Error Handling & Resilience

Robust Error Handling: Handle network failures, API errors, and rate limiting

Retry Logic: Implement exponential backoff for transient failures

# Advanced Error Handling
import time
import random
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

class ResilientAPIClient:
    def __init__(self, api_key):
        self.session = requests.Session()
        
        # Configure retry strategy
        retry_strategy = Retry(
            total=3,
            status_forcelist=[429, 500, 502, 503, 504],
            method_whitelist=["HEAD", "GET", "OPTIONS"],
            backoff_factor=1
        )
        
        adapter = HTTPAdapter(max_retries=retry_strategy)
        self.session.mount("http://", adapter)
        self.session.mount("https://", adapter)
        
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        })
    
    def make_request(self, method, url, **kwargs):
        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))
                time.sleep(retry_after)
                return self.make_request(method, url, **kwargs)
            
            response.raise_for_status()
            return response.json()
            
        except requests.exceptions.RequestException as e:
            print(f"API request failed: {e}")
            return None
5
Data Management

Data Persistence: Store API responses appropriately for your use case

Caching Strategy: Reduce API calls with intelligent caching

# Caching Implementation Example
import redis
import json
import hashlib

class CachedAPIClient:
    def __init__(self, api_key, cache_ttl=300):
        self.api_client = AffiliateAPIClient(api_key)
        self.redis_client = redis.Redis(host='localhost', port=6379, db=0)
        self.cache_ttl = cache_ttl
    
    def _cache_key(self, endpoint, params=None):
        """Generate cache key from endpoint and parameters"""
        key_data = f"{endpoint}:{json.dumps(params or {}, sort_keys=True)}"
        return hashlib.md5(key_data.encode()).hexdigest()
    
    def get_with_cache(self, endpoint, params=None):
        cache_key = self._cache_key(endpoint, params)
        
        # Try cache first
        cached_data = self.redis_client.get(cache_key)
        if cached_data:
            return json.loads(cached_data)
        
        # Fetch from API
        data = self.api_client.make_request('GET', endpoint, params=params)
        if data:
            # Store in cache
            self.redis_client.setex(
                cache_key, 
                self.cache_ttl, 
                json.dumps(data)
            )
        
        return data

Essential API Testing Tools

Professional Testing Tools

Insomnia
Developer Friendly

Best For: Lightweight API testing with great UX

  • Clean, intuitive interface
  • GraphQL support
  • Plugin ecosystem
  • Git sync for version control
cURL
Command Line

Best For: Quick tests, scripting, and CI/CD integration

# Test affiliate API endpoint
curl -X GET "https://api.rebusai.com/v1/affiliate/affiliates/" \
  -H "Authorization: Bearer sk_live_your_key" \
  -H "Content-Type: application/json"
HTTPie
User Friendly CLI

Best For: Human-friendly command line HTTP client

# Install HTTPie
pip install httpie

# Test API call
http GET api.rebusai.com/v1/affiliate/affiliates/ \
  Authorization:"Bearer sk_live_your_key"
REST Client (VS Code)
IDE Integration

Best For: Testing APIs directly in your code editor

# Create .http file in VS Code
GET https://api.rebusai.com/v1/affiliate/affiliates/
Authorization: Bearer sk_live_your_key
Content-Type: application/json

###

POST https://api.rebusai.com/v1/affiliate/affiliates/
Authorization: Bearer sk_live_your_key
Content-Type: application/json

{
  "name": "Test Affiliate",
  "email": "test@example.com"
}

Testing Best Practices

Start with Happy Path

Test successful scenarios first to ensure basic connectivity works

Test Error Cases

Verify how your application handles API errors, timeouts, and rate limits

Use Test Data

Never test with production data. Use sandbox/test environments

Test Performance

Measure response times and identify potential bottlenecks

RebusAI Affiliate API Examples

Practical Examples with RebusAI Affiliate API

Let's walk through real-world scenarios using our affiliate marketing API to demonstrate key concepts.

Example 1: Getting Started - List All Affiliates

Scenario: You want to display all approved affiliates in your dashboard

Postman Setup
  1. Open Postman and create new request
  2. Set method to GET
  3. URL: https://api.rebusai.com/v1/affiliate/affiliates/?status=approved
  4. Headers: Authorization: Bearer YOUR_API_KEY
  5. Click Send
cURL Command:
curl -X GET "https://api.rebusai.com/v1/affiliate/affiliates/?status=approved&page=1&page_size=10" \
  -H "Authorization: Bearer sk_live_your_api_key" \
  -H "Content-Type: application/json"
Python Implementation:
import requests

def get_approved_affiliates():
    url = "https://api.rebusai.com/v1/affiliate/affiliates/"
    headers = {
        'Authorization': 'Bearer sk_live_your_api_key',
        'Content-Type': 'application/json'
    }
    params = {
        'status': 'approved',
        'page': 1,
        'page_size': 10
    }
    
    response = requests.get(url, headers=headers, params=params)
    
    if response.status_code == 200:
        data = response.json()
        print(f"Found {data['data']['pagination']['total_count']} approved affiliates")
        for affiliate in data['data']['results']:
            print(f"- {affiliate['name']} ({affiliate['email']}) - Tier {affiliate['tier']}")
    else:
        print(f"Error: {response.status_code} - {response.text}")

# Usage
get_approved_affiliates()
Expected Response:
{
  "success": true,
  "data": {
    "results": [
      {
        "id": 123,
        "name": "John Smith",
        "email": "john@example.com",
        "status": {"value": "approved", "display": "Approved"},
        "tier": 2,
        "commission_rate": 12.0,
        "performance_metrics": {
          "total_sales": 15000.00,
          "total_commissions": 1800.00
        }
      }
    ],
    "pagination": {
      "page": 1,
      "total_count": 95,
      "has_next": true
    }
  }
}
Example 2: Creating New Affiliate

Scenario: A new partner wants to join your affiliate program

cURL Command:
curl -X POST "https://api.rebusai.com/v1/affiliate/affiliates/" \
  -H "Authorization: Bearer sk_live_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Sarah Williams",
    "email": "sarah@techblog.com",
    "phone": "+1-555-0199",
    "website": "https://sarahstechblog.com",
    "marketing_channels": ["blog", "social_media"],
    "audience_size": 15000,
    "experience_level": "advanced"
  }'
JavaScript (Node.js) Implementation:
const axios = require('axios');

async function createAffiliate(affiliateData) {
    try {
        const response = await axios.post(
            'https://api.rebusai.com/v1/affiliate/affiliates/',
            affiliateData,
            {
                headers: {
                    'Authorization': 'Bearer sk_live_your_api_key',
                    'Content-Type': 'application/json'
                }
            }
        );
        
        console.log('Affiliate created successfully:');
        console.log(`ID: ${response.data.data.id}`);
        console.log(`Code: ${response.data.data.affiliate_code}`);
        console.log(`Status: ${response.data.data.status.display}`);
        
        return response.data.data;
    } catch (error) {
        if (error.response) {
            console.error('API Error:', error.response.data);
        } else {
            console.error('Network Error:', error.message);
        }
        return null;
    }
}

// Usage
const newAffiliate = {
    name: "Sarah Williams",
    email: "sarah@techblog.com", 
    phone: "+1-555-0199",
    website: "https://sarahstechblog.com",
    marketing_channels: ["blog", "social_media"],
    audience_size: 15000,
    experience_level: "advanced"
};

createAffiliate(newAffiliate);
Example 3: Generating Affiliate Links

Scenario: An affiliate needs a trackable link for a specific product campaign

Python with Error Handling:
import requests
import time

class AffiliateAPIClient:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.rebusai.com/v1/affiliate"
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        })
    
    def generate_affiliate_link(self, affiliate_id, product_id, campaign_data):
        """Generate a trackable affiliate link with UTM parameters"""
        url = f"{self.base_url}/links/generate/"
        
        payload = {
            "affiliate_id": affiliate_id,
            "product_id": product_id,
            "utm_parameters": {
                "source": campaign_data.get("source", "affiliate"),
                "medium": campaign_data.get("medium", "referral"),
                "campaign": campaign_data.get("campaign", "general"),
                "content": campaign_data.get("content", "link")
            },
            "expires_date": campaign_data.get("expires_date"),
            "custom_parameters": campaign_data.get("custom_params", {})
        }
        
        try:
            response = self.session.post(url, json=payload, timeout=30)
            
            if response.status_code == 200:
                link_data = response.json()['data']
                print(f"✅ Link generated successfully!")
                print(f"   Full URL: {link_data['url']}")
                print(f"   Short URL: {link_data['short_url']}")
                print(f"   QR Code: {link_data['qr_code_url']}")
                return link_data
                
            elif response.status_code == 429:
                print("⚠️  Rate limit exceeded. Waiting...")
                time.sleep(60)
                return self.generate_affiliate_link(affiliate_id, product_id, campaign_data)
                
            else:
                error_data = response.json()
                print(f"❌ Error: {error_data['error']['message']}")
                return None
                
        except requests.exceptions.RequestException as e:
            print(f"❌ Network error: {e}")
            return None

# Usage Example
client = AffiliateAPIClient('sk_live_your_api_key')

campaign_info = {
    "source": "email",
    "medium": "newsletter",
    "campaign": "summer2024",
    "content": "hero_banner",
    "expires_date": "2024-08-31T23:59:59Z",
    "custom_params": {
        "discount_code": "SUMMER20",
        "landing_page": "summer-sale"
    }
}

link = client.generate_affiliate_link(
    affiliate_id=123,
    product_id=456,
    campaign_data=campaign_info
)
Example 4: Analytics and Performance Tracking

Scenario: Generate a performance report for your top affiliates

Comprehensive Analytics Script:
import requests
import pandas as pd
from datetime import datetime, timedelta

class AffiliateAnalytics:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.rebusai.com/v1/affiliate"
        self.headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }
    
    def get_performance_report(self, days_back=30):
        """Generate comprehensive performance report"""
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days_back)
        
        # Get overall analytics
        analytics_url = f"{self.base_url}/analytics/overview/"
        params = {
            'date_from': start_date.strftime('%Y-%m-%d'),
            'date_to': end_date.strftime('%Y-%m-%d'),
            'granularity': 'day'
        }
        
        response = requests.get(analytics_url, headers=self.headers, params=params)
        
        if response.status_code == 200:
            data = response.json()['data']
            
            print("📊 AFFILIATE PERFORMANCE REPORT")
            print("=" * 50)
            print(f"Period: {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}")
            print()
            
            overview = data['overview']
            print(f"🔢 Total Affiliates: {overview['total_affiliates']}")
            print(f"✅ Active Affiliates: {overview['active_affiliates']}")
            print(f"👆 Total Clicks: {overview['total_clicks']:,}")
            print(f"🎯 Total Conversions: {overview['total_conversions']:,}")
            print(f"📈 Conversion Rate: {overview['conversion_rate']:.2f}%")
            print(f"💰 Total Revenue: ${overview['total_revenue']:,.2f}")
            print(f"💸 Total Commissions: ${overview['total_commissions']:,.2f}")
            print(f"🛒 Avg Order Value: ${overview['average_order_value']:.2f}")
            print()
            
            # Top performers
            print("🏆 TOP PERFORMERS")
            print("-" * 30)
            for i, performer in enumerate(data['top_performers'][:5], 1):
                print(f"{i}. {performer['affiliate_name']}")
                print(f"   Sales: ${performer['sales']:,.2f}")
                print(f"   Commissions: ${performer['commissions']:,.2f}")
                print(f"   Conversions: {performer['conversions']}")
                print()
            
            return data
        else:
            print(f"❌ Failed to fetch analytics: {response.status_code}")
            return None
    
    def get_affiliate_details(self, affiliate_id, days_back=30):
        """Get detailed performance for specific affiliate"""
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days_back)
        
        url = f"{self.base_url}/affiliates/{affiliate_id}/performance/"
        params = {
            'date_from': start_date.strftime('%Y-%m-%d'),
            'date_to': end_date.strftime('%Y-%m-%d')
        }
        
        response = requests.get(url, headers=self.headers, params=params)
        
        if response.status_code == 200:
            data = response.json()['data']
            metrics = data['metrics']
            
            print(f"👤 AFFILIATE PERFORMANCE (ID: {affiliate_id})")
            print("=" * 40)
            print(f"Clicks: {metrics['total_clicks']:,}")
            print(f"Unique Clicks: {metrics['unique_clicks']:,}")
            print(f"Conversions: {metrics['conversions']:,}")
            print(f"Conversion Rate: {metrics['conversion_rate']:.2f}%")
            print(f"Sales: ${metrics['total_sales']:,.2f}")
            print(f"Commissions: ${metrics['total_commissions']:,.2f}")
            print(f"AOV: ${metrics['average_order_value']:.2f}")
            
            # Trending data
            trending = data['trending']
            print(f"\n📈 TRENDS vs Previous Period:")
            print(f"Clicks: {trending['clicks_trend']}")
            print(f"Conversions: {trending['conversion_trend']}")
            print(f"Commissions: {trending['commission_trend']}")
            
            return data
        else:
            print(f"❌ Failed to fetch affiliate details: {response.status_code}")
            return None

# Usage
analytics = AffiliateAnalytics('sk_live_your_api_key')

# Generate overall report
analytics.get_performance_report(days_back=30)

# Get specific affiliate performance
analytics.get_affiliate_details(affiliate_id=123, days_back=30)
Pro Tips for RebusAI API Integration
  • Use Webhooks: Set up webhooks for real-time notifications when affiliates are approved or commissions are earned
  • Batch Operations: Use bulk approve endpoints for processing multiple commissions efficiently
  • Caching Strategy: Cache affiliate data and analytics to reduce API calls and improve performance
  • Error Monitoring: Implement logging and monitoring to track API usage and identify issues quickly
  • Rate Limiting: Respect rate limits (100 requests/minute) and implement exponential backoff