Overview

The SG Cars Trends API provides powerful filtering capabilities to help you extract specific data subsets. This guide covers all available filtering options and best practices.

Basic Filtering

Month Filtering

Filter data by specific months using the month parameter in YYYY-MM format:

curl "https://api.sgcarstrends.com/v1/cars?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Make Filtering

Filter by specific car manufacturers:

curl "https://api.sgcarstrends.com/v1/cars?make=Toyota" \
  -H "Authorization: Bearer YOUR_API_KEY"

Advanced Filtering

Multiple Parameters

Combine multiple filters for precise data extraction:

curl "https://api.sgcarstrends.com/v1/cars?month=2024-01&make=Toyota&fuel_type=Hybrid" \
  -H "Authorization: Bearer YOUR_API_KEY"

Date Range Filtering

Use from and to parameters for date range queries (available on COE endpoints):

curl "https://api.sgcarstrends.com/v1/coe?from=2024-01&to=2024-06" \
  -H "Authorization: Bearer YOUR_API_KEY"

Fuel Type Filtering

Available Fuel Types

Petrol

Traditional gasoline vehicles

Diesel

Diesel-powered vehicles

Electric

Battery electric vehicles (BEV)

Hybrid

Petrol-electric hybrid vehicles

Others

Alternative fuel types

Filter by Fuel Type

curl "https://api.sgcarstrends.com/v1/cars?fuel_type=Electric" \
  -H "Authorization: Bearer YOUR_API_KEY"

Dedicated Fuel Type Endpoints

Use specific endpoints for fuel type data:

# Get all electric vehicle data
curl "https://api.sgcarstrends.com/v1/cars/fuel-types/Electric" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Get electric vehicle data for specific month
curl "https://api.sgcarstrends.com/v1/cars/fuel-types/Electric?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Vehicle Type Filtering

Available Vehicle Types

Passenger Cars

Standard passenger vehicles

Goods & Other Vehicles

Commercial and utility vehicles

Motorcycles & Scooters

Two-wheeled vehicles

Buses

Public and private buses

Taxis

Licensed taxi vehicles

Rental Cars

Car rental fleet vehicles

Filter by Vehicle Type

curl "https://api.sgcarstrends.com/v1/cars?vehicle_type=Passenger Cars" \
  -H "Authorization: Bearer YOUR_API_KEY"

Dedicated Vehicle Type Endpoints

# Get all passenger car data
curl "https://api.sgcarstrends.com/v1/cars/vehicle-types/Passenger Cars" \
  -H "Authorization: Bearer YOUR_API_KEY"

# URL encode spaces in vehicle type
curl "https://api.sgcarstrends.com/v1/cars/vehicle-types/Passenger%20Cars?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Make-Specific Filtering

Filter by Manufacturer

curl "https://api.sgcarstrends.com/v1/cars/makes/Toyota" \
  -H "Authorization: Bearer YOUR_API_KEY"

Get Available Makes

First, get the list of available manufacturers:

curl "https://api.sgcarstrends.com/v1/cars/makes" \
  -H "Authorization: Bearer YOUR_API_KEY"

Pagination and Limits

Basic Pagination

# Get first page (default)
curl "https://api.sgcarstrends.com/v1/cars?page=1&limit=20" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Get second page
curl "https://api.sgcarstrends.com/v1/cars?page=2&limit=20" \
  -H "Authorization: Bearer YOUR_API_KEY"

Pagination with Filters

// Paginate through filtered results
async function getPaginatedFilteredData(filters, page = 1, limit = 20) {
  const params = new URLSearchParams({
    ...filters,
    page: page.toString(),
    limit: limit.toString()
  });
  
  const response = await fetch(`https://api.sgcarstrends.com/v1/cars?${params}`, {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });
  
  return await response.json();
}

// Example usage
const filters = {
  month: '2024-01',
  fuel_type: 'Electric'
};

const results = await getPaginatedFilteredData(filters, 1, 10);

Common Filtering Patterns

1. Monthly Analysis

Get comprehensive data for a specific month:

