Code Examples

Complete code examples for integrating the VIN Decoder API in various programming languages.

Jump to: Python | JavaScript | cURL | PHP

Python

Basic VIN Decode
import requests

# Using API Key
headers = {
    'X-API-Key': 'your-api-key-here'
}

response = requests.post(
    'https://api.vinreveal.com/api/v1/decode',
    headers=headers,
    json={'vin': 'WAUAFAFL1DN015882'}
)

if response.status_code == 200:
    data = response.json()
    print(f"Make: {data['make']}")
    print(f"Model: {data['model']}")
    print(f"Year: {data['year']}")
Batch VIN Decode
import requests
import csv

# Read VINs from CSV
vins = []
with open('vins.csv', 'r') as file:
    reader = csv.reader(file)
    vins = [row[0] for row in reader]

# Batch decode
headers = {'X-API-Key': 'your-api-key-here'}
response = requests.post(
    'https://api.vinreveal.com/api/v1/decode/batch',
    headers=headers,
    json={'vins': vins}
)

# Process results
if response.status_code == 200:
    results = response.json()['results']
    for result in results:
        print(f"{result['vin']}: {result['make']} {result['model']}")
Error Handling
import requests
from requests.exceptions import RequestException

def decode_vin_with_error_handling(vin, api_key):
    """Decode a VIN with comprehensive error handling."""
    headers = {
        'X-API-Key': api_key,
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(
            'https://www.vinreveal.com/api/v1/decode',
            headers=headers,
            json={'vin': vin},
            timeout=30
        )

        # Check for HTTP errors
        if response.status_code == 200:
            return {'success': True, 'data': response.json()}
        elif response.status_code == 400:
            return {'success': False, 'error': 'Invalid VIN format'}
        elif response.status_code == 401:
            return {'success': False, 'error': 'Invalid API key'}
        elif response.status_code == 429:
            error_data = response.json()
            return {
                'success': False,
                'error': 'Rate limit exceeded',
                'retry_after': response.headers.get('Retry-After')
            }
        else:
            return {'success': False, 'error': f'HTTP {response.status_code}'}

    except RequestException as e:
        return {'success': False, 'error': f'Network error: {str(e)}'}
    except ValueError as e:
        return {'success': False, 'error': 'Invalid JSON response'}

# Usage
result = decode_vin_with_error_handling('WAUAFAFL1DN015882', 'your-api-key')
if result['success']:
    print(f"Vehicle: {result['data']['make']} {result['data']['model']}")
else:
    print(f"Error: {result['error']}")
Complete Implementation
import requests
import json
import time
from datetime import datetime

class VINDecoderClient:
    """Complete VIN Decoder API client implementation."""

    def __init__(self, api_key, base_url='https://www.vinreveal.com/api/v1/'):
        self.api_key = api_key
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        self.session.headers.update({
            'X-API-Key': api_key,
            'Content-Type': 'application/json'
        })

    def decode_vin(self, vin):
        """Decode a single VIN."""
        response = self.session.post(
            f'{self.base_url}/decode',
            json={'vin': vin}
        )
        response.raise_for_status()
        return response.json()

    def get_cached_vin(self, vin):
        """Get cached VIN data (doesn't count against quota)."""
        response = self.session.get(f'{self.base_url}/decode/{vin}')
        if response.status_code == 404:
            return None
        response.raise_for_status()
        return response.json()

    def get_usage_stats(self):
        """Get current usage statistics."""
        response = self.session.get(f'{self.base_url}/user/usage')
        response.raise_for_status()
        return response.json()

    def get_history(self, page=1, page_size=20, **filters):
        """Get decode history with optional filters."""
        params = {'page': page, 'page_size': page_size, **filters}
        response = self.session.get(
            f'{self.base_url}/user/history',
            params=params
        )
        response.raise_for_status()
        return response.json()

    def decode_with_cache(self, vin):
        """Try cache first, then decode if needed."""
        # Try to get from cache first
        cached = self.get_cached_vin(vin)
        if cached:
            print(f"VIN {vin} found in cache")
            return cached

        # Not in cache, decode it
        print(f"Decoding VIN {vin}...")
        return self.decode_vin(vin)

    def batch_decode(self, vins, use_cache=True):
        """Decode multiple VINs with progress tracking."""
        results = []
        total = len(vins)

        for i, vin in enumerate(vins, 1):
            print(f"Processing {i}/{total}: {vin}")
            try:
                if use_cache:
                    result = self.decode_with_cache(vin)
                else:
                    result = self.decode_vin(vin)
                results.append({'vin': vin, 'success': True, 'data': result})
            except Exception as e:
                results.append({'vin': vin, 'success': False, 'error': str(e)})
                print(f"Error decoding {vin}: {e}")

            # Add delay to respect rate limits
            if i < total:
                time.sleep(0.1)

        return results

# Example usage
if __name__ == '__main__':
    # Initialize client
    client = VINDecoderClient('your-api-key-here')

    # Check usage before starting
    usage = client.get_usage_stats()
    print(f"Monthly usage: {usage['used_this_month']}/{usage['monthly_limit']}")

    # Decode a single VIN
    try:
        result = client.decode_vin('WAUAFAFL1DN015882')
        print(f"\nDecoded: {result['year']} {result['make']} {result['model']}")
    except requests.HTTPError as e:
        print(f"Error: {e}")

    # Batch decode with cache
    vins = [
        'WAUAFAFL1DN015882',
        'WBAVA13571PZ12345',
        'JM1BL1SF6A1185097'
    ]

    print("\nBatch decoding...")
    results = client.batch_decode(vins)

    # Process results
    successful = [r for r in results if r['success']]
    failed = [r for r in results if not r['success']]

    print(f"\nSuccessfully decoded: {len(successful)}")
    print(f"Failed: {len(failed)}")

    # Get recent history
    history = client.get_history(page_size=5)
    print(f"\nRecent decodes: {history['count']} total")
    for item in history['results']:
        print(f"  - {item['vin']}: {item['make']} {item['model']}")

JavaScript

Basic VIN Decode
// Using Fetch API
const headers = {
    'X-API-Key': 'your-api-key-here',
    'Content-Type': 'application/json'
};

fetch('https://api.vinreveal.com/api/v1/decode', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify({ vin: 'WAUAFAFL1DN015882' })
})
.then(response => response.json())
.then(data => {
    console.log(`Make: ${data.make}`);
    console.log(`Model: ${data.model}`);
    console.log(`Year: ${data.year}`);
})
.catch(error => console.error('Error:', error));
Batch VIN Decode
// Batch decode with async/await
async function batchDecode(vins) {
    const headers = {
        'X-API-Key': 'your-api-key-here',
        'Content-Type': 'application/json'
    };

    try {
        const response = await fetch('https://api.vinreveal.com/api/v1/decode/batch', {
            method: 'POST',
            headers: headers,
            body: JSON.stringify({ vins: vins })
        });

        const data = await response.json();
        data.results.forEach(result => {
            console.log(`${result.vin}: ${result.make} ${result.model}`);
        });
    } catch (error) {
        console.error('Error:', error);
    }
}

