Skip to main content
GET
https://api.dcycle.io
/
api
/
v1
/
vehicle_consumptions
/
vehicle
/
{vehicle_id}
List Vehicle Consumptions
const options = {
  method: 'GET',
  headers: {
    'x-api-key': '<x-api-key>',
    'x-organization-id': '<x-organization-id>',
    'x-user-id': '<x-user-id>'
  }
};

fetch('https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}', options)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err));
{
  "page": 123,
  "size": 123,
  "total": 123,
  "total_error": 123,
  "items": [
    {
      "id": "<string>",
      "vehicle_id": "<string>",
      "quantity": 123,
      "unit_id": "<string>",
      "unit": {},
      "start_date": {},
      "end_date": {},
      "co2e": 123,
      "co2e_consumption": 123,
      "co2e_generation": 123,
      "status": "<string>",
      "custom_id": "<string>",
      "created_at": {},
      "updated_at": {}
    }
  ]
}

List Vehicle Consumptions

Retrieve all fuel consumption records for a specific vehicle with pagination support. Vehicle consumptions track fuel usage over time and automatically calculate CO2e emissions based on fuel type and quantity.
Vehicle consumptions represent Scope 1 emissions from mobile combustion. These are typically tracked via fuel purchases, mileage logs, or telematics systems.

Request

Headers

x-api-key
string
required
Your API key for authenticationExample: sk_live_1234567890abcdef
x-organization-id
string
required
Your organization UUIDExample: ff4adcc7-8172-45fe-9cf1-e90a6de53aa9
x-user-id
string
required
Your user UUIDExample: a1b2c3d4-e5f6-7890-abcd-ef1234567890

Path Parameters

vehicle_id
string
required
UUID of the vehicle to retrieve consumptions forExample: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"

Query Parameters

page
integer
default:"1"
Page number for paginationExample: 1
size
integer
default:"50"
Number of items per page (max: 100)Example: 50
filter_by
string
Advanced filtering criteria (format: field:operator:value)Supported operators:
  • eq - Equals
  • neq - Not equals
  • gt - Greater than
  • gte - Greater than or equal
  • lt - Less than
  • lte - Less than or equal
Example: "status:active"
sort_by
string
Sort criteria (format: field:asc or field:desc)Sortable fields:
  • start_date
  • end_date
  • quantity
  • co2e
Example: "start_date:desc"
start_date
integer
Filter by start date (Unix timestamp in seconds)Example: 1704067200 (January 1, 2024)
end_date
integer
Filter by end date (Unix timestamp in seconds)Example: 1735689600 (January 1, 2025)

Response

page
integer
Current page number
size
integer
Number of items per page
total
integer
Total count of consumption records
total_error
integer
Total count of consumption records with errors
items
array
Array of consumption objects

Consumption Object Fields:

id
string
Unique consumption record identifier (UUID v4)
vehicle_id
string
Vehicle UUID this consumption belongs to
quantity
float
Fuel quantity consumed
unit_id
string
Unit UUID for the quantity
unit
object
Unit details object with id, name, type fieldsCommon units: L (liters), kWh (kilowatt-hours), kg (kilograms)
start_date
datetime
Consumption period start date (ISO 8601 format)
end_date
datetime
Consumption period end date (ISO 8601 format)
co2e
float
Total CO2 equivalent emissions in kg
co2e_consumption
float
CO2e from fuel consumption (tank-to-wheel emissions)
co2e_generation
float
CO2e from fuel production (well-to-tank emissions)
status
string
Consumption record statusValues:
  • active - Successfully processed
  • error - Processing failed
  • pending - Awaiting processing
custom_id
string
External reference ID (e.g., from fuel card system, invoice number)
created_at
datetime
Record creation timestamp
updated_at
datetime
Last update timestamp

Example

curl -X GET "https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/a1b2c3d4-e5f6-7890-abcd-ef1234567890?page=1&size=50" \
  -H "Authorization: Bearer ${DCYCLE_API_KEY}" \
  -H "x-organization-id: ${DCYCLE_ORG_ID}" \
  -H "x-user-id: ${DCYCLE_USER_ID}"