async function getMonthlyAnalysis(month) {
  const [cars, coe] = await Promise.all([
    fetch(`https://api.sgcarstrends.com/v1/cars?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    fetch(`https://api.sgcarstrends.com/v1/coe?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json())
  ]);
  
  return { cars: cars.data, coe: coe.data };
}

const analysis = await getMonthlyAnalysis('2024-01');

Track electric vehicle adoption over time:

async function getElectricVehicleTrends() {
  const months = ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'];
  
  const trends = await Promise.all(
    months.map(async (month) => {
      const response = await fetch(`https://api.sgcarstrends.com/v1/cars/fuel-types/Electric?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      });
      const data = await response.json();
      return {
        month,
        total: data.data.reduce((sum, item) => sum + item.number, 0)
      };
    })
  );
  
  return trends;
}

const evTrends = await getElectricVehicleTrends();

3. Manufacturer Comparison

Compare different manufacturers for a specific month:

async function compareManufacturers(month, makes) {
  const comparisons = await Promise.all(
    makes.map(async (make) => {
      const response = await fetch(`https://api.sgcarstrends.com/v1/cars/makes/${make}?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      });
      const data = await response.json();
      return {
        make,
        total: data.data.reduce((sum, item) => sum + item.number, 0)
      };
    })
  );
  
  return comparisons.sort((a, b) => b.total - a.total);
}

const comparison = await compareManufacturers('2024-01', ['Toyota', 'Honda', 'BMW']);

Best Practices

1. URL Encoding

Always URL encode parameters with special characters:

// Correct way to handle spaces and special characters
const vehicleType = 'Passenger Cars';
const encodedType = encodeURIComponent(vehicleType);
const url = `https://api.sgcarstrends.com/v1/cars/vehicle-types/${encodedType}`;

2. Parameter Validation

Validate parameters before making requests:

function validateMonth(month) {
  const monthPattern = /^\d{4}-\d{2}$/;
  return monthPattern.test(month);
}

function validateFuelType(fuelType) {
  const validTypes = ['Petrol', 'Diesel', 'Electric', 'Hybrid', 'Others'];
  return validTypes.includes(fuelType);
}

// Usage
const month = '2024-01';
const fuelType = 'Electric';

if (validateMonth(month) && validateFuelType(fuelType)) {
  // Make API request
}

3. Error Handling

Handle filtering errors gracefully:

async function safeApiCall(url, params = {}) {
  try {
    const queryString = new URLSearchParams(params).toString();
    const fullUrl = queryString ? `${url}?${queryString}` : url;
    
    const response = await fetch(fullUrl, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    
    if (!data.success) {
      throw new Error(data.error || 'API request failed');
    }
    
    return data;
  } catch (error) {
    console.error('API call failed:', error.message);
    throw error;
  }
}

// Usage
try {
  const data = await safeApiCall('https://api.sgcarstrends.com/v1/cars', {
    month: '2024-01',
    fuel_type: 'Electric'
  });
  console.log(data);
} catch (error) {
  console.error('Failed to fetch data:', error.message);
}

Next Steps

Overview

The SG Cars Trends API provides powerful filtering capabilities to help you extract specific data subsets. This guide covers all available filtering options and best practices.

Basic Filtering

Month Filtering

Filter data by specific months using the month parameter in YYYY-MM format:

curl "https://api.sgcarstrends.com/v1/cars?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Make Filtering

Filter by specific car manufacturers:

curl "https://api.sgcarstrends.com/v1/cars?make=Toyota" \
  -H "Authorization: Bearer YOUR_API_KEY"

Advanced Filtering

Multiple Parameters

Combine multiple filters for precise data extraction:

curl "https://api.sgcarstrends.com/v1/cars?month=2024-01&make=Toyota&fuel_type=Hybrid" \
  -H "Authorization: Bearer YOUR_API_KEY"

Date Range Filtering

Use from and to parameters for date range queries (available on COE endpoints):

curl "https://api.sgcarstrends.com/v1/coe?from=2024-01&to=2024-06" \
  -H "Authorization: Bearer YOUR_API_KEY"

Fuel Type Filtering

Available Fuel Types

Petrol

Traditional gasoline vehicles

Diesel

Diesel-powered vehicles

Electric

Battery electric vehicles (BEV)

Hybrid

Petrol-electric hybrid vehicles

Others

Alternative fuel types

Filter by Fuel Type

curl "https://api.sgcarstrends.com/v1/cars?fuel_type=Electric" \
  -H "Authorization: Bearer YOUR_API_KEY"

Dedicated Fuel Type Endpoints

Use specific endpoints for fuel type data:

# Get all electric vehicle data
curl "https://api.sgcarstrends.com/v1/cars/fuel-types/Electric" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Get electric vehicle data for specific month
curl "https://api.sgcarstrends.com/v1/cars/fuel-types/Electric?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Vehicle Type Filtering

Available Vehicle Types

Passenger Cars

Standard passenger vehicles

Goods & Other Vehicles

Commercial and utility vehicles

Motorcycles & Scooters

Two-wheeled vehicles

Buses

Public and private buses

Taxis

Licensed taxi vehicles

Rental Cars

Car rental fleet vehicles

Filter by Vehicle Type

curl "https://api.sgcarstrends.com/v1/cars?vehicle_type=Passenger Cars" \
  -H "Authorization: Bearer YOUR_API_KEY"

Dedicated Vehicle Type Endpoints

# Get all passenger car data
curl "https://api.sgcarstrends.com/v1/cars/vehicle-types/Passenger Cars" \
  -H "Authorization: Bearer YOUR_API_KEY"

# URL encode spaces in vehicle type
curl "https://api.sgcarstrends.com/v1/cars/vehicle-types/Passenger%20Cars?month=2024-01" \
  -H "Authorization: Bearer YOUR_API_KEY"

Make-Specific Filtering

Filter by Manufacturer

curl "https://api.sgcarstrends.com/v1/cars/makes/Toyota" \
  -H "Authorization: Bearer YOUR_API_KEY"

Get Available Makes

First, get the list of available manufacturers:

curl "https://api.sgcarstrends.com/v1/cars/makes" \
  -H "Authorization: Bearer YOUR_API_KEY"

Pagination and Limits

Basic Pagination

# Get first page (default)
curl "https://api.sgcarstrends.com/v1/cars?page=1&limit=20" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Get second page
curl "https://api.sgcarstrends.com/v1/cars?page=2&limit=20" \
  -H "Authorization: Bearer YOUR_API_KEY"

Pagination with Filters

// Paginate through filtered results
async function getPaginatedFilteredData(filters, page = 1, limit = 20) {
  const params = new URLSearchParams({
    ...filters,
    page: page.toString(),
    limit: limit.toString()
  });
  
  const response = await fetch(`https://api.sgcarstrends.com/v1/cars?${params}`, {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });
  
  return await response.json();
}

// Example usage
const filters = {
  month: '2024-01',
  fuel_type: 'Electric'
};

const results = await getPaginatedFilteredData(filters, 1, 10);

Common Filtering Patterns

1. Monthly Analysis

Get comprehensive data for a specific month:

async function getMonthlyAnalysis(month) {
  const [cars, coe] = await Promise.all([
    fetch(`https://api.sgcarstrends.com/v1/cars?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json()),
    fetch(`https://api.sgcarstrends.com/v1/coe?month=${month}`, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }).then(r => r.json())
  ]);
  
  return { cars: cars.data, coe: coe.data };
}

const analysis = await getMonthlyAnalysis('2024-01');

Track electric vehicle adoption over time:

async function getElectricVehicleTrends() {
  const months = ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06'];
  
  const trends = await Promise.all(
    months.map(async (month) => {
      const response = await fetch(`https://api.sgcarstrends.com/v1/cars/fuel-types/Electric?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      });
      const data = await response.json();
      return {
        month,
        total: data.data.reduce((sum, item) => sum + item.number, 0)
      };
    })
  );
  
  return trends;
}

const evTrends = await getElectricVehicleTrends();

3. Manufacturer Comparison

Compare different manufacturers for a specific month:

async function compareManufacturers(month, makes) {
  const comparisons = await Promise.all(
    makes.map(async (make) => {
      const response = await fetch(`https://api.sgcarstrends.com/v1/cars/makes/${make}?month=${month}`, {
        headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
      });
      const data = await response.json();
      return {
        make,
        total: data.data.reduce((sum, item) => sum + item.number, 0)
      };
    })
  );
  
  return comparisons.sort((a, b) => b.total - a.total);
}

const comparison = await compareManufacturers('2024-01', ['Toyota', 'Honda', 'BMW']);

Best Practices

1. URL Encoding

Always URL encode parameters with special characters:

// Correct way to handle spaces and special characters
const vehicleType = 'Passenger Cars';
const encodedType = encodeURIComponent(vehicleType);
const url = `https://api.sgcarstrends.com/v1/cars/vehicle-types/${encodedType}`;

2. Parameter Validation

Validate parameters before making requests:

function validateMonth(month) {
  const monthPattern = /^\d{4}-\d{2}$/;
  return monthPattern.test(month);
}

function validateFuelType(fuelType) {
  const validTypes = ['Petrol', 'Diesel', 'Electric', 'Hybrid', 'Others'];
  return validTypes.includes(fuelType);
}

// Usage
const month = '2024-01';
const fuelType = 'Electric';

if (validateMonth(month) && validateFuelType(fuelType)) {
  // Make API request
}

3. Error Handling

Handle filtering errors gracefully:

async function safeApiCall(url, params = {}) {
  try {
    const queryString = new URLSearchParams(params).toString();
    const fullUrl = queryString ? `${url}?${queryString}` : url;
    
    const response = await fetch(fullUrl, {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    
    if (!data.success) {
      throw new Error(data.error || 'API request failed');
    }
    
    return data;
  } catch (error) {
    console.error('API call failed:', error.message);
    throw error;
  }
}

// Usage
try {
  const data = await safeApiCall('https://api.sgcarstrends.com/v1/cars', {
    month: '2024-01',
    fuel_type: 'Electric'
  });
  console.log(data);
} catch (error) {
  console.error('Failed to fetch data:', error.message);
}

Next Steps