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

# Vehicle Consumptions

> Retrieve consumption data and tracking for a specific vehicle

# Vehicle Consumptions

Get detailed consumption records for a specific vehicle. This endpoint returns paginated consumption data including status information about data processing and tracking.

<Note>
  **Consumption Tracking**: This endpoint retrieves consumption records linked to a vehicle, showing fuel usage, mileage, and processing status over time.
</Note>

## Request

### Path Parameters

<ParamField path="vehicle_id" type="uuid" required>
  The UUID of the vehicle

  **Example:** `550e8400-e29b-41d4-a716-446655440000`
</ParamField>

### 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:** `a8315ef3-dd50-43f8-b7ce-d839e68d51fa`
</ParamField>

### Query Parameters

<ParamField query="status[]" type="array[string]">
  Filter by consumption status

  **Available values:** `active`, `success`, `loading`, `error`

  **Example:** `status[]=success&status[]=active`
</ParamField>

<ParamField query="unit_id[]" type="array[uuid]">
  Filter by unit of measurement UUID

  **Example:** `unit_id[]=550e8400-e29b-41d4-a716-446655440000`
</ParamField>

<ParamField query="custom_id" type="string">
  Filter by custom identifier

  **Example:** `REF-2024-001`
</ParamField>

<ParamField query="start_date" type="date">
  Filter consumptions starting on or after this date (inclusive)

  **Format:** `YYYY-MM-DD`
</ParamField>

<ParamField query="end_date" type="date">
  Filter consumptions ending on or before this date (inclusive)

  **Format:** `YYYY-MM-DD`
</ParamField>

<ParamField query="file_id[]" type="array[uuid]">
  Filter by source file UUID. Pass `00000000-0000-0000-0000-000000000000` to filter for records with no file.

  **Example:** `file_id[]=3fa85f64-5717-4562-b3fc-2c963f66afa6`
</ParamField>

<ParamField query="created_at_from" type="datetime">
  Filter records created on or after this timestamp (inclusive)

  **Format:** `YYYY-MM-DDTHH:MM:SSZ`
</ParamField>

<ParamField query="created_at_to" type="datetime">
  Filter records created on or before this timestamp (inclusive)

  **Format:** `YYYY-MM-DDTHH:MM:SSZ`
</ParamField>

<ParamField query="co2e_status" type="string">
  Filter by CO2e calculation status

  **Available values:** `calculated`, `not_calculated`
</ParamField>

<ParamField query="sort" type="string">
  Field to sort by. Prefix with `-` for descending order. Unrecognized values fall back to the default order (`-created_at`).

  **Available values:** `custom_id`, `quantity`, `start_date`, `end_date`, `status`, `created_at`, `updated_at`, `base_total_spend`

  **Example:** `?sort=-start_date`
</ParamField>

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

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

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

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

## Response

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

  <Expandable title="Consumption Object">
    <ResponseField name="id" type="string">
      Unique identifier (UUID) for the consumption record
    </ResponseField>

    <ResponseField name="vehicle_id" type="string">
      UUID of the associated vehicle
    </ResponseField>

    <ResponseField name="status" type="string">
      Current status: `active`, `success`, `loading`, or `error`
    </ResponseField>

    <ResponseField name="data" type="object">
      Consumption data (structure varies by consumption type)
    </ResponseField>

    <ResponseField name="total_energy_kwh" type="float">
      Total energy consumption in kWh for the period. May be `null` if the energy calculation has not completed yet.
    </ResponseField>

    <ResponseField name="created_at" type="datetime">
      Timestamp when the consumption record was created
    </ResponseField>

    <ResponseField name="updated_at" type="datetime | null">
      Timestamp when the record was last updated
    </ResponseField>
  </Expandable>
</ResponseField>

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

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

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