Successful Response

{
  "page": 1,
  "size": 50,
  "total": 156,
  "total_error": 2,
  "items": [
    {
      "id": "cons-uuid-1",
      "vehicle_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "quantity": 45.5,
      "unit_id": "liter-unit-uuid",
      "unit": {
        "id": "liter-unit-uuid",
        "name": "L",
        "type": "liquid"
      },
      "start_date": "2024-01-15T00:00:00Z",
      "end_date": "2024-01-15T23:59:59Z",
      "co2e": 115.83,
      "co2e_consumption": 103.74,
      "co2e_generation": 12.09,
      "status": "active",
      "custom_id": "INV-2024-001",
      "created_at": "2024-01-16T10:30:00Z",
      "updated_at": "2024-01-16T10:30:00Z"
    },
    {
      "id": "cons-uuid-2",
      "vehicle_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "quantity": 52.0,
      "unit_id": "liter-unit-uuid",
      "unit": {
        "id": "liter-unit-uuid",
        "name": "L",
        "type": "liquid"
      },
      "start_date": "2024-01-10T00:00:00Z",
      "end_date": "2024-01-10T23:59:59Z",
      "co2e": 132.40,
      "co2e_consumption": 118.56,
      "co2e_generation": 13.84,
      "status": "active",
      "custom_id": "INV-2024-002",
      "created_at": "2024-01-11T09:15:00Z",
      "updated_at": "2024-01-11T09:15:00Z"
    }
  ]
}

Common Errors

400 Bad Request

Cause: Invalid query parameters or filter format
{
  "detail": "Invalid filter format",
  "code": "VALIDATION_ERROR"
}
Solution: Verify that filter_by and sort_by follow the correct format.

403 Forbidden

Cause: Organization ID doesn’t match your API key or user doesn’t belong to organization
{
  "detail": "Not authorized",
  "code": "FORBIDDEN"
}
Solution: Verify that x-organization-id matches your API key’s organization.

404 Not Found

Cause: Vehicle ID doesn’t exist or doesn’t belong to your organization
{
  "detail": "Vehicle not found",
  "code": "NOT_FOUND"
}
Solution: Verify the vehicle_id exists using the List Vehicles endpoint.

Use Cases

Get Vehicle Fuel History

Display fuel consumption history for a vehicle:
def get_vehicle_fuel_history(vehicle_id, months=12):
    """Get fuel consumption history for last N months"""

    from datetime import datetime, timedelta

    # Calculate date range
    end_date = int(datetime.now().timestamp())
    start_date = int((datetime.now() - timedelta(days=30*months)).timestamp())

    # Get all consumptions in date range
    all_consumptions = []
    page = 1

    while True:
        response = requests.get(
            f"https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}",
            headers=headers,
            params={
                "page": page,
                "size": 100,
                "start_date": start_date,
                "end_date": end_date,
                "sort_by": "start_date:asc"
            }
        )

        data = response.json()
        all_consumptions.extend(data['items'])

        if len(all_consumptions) >= data['total']:
            break

        page += 1

    # Group by month
    from collections import defaultdict
    monthly_data = defaultdict(lambda: {'fuel': 0, 'emissions': 0})

    for consumption in all_consumptions:
        month = consumption['start_date'][:7]  # YYYY-MM
        monthly_data[month]['fuel'] += consumption['quantity']
        monthly_data[month]['emissions'] += consumption['co2e']

    # Display
    print(f"Fuel History for Vehicle {vehicle_id} (Last {months} months):")
    print("-" * 60)
    for month in sorted(monthly_data.keys()):
        data = monthly_data[month]
        print(f"{month}: {data['fuel']:.2f} L, {data['emissions']:.2f} kg CO2e")

    return monthly_data

# Usage
history = get_vehicle_fuel_history("vehicle-uuid", months=12)

Calculate Average Consumption