// Usage
const vins = ['WAUAFAFL1DN015882', 'WBAVA13571PZ12345'];
batchDecode(vins);
Error Handling
// Error handling with async/await
async function decodeVINWithErrorHandling(vin, apiKey) {
    const headers = {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
    };

    try {
        const response = await fetch('https://www.vinreveal.com/api/v1/decode', {
            method: 'POST',
            headers: headers,
            body: JSON.stringify({ vin: vin }),
            timeout: 30000
        });

        const data = await response.json();

        if (response.ok) {
            return { success: true, data: data };
        } else {
            // Handle specific error codes
            switch (response.status) {
                case 400:
                    return { success: false, error: 'Invalid VIN format' };
                case 401:
                    return { success: false, error: 'Invalid API key' };
                case 429:
                    return {
                        success: false,
                        error: 'Rate limit exceeded',
                        retryAfter: response.headers.get('Retry-After')
                    };
                default:
                    return { success: false, error: `HTTP ${response.status}` };
            }
        }
    } catch (error) {
        if (error.name === 'AbortError') {
            return { success: false, error: 'Request timeout' };
        } else if (error instanceof TypeError) {
            return { success: false, error: 'Network error' };
        } else {
            return { success: false, error: error.message };
        }
    }
}

// Usage with error handling
const result = await decodeVINWithErrorHandling('WAUAFAFL1DN015882', 'your-api-key');
if (result.success) {
    console.log(`Vehicle: ${result.data.make} ${result.data.model}`);
} else {
    console.error(`Error: ${result.error}`);
    if (result.retryAfter) {
        console.log(`Retry after ${result.retryAfter} seconds`);
    }
}
Complete Implementation
// Complete VIN Decoder API client implementation
class VINDecoderClient {
    constructor(apiKey, baseUrl = 'https://www.vinreveal.com/api/v1/') {
        this.apiKey = apiKey;
        this.baseUrl = baseUrl.replace(/\/$/, '');
        this.headers = {
            'X-API-Key': apiKey,
            'Content-Type': 'application/json'
        };
    }