<ResponseField name="filter_hash" type="string">
  16-character hex hash of the applied filters. Pass this to the [bulk delete by filters](/api-reference/vehicles/consumptions-bulk-delete-by-filters) endpoint to ensure consistency.
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET "https://api.dcycle.io/v1/vehicles/550e8400-e29b-41d4-a716-446655440000/consumptions?status=success&page=1&size=50" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_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")
  vehicle_id = "550e8400-e29b-41d4-a716-446655440000"

  headers = {
      "x-api-key": api_key,
      "x-organization-id": org_id
  }

  params = {
      "status": ["success"],
      "page": 1,
      "size": 50
  }

  response = requests.get(
      f"https://api.dcycle.io/v1/vehicles/{vehicle_id}/consumptions",
      headers=headers,
      params=params
  )

  result = response.json()
  for consumption in result["items"]:
      print(f"Consumption ID: {consumption['id']}, Status: {consumption['status']}")
      print(f"Created: {consumption['created_at']}")
  ```

  ```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 vehicleId = "550e8400-e29b-41d4-a716-446655440000";

  const headers = {
    'x-api-key': apiKey,
    'x-organization-id': orgId
  };

  const params = {
    status: ['success'],
    page: 1,
    size: 50
  };

  axios.get(
    `https://api.dcycle.io/v1/vehicles/${vehicleId}/consumptions`,
    { headers, params }
  )
  .then(response => {
    response.data.items.forEach(consumption => {
      console.log(`Consumption ID: ${consumption.id}, Status: ${consumption.status}`);
      console.log(`Created: ${consumption.created_at}`);
    });
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "items": [
    {
      "id": "660e8400-e29b-41d4-a716-446655440000",
      "vehicle_id": "550e8400-e29b-41d4-a716-446655440000",
      "status": "success",
      "data": {
        "fuel_consumed": 45.5,
        "distance_km": 450,
        "fuel_efficiency": 10.1,
        "period": "2024-11-01 to 2024-11-30"
      },
      "total_energy_kwh": 1500.00,
      "created_at": "2024-11-01T08:00:00Z",
      "updated_at": "2024-11-01T08:00:00Z"
    },
    {
      "id": "660e8400-e29b-41d4-a716-446655440001",
      "vehicle_id": "550e8400-e29b-41d4-a716-446655440000",
      "status": "success",
      "data": {
        "fuel_consumed": 52.3,
        "distance_km": 520,
        "fuel_efficiency": 9.9,
        "period": "2024-10-01 to 2024-10-31"
      },
      "created_at": "2024-10-01T08:00:00Z",
      "updated_at": "2024-10-01T08:00:00Z"
    }
  ],
  "total": 12,
  "page": 1,
  "size": 50,
  "filter_hash": "a1b2c3d4e5f67890"
}
```

## Consumption Status Reference

| Status      | Description                                              | Action                 |
| ----------- | -------------------------------------------------------- | ---------------------- |
| **active**  | Consumption record is currently active and being tracked | Monitor for completion |
| **success** | Consumption data has been successfully processed         | Data is ready to use   |
| **loading** | Consumption data is being processed                      | Wait for completion    |
| **error**   | An error occurred during processing                      | Review logs or retry   |

## Common Errors

### 401 Unauthorized

**Cause:** Missing or invalid API key

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Invalid API key",
  "code": "INVALID_API_KEY"
}
```

**Solution:** Verify your API key is valid and active. Get a new one from [Settings → API](https://app.dcycle.io/settings/api).

### 404 Not Found

**Cause:** Vehicle not found in organization

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "code": "VEHICLE_NOT_FOUND",
  "detail": "Vehicle with id=UUID('...') not found"
}
```

**Solution:** Verify that the vehicle ID is correct and belongs to your organization. Use the List Vehicles endpoint to get valid IDs.

### 422 Validation Error

**Cause:** Invalid query parameters

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": [
    {
      "loc": ["query", "status"],
      "msg": "value is not a valid enumeration member; permitted: 'active', 'success', 'loading', 'error'",
      "type": "type_error.enum"
    }
  ]
}
```

**Solution:** Check that status values are valid. Use only `active`, `success`, `loading`, or `error`.

## Use Cases

### Get Successful Consumption Records

Retrieve only successfully processed consumption data:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_successful_consumptions(vehicle_id):
    """Get all successfully processed consumption records"""
    response = requests.get(
        f"https://api.dcycle.io/v1/vehicles/{vehicle_id}/consumptions",
        headers=headers,
        params={"status": ["success"], "size": 100}
    )

    return response.json()["items"]

# Get consumptions
consumptions = get_successful_consumptions(
    "550e8400-e29b-41d4-a716-446655440000"
)

total_fuel = sum(c["data"]["fuel_consumed"] for c in consumptions)
total_distance = sum(c["data"]["distance_km"] for c in consumptions)

print(f"Total fuel: {total_fuel} liters")
print(f"Total distance: {total_distance} km")
print(f"Average efficiency: {total_distance / total_fuel:.2f} km/l")
```

### Monitor Consumption Processing

Track consumption records that are being processed:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def check_consumption_status(vehicle_id):
    """Check status of all consumption records"""
    response = requests.get(
        f"https://api.dcycle.io/v1/vehicles/{vehicle_id}/consumptions",
        headers=headers,
        params={"size": 100}
    )

    consumptions = response.json()["items"]
    status_summary = {
        "active": 0,
        "success": 0,
        "loading": 0,
        "error": 0
    }

    for consumption in consumptions:
        status = consumption["status"]
        status_summary[status] += 1

    return status_summary

# Check status
summary = check_consumption_status(
    "550e8400-e29b-41d4-a716-446655440000"
)

print("Consumption Status Summary:")
for status, count in summary.items():
    print(f"  {status}: {count}")
```

### Export Consumption Data

Export consumption records for analysis:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def export_consumption_data(vehicle_id):
    """Export all consumption data to CSV"""
    response = requests.get(
        f"https://api.dcycle.io/v1/vehicles/{vehicle_id}/consumptions",
        headers=headers,
        params={"status": ["success"], "size": 100}
    )

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

    import csv
    with open(f"consumption_{vehicle_id}.csv", "w", newline="") as f:
        writer = csv.DictWriter(
            f,
            fieldnames=["date", "fuel_consumed", "distance_km", "efficiency"]
        )
        writer.writeheader()

        for c in consumptions:
            data = c["data"]
            writer.writerow({
                "date": c["created_at"],
                "fuel_consumed": data.get("fuel_consumed"),
                "distance_km": data.get("distance_km"),
                "efficiency": data.get("fuel_efficiency")
            })

    print(f"Exported {len(consumptions)} records")

# Export data
export_consumption_data("550e8400-e29b-41d4-a716-446655440000")
```

### Analyze Fuel Efficiency Trends

Track fuel efficiency changes over time:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def analyze_efficiency_trends(vehicle_id):
    """Analyze fuel efficiency trends for a vehicle"""
    response = requests.get(
        f"https://api.dcycle.io/v1/vehicles/{vehicle_id}/consumptions",
        headers=headers,
        params={"status": ["success"], "size": 100}
    )

    consumptions = response.json()["items"]
    consumptions.sort(key=lambda x: x["created_at"])

    efficiencies = [
        {
            "date": c["created_at"],
            "efficiency": c["data"].get("fuel_efficiency")
        }
        for c in consumptions
        if c["data"].get("fuel_efficiency")
    ]

    if efficiencies:
        avg_efficiency = sum(e["efficiency"] for e in efficiencies) / len(efficiencies)
        min_efficiency = min(e["efficiency"] for e in efficiencies)
        max_efficiency = max(e["efficiency"] for e in efficiencies)

        print(f"Average efficiency: {avg_efficiency:.2f} km/l")
        print(f"Min efficiency: {min_efficiency:.2f} km/l")
        print(f"Max efficiency: {max_efficiency:.2f} km/l")

    return efficiencies

# Analyze trends
trends = analyze_efficiency_trends("550e8400-e29b-41d4-a716-446655440000")
```

## Related Endpoints

<CardGroup cols={2}>
  <Card title="List Vehicles" icon="list" href="/api-reference/vehicles/list">
    Retrieve all vehicles
  </Card>

  <Card title="Create Vehicle" icon="plus" href="/api-reference/vehicles/create">
    Add a new vehicle to your fleet
  </Card>

  <Card title="Vehicle Overview" icon="car" href="/api-reference/vehicles/overview">
    Learn about the Vehicles API
  </Card>

  <Card title="Logistics API" icon="truck" href="/api-reference/logistics/create-request">
    Calculate emissions for shipments
  </Card>

  <Card title="List Vehicle Consumptions (Organization)" icon="table" href="/api-reference/vehicles/consumptions-org-list">
    List consumptions across every vehicle in the organization, not just one
  </Card>
</CardGroup>