Calculate average fuel consumption and emissions:
def calculate_vehicle_averages(vehicle_id):
    """Calculate average consumption metrics"""

    # Get all consumptions
    response = requests.get(
        f"https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}",
        headers=headers,
        params={"page": 1, "size": 1000}  # Adjust size as needed
    )

    consumptions = response.json()['items']

    if not consumptions:
        print("No consumption records found")
        return None

    # Calculate averages
    total_fuel = sum(c['quantity'] for c in consumptions)
    total_emissions = sum(c['co2e'] for c in consumptions)
    count = len(consumptions)

    avg_fuel_per_record = total_fuel / count
    avg_emissions_per_record = total_emissions / count
    avg_emission_factor = total_emissions / total_fuel  # kg CO2e per liter

    print(f"Vehicle Consumption Averages:")
    print(f"  Total records: {count}")
    print(f"  Total fuel: {total_fuel:.2f} L")
    print(f"  Total emissions: {total_emissions:.2f} kg CO2e")
    print(f"  Avg fuel per record: {avg_fuel_per_record:.2f} L")
    print(f"  Avg emissions per record: {avg_emissions_per_record:.2f} kg CO2e")
    print(f"  Emission factor: {avg_emission_factor:.4f} kg CO2e/L")

    return {
        'total_fuel': total_fuel,
        'total_emissions': total_emissions,
        'average_fuel': avg_fuel_per_record,
        'average_emissions': avg_emissions_per_record,
        'emission_factor': avg_emission_factor
    }

# Usage
averages = calculate_vehicle_averages("vehicle-uuid")

Filter by Date Range

Get consumptions for a specific period:
from datetime import datetime

def get_consumptions_for_period(vehicle_id, start_date_str, end_date_str):
    """Get consumptions for a specific date range"""

    # Convert dates to Unix timestamps
    start_date = int(datetime.strptime(start_date_str, "%Y-%m-%d").timestamp())
    end_date = int(datetime.strptime(end_date_str, "%Y-%m-%d").timestamp())

    response = requests.get(
        f"https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}",
        headers=headers,
        params={
            "start_date": start_date,
            "end_date": end_date,
            "size": 100
        }
    )

    consumptions = response.json()

    print(f"Consumptions from {start_date_str} to {end_date_str}:")
    print(f"  Records: {consumptions['total']}")

    total_fuel = sum(c['quantity'] for c in consumptions['items'])
    total_emissions = sum(c['co2e'] for c in consumptions['items'])

    print(f"  Total fuel: {total_fuel:.2f} L")
    print(f"  Total emissions: {total_emissions:.2f} kg CO2e")

    return consumptions

# Usage: Get Q1 2024 consumptions
q1_consumptions = get_consumptions_for_period(
    "vehicle-uuid",
    "2024-01-01",
    "2024-03-31"
)

Identify Consumption Errors

Find and review consumption records with errors:
def get_error_consumptions(vehicle_id):
    """Get consumption records with errors"""

    response = requests.get(
        f"https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}",
        headers=headers,
        params={
            "filter_by": "status:eqerror",
            "size": 100
        }
    )

    consumptions = response.json()

    if consumptions['total'] > 0:
        print(f"⚠️ {consumptions['total']} consumption records with errors:")

        for consumption in consumptions['items']:
            print(f"\nConsumption ID: {consumption['id']}")
            print(f"  Date: {consumption['start_date'][:10]}")
            print(f"  Quantity: {consumption['quantity']} {consumption['unit']['name']}")
            print(f"  Status: {consumption['status']}")
            if consumption.get('custom_id'):
                print(f"  Reference: {consumption['custom_id']}")
    else:
        print("✅ No consumption errors found")

    return consumptions

# Usage
errors = get_error_consumptions("vehicle-uuid")

Compare Vehicles Fuel Efficiency

