API Code Examples

API Code Examples

This page provides examples of how to use the AutoElite API with different programming languages and frameworks.

Table of Contents

JavaScript/Node.js

Fetch Vehicles for a Dealer

const axios = require('axios');

// Configuration
const API_KEY = 'your-api-key-here';
const DEALER_ID = 1; // AutoPret 123
const API_URL = 'https://api.autoelite.io';

// Create API client
const apiClient = axios.create({
  baseURL: API_URL,
  headers: {
    'X-API-Key': API_KEY,
    'Content-Type': 'application/json'
  }
});

// Fetch vehicles for a specific dealer
async function getVehicles(dealerId) {
  try {
    const response = await apiClient.get(`/api/vehicles?dealer_id=${dealerId}`);
    
    console.log(`Found ${response.data.meta.total} vehicles`);
    
    // Process vehicles
    response.data.vehicles.forEach(vehicle => {
      console.log(`${vehicle.year} ${vehicle.make} ${vehicle.model} - $${vehicle.price}`);
    });
    
    return response.data.vehicles;
  } catch (error) {
    console.error('Error fetching vehicles:', error.response?.data || error.message);
    throw error;
  }
}

// Execute the function
getVehicles(DEALER_ID)
  .then(vehicles => console.log(`Successfully retrieved ${vehicles.length} vehicles`))
  .catch(err => console.error('Failed to get vehicles:', err));

Python

Fetch Vehicles for a Dealer

import requests
import json

# Configuration
API_KEY = "your-api-key-here"
DEALER_ID = 1  # AutoPret 123
API_URL = "https://api.autoelite.io"

# Headers for all requests
headers = {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json"
}

def get_vehicles(dealer_id):
    """Fetch vehicles for a specific dealer"""
    try:
        # Make the API request
        response = requests.get(
            f"{API_URL}/api/vehicles?dealer_id={dealer_id}",
            headers=headers
        )
        
        # Check if request was successful
        response.raise_for_status()
        
        # Parse the JSON response
        data = response.json()
        
        print(f"Found {data['meta']['total']} vehicles")
        
        # Process vehicles
        for vehicle in data["vehicles"]:
            print(f"{vehicle['year']} {vehicle['make']} {vehicle['model']} - ${vehicle['price']}")
        
        return data["vehicles"]
    
    except requests.exceptions.RequestException as e:
        print(f"Error fetching vehicles: {e}")
        if hasattr(e, 'response') and e.response:
            print(f"Response: {e.response.text}")
        raise

# Execute the function
if __name__ == "__main__":
    try:
        vehicles = get_vehicles(DEALER_ID)
        print(f"Successfully retrieved {len(vehicles)} vehicles")
    except Exception as e:
        print(f"Failed to get vehicles: {e}")

C#/.NET

Fetch Vehicles for a Dealer

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Text.Json;
using System.Collections.Generic;

namespace AutoEliteApiClient
{
    // Classes to deserialize the JSON response
    public class ApiResponse
    {
        public MetaData meta { get; set; }
        public List<Vehicle> vehicles { get; set; }
    }

    public class MetaData
    {
        public int total { get; set; }
        public bool filter_applied { get; set; }
        public int dealer_id { get; set; }
        public string timestamp { get; set; }
        public string sql { get; set; }
    }

    public class Vehicle
    {
        public int id { get; set; }
        public int dealer_id { get; set; }
        public string make { get; set; }
        public string model { get; set; }
        public int year { get; set; }
        public decimal price { get; set; }
        public int? mileage { get; set; }
        public string vin { get; set; }
        public string status { get; set; }
        // Additional properties omitted for brevity
    }

    public class ApiClient
    {
        private readonly HttpClient _client;
        private readonly string _baseUrl;