    async decodeVIN(vin) {
        const response = await fetch(`${this.baseUrl}/decode`, {
            method: 'POST',
            headers: this.headers,
            body: JSON.stringify({ vin })
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return await response.json();
    }

    async getCachedVIN(vin) {
        const response = await fetch(`${this.baseUrl}/decode/${vin}`, {
            headers: this.headers
        });

        if (response.status === 404) {
            return null;
        }

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return await response.json();
    }

    async getUsageStats() {
        const response = await fetch(`${this.baseUrl}/user/usage`, {
            headers: this.headers
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return await response.json();
    }

    async getHistory(options = {}) {
        const params = new URLSearchParams({
            page: options.page || 1,
            page_size: options.pageSize || 20,
            ...options.filters
        });

        const response = await fetch(`${this.baseUrl}/user/history?${params}`, {
            headers: this.headers
        });

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return await response.json();
    }

    async decodeWithCache(vin) {
        // Try cache first
        const cached = await this.getCachedVIN(vin);
        if (cached) {
            console.log(`VIN ${vin} found in cache`);
            return cached;
        }

        // Not in cache, decode it
        console.log(`Decoding VIN ${vin}...`);
        return await this.decodeVIN(vin);
    }

    async batchDecode(vins, useCache = true) {
        const results = [];
        const total = vins.length;

        for (let i = 0; i < total; i++) {
            const vin = vins[i];
            console.log(`Processing ${i + 1}/${total}: ${vin}`);

            try {
                const data = useCache
                    ? await this.decodeWithCache(vin)
                    : await this.decodeVIN(vin);

                results.push({ vin, success: true, data });
            } catch (error) {
                results.push({ vin, success: false, error: error.message });
                console.error(`Error decoding ${vin}:`, error);
            }

            // Add delay to respect rate limits
            if (i < total - 1) {
                await new Promise(resolve => setTimeout(resolve, 100));
            }
        }

        return results;
    }
}

// Example usage
async function main() {
    // Initialize client
    const client = new VINDecoderClient('your-api-key-here');

    try {
        // Check usage
        const usage = await client.getUsageStats();
        console.log(`Monthly usage: ${usage.used_this_month}/${usage.monthly_limit}`);

        // Decode a single VIN
        const result = await client.decodeVIN('WAUAFAFL1DN015882');
        console.log(`\nDecoded: ${result.year} ${result.make} ${result.model}`);

        // Batch decode
        const vins = [
            'WAUAFAFL1DN015882',
            'WBAVA13571PZ12345',
            'JM1BL1SF6A1185097'
        ];

        console.log('\nBatch decoding...');
        const results = await client.batchDecode(vins);

        // Process results
        const successful = results.filter(r => r.success);
        const failed = results.filter(r => !r.success);

        console.log(`\nSuccessfully decoded: ${successful.length}`);
        console.log(`Failed: ${failed.length}`);

        // Get recent history
        const history = await client.getHistory({ pageSize: 5 });
        console.log(`\nRecent decodes: ${history.count} total`);
        history.results.forEach(item => {
            console.log(`  - ${item.vin}: ${item.make} ${item.model}`);
        });

    } catch (error) {
        console.error('Error:', error);
    }
}

// Run the example
main();

cURL

Basic VIN Decode
# Using API Key
curl -X POST https://api.vinreveal.com/api/v1/decode \
  -H "X-API-Key: your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{"vin": "WAUAFAFL1DN015882"}'

# Using Token Authentication
curl -X POST https://api.vinreveal.com/api/v1/decode \
  -H "Authorization: Token your-token-here" \
  -H "Content-Type: application/json" \
  -d '{"vin": "WAUAFAFL1DN015882"}'
Batch VIN Decode
# Batch decode multiple VINs
curl -X POST https://api.vinreveal.com/api/v1/decode/batch \
  -H "X-API-Key: your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "vins": [
      "WAUAFAFL1DN015882",
      "WBAVA13571PZ12345",
      "JM1BL1SF6A1185097"
    ]
  }'
Error Handling
# Error handling example
# Using API Key
curl -X POST https://api.vinreveal.com/api/v1/decode \
  -H "X-API-Key: your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{"vin": "WAUAFAFL1DN015882"}'

# Using Token Authentication
curl -X POST https://api.vinreveal.com/api/v1/decode \
  -H "Authorization: Token your-token-here" \
  -H "Content-Type: application/json" \
  -d '{"vin": "WAUAFAFL1DN015882"}'
Complete Implementation
# Using API Key
curl -X POST https://api.vinreveal.com/api/v1/decode \
  -H "X-API-Key: your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{"vin": "WAUAFAFL1DN015882"}'

# Using Token Authentication
curl -X POST https://api.vinreveal.com/api/v1/decode \
  -H "Authorization: Token your-token-here" \
  -H "Content-Type: application/json" \
  -d '{"vin": "WAUAFAFL1DN015882"}'

PHP

Basic VIN Decode
<?php
$vin = 'WAUAFAFL1DN015882';
$apiKey = 'your-api-key-here';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.vinreveal.com/api/v1/decode');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-API-Key: ' . $apiKey,
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['vin' => $vin]));

