API Reference
This document provides comprehensive API documentation for the Beyond Compare tool, including programmatic access, integration methods, and usage examples.
Overview
The Beyond Compare tool provides both client-side JavaScript APIs and server-side REST APIs for programmatic access to comparison functionality.
Client-Side API
Core Comparison API
compareFiles(fileA, fileB, options)
Performs a file comparison between two files.
Parameters:
fileA
(File): First file to comparefileB
(File): Second file to compareoptions
(Object): Comparison options
Options:
{
ignoreWhitespace: boolean, // Default: false
ignoreCase: boolean, // Default: false
showLineNumbers: boolean, // Default: true
algorithm: string, // 'standard' | 'semantic' | 'binary'
contextLines: number // Default: 3
}
Returns:
{
added: number,
removed: number,
modified: number,
diffs: Array<{
type: 'added' | 'removed' | 'modified',
lineA: number | string,
lineB: number | string,
contentA: string,
contentB: string
}>
}
Example:
const result = await compareFiles(fileA, fileB, {
ignoreWhitespace: true,
ignoreCase: false,
showLineNumbers: true,
});
console.log(`Added: ${result.added}, Removed: ${result.removed}, Modified: ${result.modified}`);
compareTexts(textA, textB, options)
Performs a text comparison between two text strings.
Parameters:
textA
(string): First text to comparetextB
(string): Second text to compareoptions
(Object): Comparison options (same as compareFiles)
Returns: Same as compareFiles
Example:
const result = compareTexts('Hello World', 'Hello Universe', { ignoreCase: true });
History Management API
saveComparison(comparison)
Saves a comparison result to history.
Parameters:
comparison
(Object): Comparison data to save
Example:
const comparison = {
id: Date.now().toString(),
fileAName: 'file1.txt',
fileBName: 'file2.txt',
type: 'file',
timestamp: Date.now(),
result: comparisonResult,
};
saveComparison(comparison);
getHistory()
Retrieves all saved comparisons.
Returns:
Array<{
id: string,
fileAName: string,
fileBName: string,
type: 'file' | 'text',
timestamp: number,
result: ComparisonResult
}>
loadComparison(id)
Loads a specific comparison from history.
Parameters:
id
(string): Comparison ID
Returns: Comparison object or null if not found
Utility Functions
formatFileSize(bytes)
Formats file size in human-readable format.
Parameters:
bytes
(number): File size in bytes
Returns: Formatted string (e.g., "1.5 MB")
validateFile(file)
Validates a file for comparison.
Parameters:
file
(File): File to validate
Returns:
{
valid: boolean,
error?: string,
warnings?: string[]
}
Server-Side REST API
Base URL
https://api.example.com/beyond-compare/v1
Authentication
All API requests require authentication using API keys:
Authorization: Bearer YOUR_API_KEY
Endpoints
POST /compare/files
Compare two files by uploading them.
Request:
POST /compare/files
Content-Type: multipart/form-data
fileA: [file]
fileB: [file]
options: {
"ignoreWhitespace": true,
"ignoreCase": false,
"showLineNumbers": true
}
Response:
{
"success": true,
"data": {
"added": 5,
"removed": 3,
"modified": 2,
"diffs": [
{
"type": "added",
"lineA": "-",
"lineB": 10,
"contentA": "",
"contentB": "new line content"
}
]
},
"metadata": {
"processingTime": 150,
"fileSizeA": 1024,
"fileSizeB": 2048
}
}
POST /compare/texts
Compare two text strings.
Request:
POST /compare/texts
Content-Type: application/json
{
"textA": "Hello World",
"textB": "Hello Universe",
"options": {
"ignoreWhitespace": false,
"ignoreCase": true
}
}
Response:
{
"success": true,
"data": {
"added": 1,
"removed": 1,
"modified": 0,
"diffs": [
{
"type": "removed",
"lineA": 1,
"lineB": "-",
"contentA": "Hello World",
"contentB": ""
},
{
"type": "added",
"lineA": "-",
"lineB": 1,
"contentA": "",
"contentB": "Hello Universe"
}
]
}
}
GET /history
Retrieve comparison history.
Query Parameters:
limit
(number): Maximum number of results (default: 50)offset
(number): Number of results to skip (default: 0)type
(string): Filter by comparison type ('file' | 'text')
Response:
{
"success": true,
"data": [
{
"id": "1234567890",
"fileAName": "file1.txt",
"fileBName": "file2.txt",
"type": "file",
"timestamp": 1640995200000,
"summary": {
"added": 5,
"removed": 3,
"modified": 2
}
}
],
"pagination": {
"total": 100,
"limit": 50,
"offset": 0,
"hasMore": true
}
}
GET /history/{id}
Retrieve a specific comparison from history.
Response:
{
"success": true,
"data": {
"id": "1234567890",
"fileAName": "file1.txt",
"fileBName": "file2.txt",
"type": "file",
"timestamp": 1640995200000,
"result": {
"added": 5,
"removed": 3,
"modified": 2,
"diffs": [...]
}
}
}
DELETE /history/{id}
Delete a specific comparison from history.
Response:
{
"success": true,
"message": "Comparison deleted successfully"
}
Error Handling
Client-Side Errors
try {
const result = await compareFiles(fileA, fileB);
} catch (error) {
if (error.name === 'FileSizeError') {
console.error('File too large:', error.message);
} else if (error.name === 'FileFormatError') {
console.error('Unsupported file format:', error.message);
} else {
console.error('Comparison failed:', error.message);
}
}
Server-Side Errors
Error Response Format
{
"success": false,
"error": {
"code": "INVALID_FILE_FORMAT",
"message": "Unsupported file format",
"details": {
"supportedFormats": ["txt", "js", "json", "xml"]
}
}
}
Common Error Codes
INVALID_FILE_FORMAT
: Unsupported file formatFILE_TOO_LARGE
: File exceeds size limitINVALID_OPTIONS
: Invalid comparison optionsPROCESSING_ERROR
: Internal processing errorAUTHENTICATION_ERROR
: Invalid API keyRATE_LIMIT_EXCEEDED
: Too many requests
Rate Limiting
Limits
- Free Tier: 100 requests per hour
- Pro Tier: 1000 requests per hour
- Enterprise: Custom limits
Headers
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
SDKs and Libraries
JavaScript SDK
npm install beyond-compare-sdk
import { BeyondCompare } from 'beyond-compare-sdk';
const client = new BeyondCompare({
apiKey: 'your-api-key',
baseUrl: 'https://api.example.com/beyond-compare/v1',
});
const result = await client.compareFiles(fileA, fileB, {
ignoreWhitespace: true,
});
Python SDK
pip install beyond-compare-python
from beyond_compare import BeyondCompare
client = BeyondCompare(api_key='your-api-key')
result = client.compare_files(
file_a='file1.txt',
file_b='file2.txt',
options={'ignore_whitespace': True}
)
Webhooks
Configuration
Set up webhooks to receive notifications about comparison events:
POST /webhooks
Content-Type: application/json
{
"url": "https://your-app.com/webhook",
"events": ["comparison.completed", "comparison.failed"],
"secret": "your-webhook-secret"
}
Webhook Payload
{
"event": "comparison.completed",
"data": {
"id": "1234567890",
"type": "file",
"result": {
"added": 5,
"removed": 3,
"modified": 2
}
},
"timestamp": 1640995200000
}
Best Practices
Performance Optimization
- Use Appropriate Options: Enable relevant options to improve performance
- Batch Operations: Use batch endpoints for multiple comparisons
- Caching: Cache results when possible
- Error Handling: Implement proper error handling and retry logic
Security
- API Key Management: Secure your API keys and rotate them regularly
- HTTPS Only: Always use HTTPS for API communications
- Input Validation: Validate all inputs before processing
- Rate Limiting: Respect rate limits and implement backoff strategies
Integration
- Async Operations: Use async/await for better performance
- Progress Tracking: Implement progress indicators for long operations
- User Feedback: Provide clear feedback for all operations
- Fallback Handling: Implement fallback mechanisms for API failures
This API reference provides comprehensive documentation for integrating the Beyond Compare tool into your applications and workflows.