Code Examples

Ready-to-use code examples for integrating the Traceback Search API into your applications.

Python

Basic Search

import requests
import json

# API configuration
API_KEY = "your_api_key_here"
BASE_URL = "https://api.numberintelligence.com/v1/traceback"

def search_traceback_reports(phone_number=None, start_date=None, end_date=None, limit=20):
    """Search traceback reports"""
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    params = {
        "limit": limit
    }
    
    if phone_number:
        params["phone_number"] = phone_number
    if start_date:
        params["start_date"] = start_date
    if end_date:
        params["end_date"] = end_date
    
    response = requests.get(f"{BASE_URL}/search", headers=headers, params=params)
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code} - {response.text}")
        return None

# Example usage
results = search_traceback_reports(
    phone_number="+15551234567",
    start_date="2024-01-01",
    end_date="2024-01-31",
    limit=50
)

if results and results["success"]:
    print(f"Found {results['data']['total_count']} reports")
    for report in results["data"]["reports"]:
        print(f"- {report['violation_type']}: {report['provider_name']}")
else:
    print("No results found")

Advanced Search with Filters

def advanced_search(provider_name=None, violation_type=None, quarter=None):
    """Advanced search with multiple filters"""
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    params = {}
    
    if provider_name:
        params["provider_name"] = provider_name
    if violation_type:
        params["violation_type"] = violation_type
    if quarter:
        params["quarter"] = quarter
    
    response = requests.get(f"{BASE_URL}/search", headers=headers, params=params)
    return response.json() if response.status_code == 200 else None

# Search for specific violation types
results = advanced_search(
    violation_type="SPAM",
    quarter="2024-Q1"
)

if results and results["success"]:
    for report in results["data"]["reports"]:
        print(f"Provider: {report['provider_name']}")
        print(f"Violation: {report['violation_type']}")
        print(f"Quarter: {report['quarter']}")
        print("---")

Export to CSV

def export_reports(format="csv", **filters):
    """Export traceback reports"""
    headers = {
        "Authorization": f"Bearer {API_KEY}"
    }
    
    params = {"format": format}
    params.update(filters)
    
    response = requests.get(f"{BASE_URL}/export", headers=headers, params=params)
    
    if response.status_code == 200:
        return response.content
    else:
        print(f"Export failed: {response.status_code} - {response.text}")
        return None

# Export CSV data
csv_data = export_reports(
    format="csv",
    phone_number="+15551234567",
    start_date="2024-01-01",
    end_date="2024-01-31"
)

if csv_data:
    with open("traceback_report.csv", "wb") as f:
        f.write(csv_data)
    print("Report exported successfully")

Error Handling

def safe_api_call(endpoint, params=None):
    """Make API call with proper error handling"""
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    try:
        response = requests.get(f"{BASE_URL}/{endpoint}", headers=headers, params=params)
        
        if response.status_code == 200:
            return response.json()
        elif response.status_code == 401:
            print("Authentication failed - check your API key")
        elif response.status_code == 429:
            print("Rate limit exceeded - please wait before retrying")
        elif response.status_code == 400:
            print(f"Bad request: {response.json().get('error', 'Unknown error')}")
        else:
            print(f"API error: {response.status_code} - {response.text}")
            
    except requests.exceptions.RequestException as e:
        print(f"Network error: {e}")
    
    return None

# Example with error handling
results = safe_api_call("search", {"phone_number": "+15551234567"})
if results:
    print(f"API call successful: {len(results['data']['reports'])} reports found")

JavaScript

Node.js Usage

const axios = require('axios');

class TracebackAPI {
    constructor(apiKey) {
        this.apiKey = apiKey;
        this.baseURL = 'https://api.numberintelligence.com/v1/traceback';
        this.headers = {
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
        };
    }
    
    async searchReports(params = {}) {
        try {
            const response = await axios.get(`${this.baseURL}/search`, {
                headers: this.headers,
                params: params
            });
            return response.data;
        } catch (error) {
            console.error('API Error:', error.response?.data || error.message);
            throw error;
        }
    }
    
    async exportReports(format = 'csv', filters = {}) {
        try {
            const params = { format, ...filters };
            const response = await axios.get(`${this.baseURL}/export`, {
                headers: this.headers,
                params: params,
                responseType: 'blob'
            });
            return response.data;
        } catch (error) {
            console.error('Export Error:', error.response?.data || error.message);
            throw error;
        }
    }
    