Compare consumption patterns across multiple vehicles:
def compare_vehicles_efficiency(vehicle_ids):
    """Compare fuel efficiency across vehicles"""

    comparison = []

    for vehicle_id in vehicle_ids:
        # Get vehicle details
        vehicle_response = requests.get(
            "https://api.dcycle.io/api/v1/vehicles",
            headers=headers,
            params={"filter_by": f"id:eq{vehicle_id}"}
        )
        vehicle = vehicle_response.json()['items'][0]

        # Get consumptions
        consumption_response = requests.get(
            f"https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}",
            headers=headers,
            params={"size": 1000}
        )
        consumptions = consumption_response.json()['items']

        if consumptions:
            total_fuel = sum(c['quantity'] for c in consumptions)
            total_emissions = sum(c['co2e'] for c in consumptions)
            emission_factor = total_emissions / total_fuel if total_fuel > 0 else 0

            comparison.append({
                'vehicle_id': vehicle_id,
                'name': vehicle.get('name', 'Unknown'),
                'license_plate': vehicle.get('license_plate', 'N/A'),
                'total_fuel': total_fuel,
                'total_emissions': total_emissions,
                'emission_factor': emission_factor
            })

    # Sort by emissions (highest first)
    comparison.sort(key=lambda x: x['total_emissions'], reverse=True)

    print("Vehicle Efficiency Comparison:")
    print("-" * 80)
    for v in comparison:
        print(f"{v['name']} ({v['license_plate']})")
        print(f"  Fuel: {v['total_fuel']:.2f} L")
        print(f"  Emissions: {v['total_emissions']:.2f} kg CO2e")
        print(f"  Efficiency: {v['emission_factor']:.4f} kg CO2e/L")
        print()

    return comparison

# Usage
comparison = compare_vehicles_efficiency([
    "vehicle-uuid-1",
    "vehicle-uuid-2",
    "vehicle-uuid-3"
])

Emission Calculations

Well-to-Wheel (WTW) Methodology

Vehicle consumption emissions are calculated using Well-to-Wheel methodology: Total CO2e = Tank-to-Wheel (TTW) + Well-to-Tank (WTT)
  • Tank-to-Wheel (co2e_consumption): Direct emissions from fuel combustion in the vehicle
  • Well-to-Tank (co2e_generation): Upstream emissions from fuel extraction, refining, and distribution

Emission Factors

Emission factors vary by:
  • Fuel type: Diesel, gasoline, electric, CNG, etc.
  • Vehicle type: Passenger car, light commercial, truck, etc.
  • Country: Regional fuel standards and electricity grid mix
  • Year: Factors updated annually based on latest data
Electric vehicles show emissions in co2e_generation (grid electricity production) while co2e_consumption is zero (no direct tailpipe emissions).

Best Practices

1. Use Pagination for Large Datasets

When a vehicle has many consumption records, paginate through results:
# Good - Paginate through all results
def get_all_consumptions(vehicle_id):
    all_consumptions = []
    page = 1

    while True:
        response = requests.get(
            f"https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}",
            headers=headers,
            params={"page": page, "size": 100}
        )

        data = response.json()
        all_consumptions.extend(data['items'])

        if len(all_consumptions) >= data['total']:
            break

        page += 1

    return all_consumptions

2. Use Date Filtering

Filter server-side instead of loading all data:
# Good - Server-side date filtering
response = requests.get(
    f"https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}",
    headers=headers,
    params={
        "start_date": start_timestamp,
        "end_date": end_timestamp
    }
)

# Bad - Load everything and filter client-side
all_consumptions = get_all_consumptions(vehicle_id)
filtered = [c for c in all_consumptions if start <= c['start_date'] <= end]

3. Monitor Error Status

Regularly check for consumption records with errors:
# Check error count
response = requests.get(
    f"https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}",
    headers=headers,
    params={"page": 1, "size": 1}
)

error_count = response.json()['total_error']
if error_count > 0:
    print(f"⚠️ {error_count} consumption records need attention")

4. Track by Custom ID

Use custom_id to link consumption records to external systems:
# Link to fuel card system
consumption_data = {
    "vehicle_id": vehicle_id,
    "quantity": 45.5,
    "unit_id": "liter-unit-uuid",
    "start_date": "2024-01-15",
    "end_date": "2024-01-15",
    "custom_id": "FUELCARD-INV-2024-001"  # External reference
}