$response = curl_exec($ch);
$data = json_decode($response, true);

if ($data) {
    echo "Make: " . $data['make'] . "\n";
    echo "Model: " . $data['model'] . "\n";
    echo "Year: " . $data['year'] . "\n";
}

curl_close($ch);
?>
Batch VIN Decode
<?php
$vins = [
    'WAUAFAFL1DN015882',
    'WBAVA13571PZ12345',
    'JM1BL1SF6A1185097'
];
$apiKey = 'your-api-key-here';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.vinreveal.com/api/v1/decode/batch');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-API-Key: ' . $apiKey,
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['vins' => $vins]));

$response = curl_exec($ch);
$data = json_decode($response, true);

if ($data && isset($data['results'])) {
    foreach ($data['results'] as $result) {
        echo $result['vin'] . ": " . $result['make'] . " " . $result['model'] . "\n";
    }
}

curl_close($ch);
?>
Error Handling
 $vin]));
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    // Handle cURL errors
    if ($error) {
        return ['success' => false, 'error' => 'Network error: ' . $error];
    }

    // Parse response
    $data = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return ['success' => false, 'error' => 'Invalid JSON response'];
    }

    // Handle HTTP status codes
    switch ($httpCode) {
        case 200:
            return ['success' => true, 'data' => $data];
        case 400:
            return ['success' => false, 'error' => 'Invalid VIN format'];
        case 401:
            return ['success' => false, 'error' => 'Invalid API key'];
        case 429:
            return [
                'success' => false,
                'error' => 'Rate limit exceeded',
                'details' => $data
            ];
        default:
            return ['success' => false, 'error' => 'HTTP ' . $httpCode];
    }
}

// Usage
$result = decodeVINWithErrorHandling('WAUAFAFL1DN015882', 'your-api-key');
if ($result['success']) {
    echo "Vehicle: " . $result['data']['make'] . " " . $result['data']['model'];
} else {
    echo "Error: " . $result['error'];
}
?>
Complete Implementation
<?php
$vin = 'WAUAFAFL1DN015882';
$apiKey = 'your-api-key-here';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.vinreveal.com/api/v1/decode');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-API-Key: ' . $apiKey,
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['vin' => $vin]));

$response = curl_exec($ch);
$data = json_decode($response, true);

if ($data) {
    echo "Make: " . $data['make'] . "\n";
    echo "Model: " . $data['model'] . "\n";
    echo "Year: " . $data['year'] . "\n";
}

curl_close($ch);
?>

Additional Resources

Rate Limiting

Remember to implement proper rate limiting in your applications. The API allows 60 requests per minute per API key. Consider adding delays between requests when processing multiple VINs.