    async getTopOffenders(quarter, limit = 10) {
        try {
            const response = await axios.get(`${this.baseURL}/providers/top-offenders`, {
                headers: this.headers,
                params: { quarter, limit }
            });
            return response.data;
        } catch (error) {
            console.error('API Error:', error.response?.data || error.message);
            throw error;
        }
    }
}

// Usage example
const api = new TracebackAPI('your_api_key_here');

async function searchExample() {
    try {
        const results = await api.searchReports({
            phone_number: '+15551234567',
            start_date: '2024-01-01',
            end_date: '2024-01-31',
            limit: 50
        });
        
        console.log(`Found ${results.data.total_count} reports`);
        results.data.reports.forEach(report => {
            console.log(`- ${report.violation_type}: ${report.provider_name}`);
        });
    } catch (error) {
        console.error('Search failed:', error.message);
    }
}

searchExample();

Browser Usage

// Browser-compatible version using fetch
class TracebackAPIClient {
    constructor(apiKey) {
        this.apiKey = apiKey;
        this.baseURL = 'https://api.numberintelligence.com/v1/traceback';
    }
    
    async makeRequest(endpoint, params = {}) {
        const url = new URL(`${this.baseURL}/${endpoint}`);
        Object.keys(params).forEach(key => {
            if (params[key] !== undefined && params[key] !== null) {
                url.searchParams.append(key, params[key]);
            }
        });
        
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${this.apiKey}`,
                'Content-Type': 'application/json'
            }
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    }
    
    async searchReports(filters) {
        return await this.makeRequest('search', filters);
    }
    
    async getQuarters() {
        return await this.makeRequest('quarters');
    }
    
    async getStats() {
        return await this.makeRequest('stats');
    }
}

// Usage in browser
const client = new TracebackAPIClient('your_api_key_here');

client.searchReports({
    violation_type: 'SPAM',
    quarter: '2024-Q1'
}).then(results => {
    console.log('Search results:', results);
    displayResults(results.data.reports);
}).catch(error => {
    console.error('Error:', error);
});

PHP

Basic Search

apiKey = $apiKey;
        $this->baseURL = 'https://api.numberintelligence.com/v1/traceback';
    }
    
    private function makeRequest($endpoint, $params = []) {
        $url = $this->baseURL . '/' . $endpoint;
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        
        $headers = [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json'
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode !== 200) {
            throw new Exception("API request failed with status: $httpCode");
        }
        
        return json_decode($response, true);
    }
    
    public function searchReports($params = []) {
        return $this->makeRequest('search', $params);
    }
    
    public function exportReports($format = 'csv', $filters = []) {
        $params = array_merge(['format' => $format], $filters);
        return $this->makeRequest('export', $params);
    }
    
    public function getTopOffenders($quarter, $limit = 10) {
        return $this->makeRequest('providers/top-offenders', [
            'quarter' => $quarter,
            'limit' => $limit
        ]);
    }
    
    public function getQuarters() {
        return $this->makeRequest('quarters');
    }
    
    public function getStats() {
        return $this->makeRequest('stats');
    }
}

// Usage example
$api = new TracebackAPI('your_api_key_here');

try {
    $results = $api->searchReports([
        'phone_number' => '+15551234567',
        'start_date' => '2024-01-01',
        'end_date' => '2024-01-31',
        'limit' => 50
    ]);
    
    if ($results['success']) {
        echo "Found {$results['data']['total_count']} reports\n";
        foreach ($results['data']['reports'] as $report) {
            echo "- {$report['violation_type']}: {$report['provider_name']}\n";
        }
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

?>

Advanced Search

searchReports($filters);
        
        if (!$results['success']) {
            throw new Exception('API returned error: ' . json_encode($results));
        }
        
        return $results['data'];
    } catch (Exception $e) {
        error_log("Traceback API Error: " . $e->getMessage());
        return null;
    }
}

// Search for specific violation types
$searchFilters = [
    'violation_type' => 'SPAM',
    'quarter' => '2024-Q1',
    'provider_role' => 'ORIGINATING'
];

$data = advancedSearch($api, $searchFilters);

if ($data) {
    foreach ($data['reports'] as $report) {
        printf("Provider: %s\n", $report['provider_name']);
        printf("Violation: %s\n", $report['violation_type']);
        printf("Quarter: %s\n", $report['quarter']);
        echo "---\n";
    }
} else {
    echo "Search failed or returned no results\n";
}

?>

cURL

Basic Search

# Basic search by phone number
curl -X GET "https://api.numberintelligence.com/v1/traceback/search?phone_number=%2B15551234567&limit=50" \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json"

Advanced Search with Filters

# Search with multiple filters
curl -X GET "https://api.numberintelligence.com/v1/traceback/search?violation_type=SPAM&quarter=2024-Q1&provider_role=ORIGINATING&limit=100" \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json"

Export to CSV

# Export search results to CSV
curl -X GET "https://api.numberintelligence.com/v1/traceback/export?format=csv&phone_number=%2B15551234567&start_date=2024-01-01&end_date=2024-01-31" \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -o traceback_report.csv

Get Top Offenders

# Get top offending providers for a quarter
curl -X GET "https://api.numberintelligence.com/v1/traceback/providers/top-offenders?quarter=2024-Q1&limit=10" \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json"

Get Available Quarters

# List available quarters
curl -X GET "https://api.numberintelligence.com/v1/traceback/quarters" \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json"

Get Statistics

# Get general statistics
curl -X GET "https://api.numberintelligence.com/v1/traceback/stats" \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json"

POST Request Example

# Search using POST with JSON body
curl -X POST "https://api.numberintelligence.com/v1/traceback/search" \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "phone_number": "+15551234567",
       "start_date": "2024-01-01",
       "end_date": "2024-01-31",
       "violation_type": "SPAM",
       "limit": 50
     }'

Integration Patterns

Batch Processing (Python)

import time
from datetime import datetime, timedelta

def process_daily_reports(api, days_back=7):
    """Process reports for the last N days"""
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days_back)
    
    # Get reports day by day to avoid large result sets
    current_date = start_date
    all_reports = []
    
    while current_date <= end_date:
        date_str = current_date.strftime('%Y-%m-%d')
        
        try:
            results = api.searchReports({
                'start_date': date_str,
                'end_date': date_str,
                'limit': 100
            })
            
            if results and results['success']:
                all_reports.extend(results['data']['reports'])
                print(f"Processed {len(results['data']['reports'])} reports for {date_str}")
            
            # Rate limiting - wait between requests
            time.sleep(0.1)
            
        except Exception as e:
            print(f"Error processing {date_str}: {e}")
        
        current_date += timedelta(days=1)
    
    return all_reports

# Usage
api = TracebackAPI('your_api_key_here')
reports = process_daily_reports(api, days_back=30)
print(f"Total reports processed: {len(reports)}")

Real-time Monitoring (JavaScript)

class TracebackMonitor {
    constructor(apiKey, checkInterval = 300000) { // 5 minutes
        this.api = new TracebackAPI(apiKey);
        this.checkInterval = checkInterval;
        this.lastCheck = new Date();
        this.isRunning = false;
    }
    
    async startMonitoring() {
        this.isRunning = true;
        console.log('Starting traceback monitoring...');
        
        while (this.isRunning) {
            try {
                await this.checkForNewReports();
                await this.sleep(this.checkInterval);
            } catch (error) {
                console.error('Monitoring error:', error);
                await this.sleep(60000); // Wait 1 minute on error
            }
        }
    }
    
    async checkForNewReports() {
        const now = new Date();
        const startDate = this.lastCheck.toISOString().split('T')[0];
        const endDate = now.toISOString().split('T')[0];
        
        const results = await this.api.searchReports({
            start_date: startDate,
            end_date: endDate,
            limit: 1000
        });
        
        if (results.success && results.data.reports.length > 0) {
            console.log(`Found ${results.data.reports.length} new reports`);
            await this.processNewReports(results.data.reports);
        }
        
        this.lastCheck = now;
    }
    
    async processNewReports(reports) {
        for (const report of reports) {
            // Process each report (send alerts, update database, etc.)
            if (report.violation_type === 'SPAM') {
                console.log(`SPAM alert: ${report.phone_number} from ${report.provider_name}`);
            }
        }
    }
    
    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    
    stop() {
        this.isRunning = false;
        console.log('Stopping traceback monitoring...');
    }
}

// Usage
const monitor = new TracebackMonitor('your_api_key_here');
monitor.startMonitoring();
Need Help? Check out our REST endpoints documentation for detailed parameter information, or review our FAQ for common questions.