> ## Documentation Index
> Fetch the complete documentation index at: https://code.dcycle.io/llms.txt
> Use this file to discover all available pages before exploring further.

# List Vehicle Consumptions

> Get fuel consumption records for a specific vehicle

# 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.

<Note>
  Vehicle consumptions represent **Scope 1 emissions** from mobile combustion. These are typically tracked via fuel purchases, mileage logs, or telematics systems.
</Note>

## Request

### Headers

<ParamField header="x-api-key" type="string" required>
  Your API key for authentication

  **Example:** `sk_live_1234567890abcdef`
</ParamField>

<ParamField header="x-organization-id" type="string" required>
  Your organization UUID

  **Example:** `ff4adcc7-8172-45fe-9cf1-e90a6de53aa9`
</ParamField>

<ParamField header="x-user-id" type="string" required>
  Your user UUID

  **Example:** `a1b2c3d4-e5f6-7890-abcd-ef1234567890`
</ParamField>

### Path Parameters

<ParamField path="vehicle_id" type="string" required>
  UUID of the vehicle to retrieve consumptions for

  **Example:** `"a1b2c3d4-e5f6-7890-abcd-ef1234567890"`
</ParamField>

### Query Parameters

<ParamField query="page" type="integer" default="1">
  Page number for pagination

  **Example:** `1`
</ParamField>

<ParamField query="size" type="integer" default="50">
  Number of items per page (max: 100)

  **Example:** `50`
</ParamField>

<ParamField query="filter_by" type="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"`
</ParamField>

<ParamField query="sort_by" type="string">
  Sort criteria (format: `field:asc` or `field:desc`)

  **Sortable fields:**

  * `start_date`
  * `end_date`
  * `quantity`
  * `co2e`

  **Example:** `"start_date:desc"`
</ParamField>

<ParamField query="start_date" type="integer">
  Filter by start date (Unix timestamp in seconds)

  **Example:** `1704067200` (January 1, 2024)
</ParamField>

<ParamField query="end_date" type="integer">
  Filter by end date (Unix timestamp in seconds)

  **Example:** `1735689600` (January 1, 2025)
</ParamField>

## Response

<ResponseField name="page" type="integer">
  Current page number
</ResponseField>

<ResponseField name="size" type="integer">
  Number of items per page
</ResponseField>

<ResponseField name="total" type="integer">
  Total count of consumption records
</ResponseField>

<ResponseField name="total_error" type="integer">
  Total count of consumption records with errors
</ResponseField>

<ResponseField name="items" type="array">
  Array of consumption objects

  ### Consumption Object Fields:

  <ResponseField name="id" type="string">
    Unique consumption record identifier (UUID v4)
  </ResponseField>

  <ResponseField name="vehicle_id" type="string">
    Vehicle UUID this consumption belongs to
  </ResponseField>

  <ResponseField name="quantity" type="float">
    Fuel quantity consumed
  </ResponseField>

  <ResponseField name="unit_id" type="string">
    Unit UUID for the quantity
  </ResponseField>

  <ResponseField name="unit" type="object">
    Unit details object with `id`, `name`, `type` fields

    **Common units:** `L` (liters), `kWh` (kilowatt-hours), `kg` (kilograms)
  </ResponseField>

  <ResponseField name="start_date" type="datetime">
    Consumption period start date (ISO 8601 format)
  </ResponseField>

  <ResponseField name="end_date" type="datetime">
    Consumption period end date (ISO 8601 format)
  </ResponseField>

  <ResponseField name="co2e" type="float">
    Total CO2 equivalent emissions in kg
  </ResponseField>

  <ResponseField name="co2e_consumption" type="float" optional>
    CO2e from fuel consumption (tank-to-wheel emissions)
  </ResponseField>

  <ResponseField name="co2e_generation" type="float" optional>
    CO2e from fuel production (well-to-tank emissions)
  </ResponseField>

  <ResponseField name="status" type="string">
    Consumption record status

    **Values:**

    * `active` - Successfully processed
    * `error` - Processing failed
    * `pending` - Awaiting processing
  </ResponseField>

  <ResponseField name="custom_id" type="string" optional>
    External reference ID (e.g., from fuel card system, invoice number)
  </ResponseField>

  <ResponseField name="created_at" type="datetime">
    Record creation timestamp
  </ResponseField>

  <ResponseField name="updated_at" type="datetime">
    Last update timestamp
  </ResponseField>
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  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}"
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  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")
  ```

  ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  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));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "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

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "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

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "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

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "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:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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

<Info>
  Electric vehicles show emissions in `co2e_generation` (grid electricity production) while `co2e_consumption` is zero (no direct tailpipe emissions).
</Info>

## Best Practices

### 1. Use Pagination for Large Datasets

When a vehicle has many consumption records, paginate through results:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 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:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 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:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 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:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# 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

<CardGroup cols={2}>
  <Card title="Bulk Upload Consumptions" icon="upload" href="/api-docs/vehicle-consumptions/bulk-upload">
    Upload multiple consumption records via CSV
  </Card>

  <Card title="List Vehicles" icon="car" href="/api-docs/vehicles/list">
    View your vehicle fleet
  </Card>

  <Card title="List Vehicle Fuels" icon="gas-pump" href="/api-docs/vehicle-fuels/list">
    Get available vehicle fuels
  </Card>

  <Card title="Authentication" icon="key" href="/api-docs/authentication">
    Learn about API authentication
  </Card>
</CardGroup>