        public ApiClient(string apiKey, string baseUrl = "https://api.autoelite.io")
        {
            _baseUrl = baseUrl;
            _client = new HttpClient();
            _client.DefaultRequestHeaders.Add("X-API-Key", apiKey);
            _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public async Task<List<Vehicle>> GetVehiclesAsync(int dealerId)
        {
            try
            {
                var response = await _client.GetAsync($"{_baseUrl}/api/vehicles?dealer_id={dealerId}");
                response.EnsureSuccessStatusCode();
                
                var content = await response.Content.ReadAsStringAsync();
                var apiResponse = JsonSerializer.Deserialize<ApiResponse>(content, 
                    new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
                
                return apiResponse?.vehicles ?? new List<Vehicle>();
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"Error fetching vehicles: {ex.Message}");
                throw;
            }
        }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            // Configuration
            string apiKey = "your-api-key-here";
            int dealerId = 1; // AutoPret 123
            
            try
            {
                var apiClient = new ApiClient(apiKey);
                
                Console.WriteLine($"Fetching vehicles for dealer ID {dealerId}...");
                var vehicles = await apiClient.GetVehiclesAsync(dealerId);
                
                Console.WriteLine($"Found {vehicles.Count} vehicles:");
                foreach (var vehicle in vehicles)
                {
                    Console.WriteLine($"{vehicle.year} {vehicle.make} {vehicle.model} - ${vehicle.price:N0}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

PHP

Fetch Vehicles for a Dealer

<?php
// Configuration
$API_KEY = 'your-api-key-here';
$DEALER_ID = 1; // AutoPret 123
$API_URL = 'https://api.autoelite.io';

/**
 * Fetch vehicles for a specific dealer
 * 
 * @param int $dealerId The dealer ID to fetch vehicles for
 * @return array The vehicles data
 */
function getVehicles($dealerId) {
    global $API_KEY, $API_URL;
    
    // Initialize cURL session
    $ch = curl_init();
    
    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, "{$API_URL}/api/vehicles?dealer_id={$dealerId}");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "X-API-Key: {$API_KEY}",
        "Content-Type: application/json"
    ]);
    
    // Execute the request
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    // Check for errors
    if (curl_errno($ch)) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new Exception("cURL Error: {$error}");
    }
    
    curl_close($ch);
    
    // Check HTTP status code
    if ($httpCode !== 200) {
        throw new Exception("API Error: HTTP Status {$httpCode}, Response: {$response}");
    }
    
    // Parse JSON response
    $data = json_decode($response, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception("JSON Parsing Error: " . json_last_error_msg());
    }
    
    return $data;
}

// Execute the function
try {
    $result = getVehicles($DEALER_ID);
    
    echo "Found {$result['meta']['total']} vehicles\n";
    
    // Process vehicles
    foreach ($result['vehicles'] as $vehicle) {
        echo "{$vehicle['year']} {$vehicle['make']} {$vehicle['model']} - \${$vehicle['price']}\n";
    }
    
    echo "Successfully retrieved " . count($result['vehicles']) . " vehicles\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>

Java

Fetch Vehicles for a Dealer

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class AutoEliteApiClient {
    
    // Configuration
    private static final String API_KEY = "your-api-key-here";
    private static final int DEALER_ID = 1; // AutoPret 123
    private static final String API_URL = "https://api.autoelite.io";
    
    private final HttpClient httpClient;
    private final ObjectMapper objectMapper;
    
    public AutoEliteApiClient() {
        this.httpClient = HttpClient.newHttpClient();
        this.objectMapper = new ObjectMapper();
    }
    
    public List<Vehicle> getVehicles(int dealerId) throws IOException, InterruptedException {
        // Build the request
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(API_URL + "/api/vehicles?dealer_id=" + dealerId))
                .header("X-API-Key", API_KEY)
                .header("Content-Type", "application/json")
                .GET()
                .build();
        
        // Send the request
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        
        // Check response status
        if (response.statusCode() != 200) {
            throw new IOException("API Error: HTTP Status " + response.statusCode() + ", Response: " + response.body());
        }
        
        // Parse the JSON response
        Map<String, Object> data = objectMapper.readValue(response.body(), Map.class);
        Map<String, Object> meta = (Map<String, Object>) data.get("meta");
        List<Map<String, Object>> vehiclesData = (List<Map<String, Object>>) data.get("vehicles");
        
        // Convert to Vehicle objects
        List<Vehicle> vehicles = new ArrayList<>();
        for (Map<String, Object> vehicleData : vehiclesData) {
            Vehicle vehicle = new Vehicle();
            vehicle.id = ((Number) vehicleData.get("id")).intValue();
            vehicle.dealerId = ((Number) vehicleData.get("dealer_id")).intValue();
            vehicle.make = (String) vehicleData.get("make");
            vehicle.model = (String) vehicleData.get("model");
            vehicle.year = ((Number) vehicleData.get("year")).intValue();
            vehicle.price = ((Number) vehicleData.get("price")).doubleValue();
            vehicle.status = (String) vehicleData.get("status");
            
            vehicles.add(vehicle);
        }
        
        return vehicles;
    }
    
    // Vehicle class
    public static class Vehicle {
        public int id;
        public int dealerId;
        public String make;
        public String model;
        public int year;
        public double price;
        public String status;
        
        @Override
        public String toString() {
            return year + " " + make + " " + model + " - $" + (int) price;
        }
    }
    
    public static void main(String[] args) {
        try {
            AutoEliteApiClient client = new AutoEliteApiClient();
            
            System.out.println("Fetching vehicles for dealer ID " + DEALER_ID + "...");
            List<Vehicle> vehicles = client.getVehicles(DEALER_ID);
            
            System.out.println("Found " + vehicles.size() + " vehicles:");
            for (Vehicle vehicle : vehicles) {
                System.out.println(vehicle);
            }
            
            System.out.println("Successfully retrieved " + vehicles.size() + " vehicles");
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Ruby

Fetch Vehicles for a Dealer

require 'net/http'
require 'uri'
require 'json'

# Configuration
API_KEY = 'your-api-key-here'
DEALER_ID = 1 # AutoPret 123
API_URL = 'https://api.autoelite.io'

def get_vehicles(dealer_id)
  # Build the URI
  uri = URI("#{API_URL}/api/vehicles?dealer_id=#{dealer_id}")
  
  # Create the request
  request = Net::HTTP::Get.new(uri)
  request['X-API-Key'] = API_KEY
  request['Content-Type'] = 'application/json'
  
  # Send the request
  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
    http.request(request)
  end
  
  # Check response status
  unless response.is_a?(Net::HTTPSuccess)
    raise "API Error: HTTP Status #{response.code}, Response: #{response.body}"
  end
  
  # Parse the JSON response
  data = JSON.parse(response.body)
  
  puts "Found #{data['meta']['total']} vehicles"
  
  # Process vehicles
  data['vehicles'].each do |vehicle|
    puts "#{vehicle['year']} #{vehicle['make']} #{vehicle['model']} - $#{vehicle['price']}"
  end
  
  data['vehicles']
rescue => e
  puts "Error fetching vehicles: #{e.message}"
  raise
end

# Execute the function
begin
  vehicles = get_vehicles(DEALER_ID)
  puts "Successfully retrieved #{vehicles.length} vehicles"
rescue => e
  puts "Failed to get vehicles: #{e.message}"
end

Command Line (cURL)

Fetch Vehicles for a Dealer

# Configuration
API_KEY="your-api-key-here"
DEALER_ID=1  # AutoPret 123
API_URL="https://api.autoelite.io"

# Make the API request
curl -X GET "${API_URL}/api/vehicles?dealer_id=${DEALER_ID}" \
  -H "X-API-Key: ${API_KEY}" \
  -H "Content-Type: application/json" \
  | jq

Next Steps

For more detailed information about the API endpoints, request parameters, and response formats, please refer to the API Reference.

If you have any questions or need assistance with your integration, please contact our support team.