API Documentation
Code Examples
Ready-to-use code examples and SDK implementations for integrating the Traceback Search API into your applications.
Python SDK
Install the official Python SDK:
pip install traceback-search-api
Basic Usage
from traceback_search import TracebackAPI
# Initialize the client
api = TracebackAPI("your_api_key_here")
# Search for spam reports
results = api.search_spam_reports(
sender_number="+15551234567",
days_back=30,
limit=100
)
print(f"Found {results['total_count']} spam reports")
for report in results['reports']:
print(f"- {report['spam_type']}: {report['message_content'][:50]}...")
Advanced Search with Filters
from datetime import datetime, timedelta
# Search with multiple filters
end_date = datetime.now()
start_date = end_date - timedelta(days=7)
results = api.search_spam_reports(
spam_types=["phishing", "scam"],
start_date=start_date.isoformat(),
end_date=end_date.isoformat(),
carriers=["Verizon", "AT&T"],
min_confidence=0.8,
limit=500
)
# Process results
for report in results['reports']:
print(f"Spam Type: {report['spam_type']}")
print(f"Confidence: {report['confidence_score']}")
print(f"Carrier: {report['carrier_info']['name']}")
print("---")
Export to CSV
import csv
from io import StringIO
# Export spam reports
csv_data = api.export_reports(
sender_number="+15551234567",
format="csv",
include_content=True
)
# Save to file
with open("spam_report.csv", "wb") as f:
f.write(csv_data)
# Or process in memory
csv_string = csv_data.decode('utf-8')
csv_reader = csv.DictReader(StringIO(csv_string))
for row in csv_reader:
print(f"Report ID: {row['id']}, Type: {row['spam_type']}")
Error Handling
from traceback_search.exceptions import (
TracebackAPIError,
RateLimitError,
AuthenticationError
)
try:
results = api.search_spam_reports("+15551234567")
except AuthenticationError:
print("Invalid API key")
except RateLimitError as e:
print(f"Rate limit exceeded. Retry after {e.retry_after} seconds")
except TracebackAPIError as e:
print(f"API Error: {e.message} (Code: {e.error_code})")
JavaScript SDK
Install via npm:
npm install traceback-search-api
Node.js Usage
const { TracebackAPI } = require('traceback-search-api');
// Initialize the client
const api = new TracebackAPI('your_api_key_here');
// Search for spam reports
async function searchSpamReports() {
try {
const results = await api.searchSpamReports({
senderNumber: '+15551234567',
daysBack: 30,
limit: 100
});
console.log(`Found ${results.totalCount} spam reports`);
results.reports.forEach(report => {
console.log(`- ${report.spamType}: ${report.messageContent.substring(0, 50)}...`);
});
} catch (error) {
console.error('Error:', error.message);
}
}
searchSpamReports();
Browser Usage
// Include via CDN
//
const api = new TracebackSearchAPI.TracebackAPI('your_api_key_here');
// Search with async/await
async function analyzeSpamReports() {
try {
const results = await api.searchSpamReports({
spamTypes: ['phishing', 'scam'],
startDate: '2024-01-01T00:00:00Z',
endDate: '2024-01-31T23:59:59Z',
limit: 200
});
// Display results in UI
displayResults(results.reports);
} catch (error) {
if (error.code === 'RATE_LIMIT_EXCEEDED') {
setTimeout(() => analyzeSpamReports(), error.retryAfter * 1000);
} else {
console.error('API Error:', error);
}
}
}
function displayResults(reports) {
const container = document.getElementById('results');
container.innerHTML = reports.map(report => `
${report.spamType}
Sender: ${report.senderNumber}
Confidence: ${(report.confidenceScore * 100).toFixed(1)}%
Carrier: ${report.carrierInfo.name}
`).join('');
}
Export and Download
// Export reports and trigger download
async function exportAndDownload() {
try {
const csvBlob = await api.exportReports({
senderNumber: '+15551234567',
format: 'csv',
includeContent: true
});
// Create download link
const url = window.URL.createObjectURL(csvBlob);
const a = document.createElement('a');
a.href = url;
a.download = 'spam_report.csv';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
} catch (error) {
console.error('Export failed:', error);
}
}
PHP SDK
Install via Composer:
composer require traceback-search/api-client
Basic Usage
searchSpamReports([
'sender_number' => '+15551234567',
'days_back' => 30,
'limit' => 100
]);
echo "Found {$results['total_count']} spam reports\n";
foreach ($results['reports'] as $report) {
echo "- {$report['spam_type']}: " . substr($report['message_content'], 0, 50) . "...\n";
}
} catch (TracebackApiException $e) {
echo "API Error: {$e->getMessage()}\n";
}
?>
Advanced Search
sub(new DateInterval('P7D'));
$results = $api->searchSpamReports([
'spam_types' => ['phishing', 'scam'],
'start_date' => $startDate->format('c'),
'end_date' => $endDate->format('c'),
'carriers' => ['Verizon', 'AT&T'],
'min_confidence' => 0.8,
'limit' => 500
]);
// Process results
foreach ($results['reports'] as $report) {
echo "Spam Type: {$report['spam_type']}\n";
echo "Confidence: {$report['confidence_score']}\n";
echo "Carrier: {$report['carrier_info']['name']}\n";
echo "---\n";
}
?>
Export Handling
exportReports([
'sender_number' => '+15551234567',
'format' => 'csv',
'include_content' => true
]);
// Save to file
file_put_contents('spam_report.csv', $csvData);
// Or process in memory
$lines = explode("\n", $csvData);
$header = str_getcsv(array_shift($lines));
foreach ($lines as $line) {
if (empty(trim($line))) continue;
$data = str_getcsv($line);
$row = array_combine($header, $data);
echo "Report ID: {$row['id']}, Type: {$row['spam_type']}\n";
}
?>
cURL Examples
Direct HTTP requests using cURL for testing and integration.
Basic Search
curl -X GET "https://api.numberintelligence.com/v1/traceback/search?sender_number=%2B15551234567&limit=100" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json"
Advanced Search with Filters
curl -X GET "https://api.numberintelligence.com/v1/traceback/search" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-G \
--data-urlencode "spam_type=phishing" \
--data-urlencode "start_date=2024-01-01T00:00:00Z" \
--data-urlencode "end_date=2024-01-31T23:59:59Z" \
--data-urlencode "carrier=Verizon" \
--data-urlencode "limit=200"
Export to CSV
curl -X GET "https://api.numberintelligence.com/v1/traceback/export" \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
--data-urlencode "format=csv" \
--data-urlencode "sender_number=+15551234567" \
--data-urlencode "include_content=true" \
--output spam_report.csv
Get Statistics
curl -X GET "https://api.numberintelligence.com/v1/traceback/stats" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-G \
--data-urlencode "metric=top_senders" \
--data-urlencode "limit=10" \
--data-urlencode "start_date=2024-01-01T00:00:00Z"
GraphQL Query
curl -X POST "https://api.numberintelligence.com/v1/graphql" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "query { spamReports(filters: { senderNumber: \"+15551234567\" limit: 50 }) { edges { node { id senderNumber spamType confidenceScore } } totalCount } }"
}'
Error Handling
# Include response headers to check rate limits
curl -X GET "https://api.numberintelligence.com/v1/traceback/search?sender_number=%2B15551234567" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-i # Include response headers
# Check HTTP status code
curl -X GET "https://api.numberintelligence.com/v1/traceback/search?sender_number=%2B15551234567" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-w "HTTP Status: %{http_code}\n" \
-o response.json
Integration Patterns
Batch Processing
Process large datasets efficiently with pagination and rate limiting:
# Python example for batch processing
import time
from traceback_search import TracebackAPI
api = TracebackAPI("your_api_key_here")
def process_all_reports(phone_numbers):
all_reports = []
for number in phone_numbers:
offset = 0
limit = 100
while True:
try:
results = api.search_spam_reports(
sender_number=number,
limit=limit,
offset=offset
)
all_reports.extend(results['reports'])
if not results['pagination']['has_more']:
break
offset += limit
# Respect rate limits
time.sleep(1)
except RateLimitError as e:
time.sleep(e.retry_after)
continue
return all_reports
Real-time Monitoring
Monitor for new spam reports using webhooks or polling:
// JavaScript polling example
class SpamMonitor {
constructor(apiKey, pollInterval = 60000) {
this.api = new TracebackAPI(apiKey);
this.pollInterval = pollInterval;
this.lastCheck = new Date();
}
async startMonitoring(callback) {
setInterval(async () => {
try {
const results = await this.api.searchSpamReports({
startDate: this.lastCheck.toISOString(),
endDate: new Date().toISOString(),
spamTypes: ['phishing', 'scam'],
minConfidence: 0.8
});
if (results.reports.length > 0) {
callback(results.reports);
}
this.lastCheck = new Date();
} catch (error) {
console.error('Monitoring error:', error);
}
}, this.pollInterval);
}
}
// Usage
const monitor = new SpamMonitor('your_api_key_here');
monitor.startMonitoring((newReports) => {
console.log(`Found ${newReports.length} new spam reports`);
// Process new reports
});
Need More Examples? Check out our GitHub repository for additional code samples, or contact our support team for custom integration assistance.