Bulk Operations Guide

Bulk Operations Guide

This guide demonstrates how to perform bulk operations with the AutoElite API, including creating, updating, fetching, and deleting multiple resources in a single client operation.

Overview

While the AutoElite API doesn't provide native bulk operation endpoints, you can implement client-side batching to efficiently handle multiple resources. This guide shows you how to:

  1. Create multiple vehicles in a batch
  2. Update multiple vehicles in a batch
  3. Fetch multiple vehicles efficiently
  4. Delete multiple vehicles in a batch

Bulk Create

To create multiple vehicles in a batch:

Using JavaScript/Promise.all

/**
 * Create multiple vehicles in a batch
 * @param {Array} vehicles - Array of vehicle objects to create
 * @returns {Promise<Array>} - Array of created vehicles
 */
async function bulkCreateVehicles(vehicles) {
  try {
    // Create an array of promises for each vehicle creation
    const createPromises = vehicles.map(vehicle => 
      fetch('https://api.autoelite.io/api/vehicles', {
        method: 'POST',
        headers: {
          'X-API-Key': 'your-api-key-here',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(vehicle)
      }).then(response => {
        if (!response.ok) {
          throw new Error(`Failed to create vehicle: ${response.status}`);
        }
        return response.json();
      })
    );
    
    // Execute all promises in parallel
    const results = await Promise.all(createPromises);
    
    return {
      success: true,
      created: results.length,
      vehicles: results
    };
  } catch (error) {
    console.error('Bulk create error:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

// Example usage
const vehiclesToCreate = [
  {
    make: "Toyota",
    model: "Camry",
    year: 2023,
    price: 25000,
    dealer_id: 1
  },
  {
    make: "Honda",
    model: "Accord",
    year: 2023,
    price: 27000,
    dealer_id: 1
  },
  {
    make: "Ford",
    model: "Mustang",
    year: 2023,
    price: 35000,
    dealer_id: 1
  }
];

bulkCreateVehicles(vehiclesToCreate)
  .then(result => console.log('Bulk create result:', result))
  .catch(error => console.error('Error in bulk create:', error));

Using Python

import requests
import concurrent.futures

def bulk_create_vehicles(vehicles, api_key):
    """
    Create multiple vehicles in a batch
    
    Args:
        vehicles (list): List of vehicle dictionaries to create
        api_key (str): Your API key
        
    Returns:
        dict: Results of the bulk operation
    """
    created_vehicles = []
    failed_operations = []
    
    def create_single_vehicle(vehicle):
        try:
            response = requests.post(
                'https://api.autoelite.io/api/vehicles',
                headers={
                    'X-API-Key': api_key,
                    'Content-Type': 'application/json'
                },
                json=vehicle
            )
            
            response.raise_for_status()
            return {'success': True, 'vehicle': response.json()}
        except Exception as e:
            return {'success': False, 'vehicle': vehicle, 'error': str(e)}
    
    # Use ThreadPoolExecutor to run requests in parallel
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        results = list(executor.map(create_single_vehicle, vehicles))
    
    # Process results
    for result in results:
        if result['success']:
            created_vehicles.append(result['vehicle'])
        else:
            failed_operations.append(result)
    
    return {
        'success': len(failed_operations) == 0,
        'created': len(created_vehicles),
        'failed': len(failed_operations),
        'vehicles': created_vehicles,
        'failures': failed_operations
    }

# Example usage
vehicles_to_create = [
    {
        "make": "Toyota",
        "model": "Camry",
        "year": 2023,
        "price": 25000,
        "dealer_id": 1
    },
    {
        "make": "Honda",
        "model": "Accord",
        "year": 2023,
        "price": 27000,
        "dealer_id": 1
    }
]

result = bulk_create_vehicles(vehicles_to_create, 'your-api-key-here')
print(result)

Bulk Update

To update multiple vehicles in a batch:

Using JavaScript/Promise.all

/**
 * Update multiple vehicles in a batch
 * @param {Array} vehicleUpdates - Array of objects with id and update data
 * @returns {Promise<Array>} - Array of updated vehicles
 */
async function bulkUpdateVehicles(vehicleUpdates) {
  try {
    // Create an array of promises for each vehicle update
    const updatePromises = vehicleUpdates.map(update => 
      fetch(`https://api.autoelite.io/api/vehicles/${update.id}`, {
        method: 'PUT',
        headers: {
          'X-API-Key': 'your-api-key-here',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(update.data)
      }).then(response => {
        if (!response.ok) {
          throw new Error(`Failed to update vehicle ${update.id}: ${response.status}`);
        }
        return response.json();
      })
    );
    
    // Execute all promises in parallel
    const results = await Promise.all(updatePromises);
    
    return {
      success: true,
      updated: results.length,
      vehicles: results
    };
  } catch (error) {
    console.error('Bulk update error:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

// Example usage
const vehicleUpdates = [
  {
    id: 1,
    data: {
      price: 24500,
      status: "pending"
    }
  },
  {
    id: 2,
    data: {
      price: 26500,
      status: "sold",
      sold_date: new Date().toISOString()
    }
  }
];

bulkUpdateVehicles(vehicleUpdates)
  .then(result => console.log('Bulk update result:', result))
  .catch(error => console.error('Error in bulk update:', error));

Bulk Fetch

To efficiently fetch multiple vehicles:

Using Query Parameters

/**
 * Fetch multiple vehicles by dealer ID
 * @param {number} dealerId - Dealer ID to filter vehicles
 * @returns {Promise<Array>} - Array of vehicles
 */
async function fetchVehiclesByDealer(dealerId) {
  try {
    const response = await fetch(`https://api.autoelite.io/api/vehicles?dealer_id=${dealerId}`, {
      headers: {
        'X-API-Key': 'your-api-key-here',
        'Content-Type': 'application/json'
      }
    });
    
    if (!response.ok) {
      throw new Error(`Failed to fetch vehicles: ${response.status}`);
    }
    
    const data = await response.json();
    return data.vehicles;
  } catch (error) {
    console.error('Fetch error:', error);
    throw error;
  }
}

// Example usage
fetchVehiclesByDealer(1)
  .then(vehicles => console.log(`Found ${vehicles.length} vehicles for dealer 1`))
  .catch(error => console.error('Error fetching vehicles:', error));

Fetching Specific Vehicles by ID

/**
 * Fetch multiple vehicles by their IDs
 * @param {Array} vehicleIds - Array of vehicle IDs to fetch
 * @returns {Promise<Array>} - Array of vehicles
 */
async function fetchVehiclesByIds(vehicleIds) {
  try {
    // Create an array of promises for each vehicle fetch
    const fetchPromises = vehicleIds.map(id => 
      fetch(`https://api.autoelite.io/api/vehicles/${id}`, {
        headers: {
          'X-API-Key': 'your-api-key-here',
          'Content-Type': 'application/json'
        }
      }).then(response => {
        if (response.status === 404) {
          // Vehicle not found, return null
          return null;
        } else if (!response.ok) {
          throw new Error(`Failed to fetch vehicle ${id}: ${response.status}`);
        }
        return response.json();
      })
    );
    
    // Execute all promises in parallel
    const results = await Promise.all(fetchPromises);
    
    // Filter out null results (not found vehicles)
    const vehicles = results.filter(vehicle => vehicle !== null);
    
    return {
      success: true,
      found: vehicles.length,
      notFound: results.length - vehicles.length,
      vehicles: vehicles
    };
  } catch (error) {
    console.error('Bulk fetch error:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

// Example usage
const vehicleIds = [1, 2, 3, 4, 5];

fetchVehiclesByIds(vehicleIds)
  .then(result => console.log('Bulk fetch result:', result))
  .catch(error => console.error('Error in bulk fetch:', error));

Bulk Delete

To delete multiple vehicles in a batch:

Using JavaScript/Promise.all

/**
 * Delete multiple vehicles in a batch
 * @param {Array} vehicleIds - Array of vehicle IDs to delete
 * @returns {Promise<Object>} - Results of the bulk delete operation
 */
async function bulkDeleteVehicles(vehicleIds) {
  try {
    // Create an array of promises for each vehicle deletion
    const deletePromises = vehicleIds.map(id => 
      fetch(`https://api.autoelite.io/api/vehicles/${id}`, {
        method: 'DELETE',
        headers: {
          'X-API-Key': 'your-api-key-here',
          'Content-Type': 'application/json'
        }
      }).then(response => {
        if (response.status === 404) {
          // Vehicle not found
          return { id, success: false, error: 'Not found' };
        } else if (!response.ok) {
          throw new Error(`Failed to delete vehicle ${id}: ${response.status}`);
        }
        return { id, success: true };
      })
    );
    
    // Execute all promises in parallel
    const results = await Promise.all(deletePromises);
    
    // Count successful and failed deletions
    const successful = results.filter(result => result.success);
    const failed = results.filter(result => !result.success);
    
    return {
      success: failed.length === 0,
      deleted: successful.length,
      failed: failed.length,
      results: results
    };
  } catch (error) {
    console.error('Bulk delete error:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

// Example usage
const vehicleIdsToDelete = [1, 2, 3];

bulkDeleteVehicles(vehicleIdsToDelete)
  .then(result => console.log('Bulk delete result:', result))
  .catch(error => console.error('Error in bulk delete:', error));

Best Practices for Bulk Operations

  1. Limit Batch Size: Keep batch sizes reasonable (20-50 items) to avoid timeouts and rate limiting.

  2. Handle Partial Failures: Always implement logic to handle cases where some operations succeed and others fail.

  3. Implement Retry Logic: For failed operations, implement exponential backoff retry logic.

  4. Consider Rate Limits: Be aware of API rate limits and adjust batch sizes and concurrency accordingly.

  5. Transaction Safety: Remember that these bulk operations are not transactional - if one operation fails, others may still succeed.

  6. Error Logging: Log detailed information about failed operations for troubleshooting.

  7. Progress Tracking: For large batches, implement progress tracking to provide feedback to users.

Error Handling

When performing bulk operations, you should implement robust error handling:

// Example of robust error handling for bulk operations
async function bulkOperationWithErrorHandling(operations) {
  const results = {
    successful: [],
    failed: [],
    total: operations.length
  };
  
  for (const operation of operations) {
    try {
      // Perform the operation (create, update, delete)
      const result = await performSingleOperation(operation);
      results.successful.push({
        operation,
        result
      });
    } catch (error) {
      results.failed.push({
        operation,
        error: error.message
      });
      
      // Log the error for debugging
      console.error(`Operation failed for ${JSON.stringify(operation)}:`, error);
    }
  }
  
  return {
    success: results.failed.length === 0,
    successCount: results.successful.length,
    failureCount: results.failed.length,
    successful: results.successful,
    failed: results.failed
  };
}

Conclusion

While the AutoElite API doesn't provide native bulk operation endpoints, you can implement efficient client-side batching using the techniques demonstrated in this guide. By using Promise.all in JavaScript or ThreadPoolExecutor in Python, you can perform multiple operations in parallel, significantly improving performance for bulk operations.

Remember to follow the best practices outlined above to ensure reliable and efficient bulk operations with the AutoElite API.