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));import requests
url = "https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}"
headers = {
"x-api-key": "<x-api-key>",
"x-organization-id": "<x-organization-id>",
"x-user-id": "<x-user-id>"
}
response = requests.get(url, headers=headers)
print(response.text)curl --request GET \
--url https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id} \
--header 'x-api-key: <x-api-key>' \
--header 'x-organization-id: <x-organization-id>' \
--header 'x-user-id: <x-user-id>'{
"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
Get fuel consumption records for a specific vehicle
GET
/
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));import requests
url = "https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}"
headers = {
"x-api-key": "<x-api-key>",
"x-organization-id": "<x-organization-id>",
"x-user-id": "<x-user-id>"
}
response = requests.get(url, headers=headers)
print(response.text)curl --request GET \
--url https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id} \
--header 'x-api-key: <x-api-key>' \
--header 'x-organization-id: <x-organization-id>' \
--header 'x-user-id: <x-user-id>'{
"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
string
required
Your API key for authenticationExample:
sk_live_1234567890abcdefstring
required
Your organization UUIDExample:
ff4adcc7-8172-45fe-9cf1-e90a6de53aa9string
required
Your user UUIDExample:
a1b2c3d4-e5f6-7890-abcd-ef1234567890Path Parameters
string
required
UUID of the vehicle to retrieve consumptions forExample:
"a1b2c3d4-e5f6-7890-abcd-ef1234567890"Query Parameters
integer
default:"1"
Page number for paginationExample:
1integer
default:"50"
Number of items per page (max: 100)Example:
50string
Advanced filtering criteria (format:
field:operator:value)Supported operators:eq- Equalsneq- Not equalsgt- Greater thangte- Greater than or equallt- Less thanlte- Less than or equal
"status:active"string
Sort criteria (format:
field:asc or field:desc)Sortable fields:start_dateend_datequantityco2e
"start_date:desc"integer
Filter by start date (Unix timestamp in seconds)Example:
1704067200 (January 1, 2024)integer
Filter by end date (Unix timestamp in seconds)Example:
1735689600 (January 1, 2025)Response
integer
Current page number
integer
Number of items per page
integer
Total count of consumption records
integer
Total count of consumption records with errors
array
Array of consumption objects
Consumption Object Fields:
string
Unique consumption record identifier (UUID v4)
string
Vehicle UUID this consumption belongs to
float
Fuel quantity consumed
string
Unit UUID for the quantity
object
Unit details object with
id, name, type fieldsCommon units: L (liters), kWh (kilowatt-hours), kg (kilograms)datetime
Consumption period start date (ISO 8601 format)
datetime
Consumption period end date (ISO 8601 format)
float
Total CO2 equivalent emissions in kg
float
CO2e from fuel consumption (tank-to-wheel emissions)
float
CO2e from fuel production (well-to-tank emissions)
string
Consumption record statusValues:
active- Successfully processederror- Processing failedpending- Awaiting processing
string
External reference ID (e.g., from fuel card system, invoice number)
datetime
Record creation timestamp
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}"
import requests
import os
api_key = os.getenv("DCYCLE_API_KEY")
org_id = os.getenv("DCYCLE_ORG_ID")
user_id = os.getenv("DCYCLE_USER_ID")
headers = {
"Authorization": f"Bearer {api_key}",
"x-organization-id": org_id,
"x-user-id": user_id
}
vehicle_id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
# Get consumptions sorted by date (most recent first)
params = {
"page": 1,
"size": 50,
"sort_by": "start_date:desc"
}
response = requests.get(
f"https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/{vehicle_id}",
headers=headers,
params=params
)
consumptions = response.json()
print(f"Total consumption records: {consumptions['total']}")
print(f"Records with errors: {consumptions['total_error']}")
# Calculate totals
total_fuel = sum(c['quantity'] for c in consumptions['items'])
total_emissions = sum(c['co2e'] for c in consumptions['items'])
print(f"\nTotal fuel: {total_fuel:.2f} L")
print(f"Total emissions: {total_emissions:.2f} kg CO2e")
# Show recent consumptions
print("\nRecent consumptions:")
for consumption in consumptions['items'][:5]:
print(f" {consumption['start_date'][:10]}: {consumption['quantity']:.2f} {consumption['unit']['name']} = {consumption['co2e']:.2f} kg CO2e")
const axios = require('axios');
const apiKey = process.env.DCYCLE_API_KEY;
const orgId = process.env.DCYCLE_ORG_ID;
const userId = process.env.DCYCLE_USER_ID;
const headers = {
'Authorization': `Bearer ${apiKey}`,
'x-organization-id': orgId,
'x-user-id': userId
};
const vehicleId = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
// Get consumptions sorted by date (most recent first)
const params = {
page: 1,
size: 50,
sort_by: 'start_date:desc'
};
axios.get(
`https://api.dcycle.io/api/v1/vehicle_consumptions/vehicle/${vehicleId}`,
{ headers, params }
)
.then(response => {
const consumptions = response.data;
console.log(`Total consumption records: ${consumptions.total}`);
console.log(`Records with errors: ${consumptions.total_error}`);
// Calculate totals
const totalFuel = consumptions.items.reduce((sum, c) => sum + c.quantity, 0);
const totalEmissions = consumptions.items.reduce((sum, c) => sum + c.co2e, 0);
console.log(`\nTotal fuel: ${totalFuel.toFixed(2)} L`);
console.log(`Total emissions: ${totalEmissions.toFixed(2)} kg CO2e`);
// Show recent consumptions
console.log('\nRecent consumptions:');
consumptions.items.slice(0, 5).forEach(consumption => {
console.log(` ${consumption.start_date.substring(0, 10)}: ${consumption.quantity.toFixed(2)} ${consumption.unit.name} = ${consumption.co2e.toFixed(2)} kg CO2e`);
});
})
.catch(error => console.error(error));
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"
}
403 Forbidden
Cause: Organization ID doesn’t match your API key or user doesn’t belong to organization{
"detail": "Not authorized",
"code": "FORBIDDEN"
}
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"
}
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
Usecustom_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
}
Related Endpoints
Bulk Upload Consumptions
Upload multiple consumption records via CSV
List Vehicles
View your vehicle fleet
List Vehicle Fuels
Get available vehicle fuels
Authentication
Learn about API authentication
Was this page helpful?