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

> Get a list of fuels available for vehicle consumption

# List Vehicle Fuels

Retrieve all vehicle fuels available in the Dcycle system. Vehicle fuels represent different types of energy sources for vehicles (gasoline, diesel, electric, hybrid, CNG, LPG, etc.) and are used when creating vehicles and tracking fuel consumption.

<Note>
  Vehicle fuels are **reference data** maintained by Dcycle. You cannot create or modify fuels through the API - this endpoint is read-only.
</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>

### Query Parameters

<ParamField query="vehicle_type" type="string">
  Filter fuels by vehicle type

  **Valid vehicle types:**

  * `passenger_car` - Standard passenger cars
  * `light_commercial` - Light commercial vehicles (vans, small trucks)
  * `rigid` - Rigid trucks
  * `articulated` - Articulated trucks (semi-trailers)
  * `motorcycle` - Motorcycles and scooters
  * `bus` - Buses and coaches

  **Example:** `"passenger_car"`
</ParamField>

<ParamField query="country" type="string">
  Filter fuels by country using ISO 3166-1 alpha-2 country code

  **Supported country codes:**

  * `ES` - Spain (returns Spanish vehicle fuels)
  * Any other code returns global (GLO) database fuels

  <Info>
    Country-specific vehicle fuels are currently only available for Spain (`ES`). Other countries will receive generic fuels from the global database.
  </Info>

  **Example:** `"ES"`
</ParamField>

## Response

Returns an array of vehicle fuel objects (not paginated - all matching fuels are returned).

<ResponseField name="[]" type="array">
  Array of vehicle fuel objects

  ### Vehicle Fuel Object Fields:

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

  <ResponseField name="fuel" type="string">
    Fuel name (e.g., "Diesel", "Gasoline", "Electric", "Hybrid", "CNG", "LPG")
  </ResponseField>

  <ResponseField name="country" type="string">
    ISO 3166-1 alpha-2 country code where fuel data applies (`ES` or `GLO`)
  </ResponseField>

  <ResponseField name="vehicle_types" type="array" optional>
    Array of vehicle type IDs that can use this fuel

    Only included when **no** `vehicle_type` filter is applied. When filtering by vehicle\_type, this field is omitted.

    **Example:** `["passenger_car_id_1", "light_commercial_id_2"]`
  </ResponseField>

  <ResponseField name="units" type="array">
    Array of available measurement units for this fuel

    Each unit object contains:

    * `id` (string) - Unit UUID
    * `name` (string) - Unit name (e.g., "L", "kWh", "kg")
    * `type` (string) - Unit type (e.g., "liquid", "energy", "solid")
  </ResponseField>
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET "https://api.dcycle.io/api/v1/vehicle_fuels?vehicle_type=passenger_car&country=ES" \
    -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
  }

  # Get fuels for passenger cars in Spain
  params = {
      "vehicle_type": "passenger_car",
      "country": "ES"
  }

  response = requests.get(
      "https://api.dcycle.io/api/v1/vehicle_fuels",
      headers=headers,
      params=params
  )

  fuels = response.json()
  print(f"Found {len(fuels)} fuels for passenger cars:")

  for fuel in fuels:
      units_str = ", ".join([u['name'] for u in fuel['units']])
      print(f"- {fuel['fuel']}: {units_str}")
  ```

  ```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
  };

  // Get fuels for passenger cars in Spain
  const params = {
    vehicle_type: 'passenger_car',
    country: 'ES'
  };

  axios.get('https://api.dcycle.io/api/v1/vehicle_fuels', { headers, params })
    .then(response => {
      const fuels = response.data;
      console.log(`Found ${fuels.length} fuels for passenger cars:`);

      fuels.forEach(fuel => {
        const unitsStr = fuel.units.map(u => u.name).join(', ');
        console.log(`- ${fuel.fuel}: ${unitsStr}`);
      });
    })
    .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response (with vehicle\_type filter)

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
[
  {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "fuel": "Diesel",
    "country": "ES",
    "units": [
      {
        "id": "unit-1-uuid",
        "name": "L",
        "type": "liquid"
      },
      {
        "id": "unit-2-uuid",
        "name": "kWh",
        "type": "energy"
      }
    ]
  },
  {
    "id": "b2c3d4e5-f6g7-8901-bcde-fg2345678901",
    "fuel": "Gasoline",
    "country": "ES",
    "units": [
      {
        "id": "unit-3-uuid",
        "name": "L",
        "type": "liquid"
      },
      {
        "id": "unit-4-uuid",
        "name": "kWh",
        "type": "energy"
      }
    ]
  },
  {
    "id": "c3d4e5f6-g7h8-9012-cdef-gh3456789012",
    "fuel": "Electric",
    "country": "ES",
    "units": [
      {
        "id": "unit-5-uuid",
        "name": "kWh",
        "type": "energy"
      }
    ]
  },
  {
    "id": "d4e5f6g7-h8i9-0123-defg-hi4567890123",
    "fuel": "Hybrid",
    "country": "ES",
    "units": [
      {
        "id": "unit-6-uuid",
        "name": "L",
        "type": "liquid"
      },
      {
        "id": "unit-7-uuid",
        "name": "kWh",
        "type": "energy"
      }
    ]
  }
]
```

### Successful Response (without filters)

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
[
  {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "fuel": "Diesel",
    "country": "GLO",
    "vehicle_types": [
      "passenger_car_id",
      "light_commercial_id",
      "rigid_id",
      "articulated_id"
    ],
    "units": [
      {
        "id": "unit-1-uuid",
        "name": "L",
        "type": "liquid"
      },
      {
        "id": "unit-2-uuid",
        "name": "kWh",
        "type": "energy"
      }
    ]
  },
  {
    "id": "b2c3d4e5-f6g7-8901-bcde-fg2345678901",
    "fuel": "Electric",
    "country": "GLO",
    "vehicle_types": [
      "passenger_car_id",
      "light_commercial_id",
      "bus_id"
    ],
    "units": [
      {
        "id": "unit-3-uuid",
        "name": "kWh",
        "type": "energy"
      }
    ]
  }
]
```

## Common Errors

### 400 Bad Request - Invalid Vehicle Type

**Cause:** Invalid vehicle type

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Invalid vehicle type",
  "code": "VALIDATION_ERROR"
}
```

**Solution:** Use a valid vehicle type from the list above (`passenger_car`, `light_commercial`, `rigid`, `articulated`, `motorcycle`, `bus`).

### 400 Bad Request - Invalid Country Code

**Cause:** Invalid country code format

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Invalid country code format",
  "code": "VALIDATION_ERROR"
}
```

**Solution:** Use a valid ISO 3166-1 alpha-2 country code (2 letters).

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

## Use Cases

### Get Fuels for Creating Unknown Vehicles

When creating an unknown vehicle, you need the fuel ID:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def create_unknown_vehicle_with_fuel(vehicle_type):
    """Create an unknown vehicle with appropriate fuel"""

    # 1. Get fuels for this vehicle type
    response = requests.get(
        "https://api.dcycle.io/api/v1/vehicle_fuels",
        headers=headers,
        params={
            "vehicle_type": vehicle_type,
            "country": "ES"
        }
    )

    fuels = response.json()

    # 2. Let user select fuel (or default to diesel)
    diesel_fuel = next(
        (f for f in fuels if "Diesel" in f['fuel']),
        fuels[0] if fuels else None
    )

    if not diesel_fuel:
        print("⚠️ No fuels available for this vehicle type")
        return

    # 3. Get unit (liters for liquid fuels)
    liter_unit = next(
        (u for u in diesel_fuel['units'] if u['name'] == 'L'),
        diesel_fuel['units'][0] if diesel_fuel['units'] else None
    )

    # 4. Create unknown vehicle (bulk upload)
    vehicle_data = {
        "name": "Company Van #1",
        "license_plate": "1234-ABC",
        "type": "freight",  # passenger or freight
        "ownership": "owned",
        "country": "ES",
        "is_known": False,  # Unknown vehicle
        "vehicle_fuel_id": diesel_fuel['id'],
        "registration_year": 2020
    }

    print(f"✅ Vehicle configured with {diesel_fuel['fuel']} fuel")
    return vehicle_data
```

### Get All Fuels with Vehicle Types

When you need to know which vehicle types can use each fuel:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_fuels_with_compatibility():
    """Get all fuels with vehicle type compatibility info"""

    # Get all fuels without filters to include vehicle_types
    response = requests.get(
        "https://api.dcycle.io/api/v1/vehicle_fuels",
        headers=headers
    )

    fuels = response.json()

    # Display fuel compatibility matrix
    print("Fuel Compatibility Matrix:")
    for fuel in fuels:
        vehicle_types = fuel.get('vehicle_types', [])
        print(f"\n{fuel['fuel']}:")
        print(f"  Country: {fuel['country']}")
        print(f"  Compatible with {len(vehicle_types)} vehicle types")
        print(f"  Available units: {', '.join([u['name'] for u in fuel['units']])}")

    return fuels
```

### Filter Fuels by Type

Organize fuels for a UI selector:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_fuels_by_category(vehicle_type, country="ES"):
    """Get fuels organized by category"""

    response = requests.get(
        "https://api.dcycle.io/api/v1/vehicle_fuels",
        headers=headers,
        params={
            "vehicle_type": vehicle_type,
            "country": country
        }
    )

    fuels = response.json()

    # Categorize fuels
    categories = {
        "fossil": [],
        "alternative": [],
        "electric": []
    }

    for fuel in fuels:
        fuel_name = fuel['fuel'].lower()

        if 'electric' in fuel_name or 'battery' in fuel_name:
            categories['electric'].append(fuel)
        elif any(alt in fuel_name for alt in ['cng', 'lng', 'lpg', 'hydrogen', 'hybrid']):
            categories['alternative'].append(fuel)
        else:
            categories['fossil'].append(fuel)

    return categories

# Usage
fuels = get_fuels_by_category("passenger_car", "ES")

print("Fossil Fuels:")
for f in fuels['fossil']:
    print(f"  - {f['fuel']}")

print("\nAlternative Fuels:")
for f in fuels['alternative']:
    print(f"  - {f['fuel']}")

print("\nElectric:")
for f in fuels['electric']:
    print(f"  - {f['fuel']}")
```

### Cache Vehicle Fuels

Since vehicle fuels don't change frequently, cache them:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from datetime import datetime, timedelta

class DcycleVehicleFuelsCache:
    def __init__(self, api_key, org_id, user_id):
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "x-organization-id": org_id,
            "x-user-id": user_id
        }
        self._cache = {}
        self._cache_time = {}
        self.cache_duration = timedelta(hours=24)

    def get_fuels(self, vehicle_type=None, country=None):
        """Get vehicle fuels with caching"""

        cache_key = f"{vehicle_type or 'all'}_{country or 'all'}"

        # Check if cache is valid
        if (cache_key not in self._cache_time or
            datetime.now() - self._cache_time[cache_key] > self.cache_duration):
            self._refresh_cache(vehicle_type, country)

        return self._cache.get(cache_key, [])

    def _refresh_cache(self, vehicle_type=None, country=None):
        """Refresh the cache"""

        params = {}
        if vehicle_type:
            params["vehicle_type"] = vehicle_type
        if country:
            params["country"] = country

        response = requests.get(
            "https://api.dcycle.io/api/v1/vehicle_fuels",
            headers=self.headers,
            params=params
        )

        fuels = response.json()

        cache_key = f"{vehicle_type or 'all'}_{country or 'all'}"
        self._cache[cache_key] = fuels
        self._cache_time[cache_key] = datetime.now()

        print(f"✅ Vehicle fuels cache refreshed for '{cache_key}': {len(fuels)} fuels")

    def get_fuel_by_id(self, fuel_id, vehicle_type=None, country=None):
        """Get a specific fuel by ID"""

        fuels = self.get_fuels(vehicle_type, country)

        for fuel in fuels:
            if fuel['id'] == fuel_id:
                return fuel

        return None

    def get_fuel_by_name(self, name, vehicle_type=None, country=None):
        """Get a fuel by name (case-insensitive)"""

        fuels = self.get_fuels(vehicle_type, country)

        for fuel in fuels:
            if name.lower() in fuel['fuel'].lower():
                return fuel

        return None

# Usage
cache = DcycleVehicleFuelsCache(
    api_key=os.getenv("DCYCLE_API_KEY"),
    org_id=os.getenv("DCYCLE_ORG_ID"),
    user_id=os.getenv("DCYCLE_USER_ID")
)

# Get fuels for passenger cars
diesel = cache.get_fuel_by_name("Diesel", "passenger_car", "ES")
electric = cache.get_fuel_by_name("Electric", "passenger_car", "ES")
```

### Validate Fuel for Vehicle Type

Ensure a fuel is compatible with a vehicle type:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def validate_fuel_for_vehicle_type(fuel_id, vehicle_type, country="ES"):
    """Validate that a fuel is compatible with a vehicle type"""

    # Get fuels for this vehicle type
    response = requests.get(
        "https://api.dcycle.io/api/v1/vehicle_fuels",
        headers=headers,
        params={
            "vehicle_type": vehicle_type,
            "country": country
        }
    )

    fuels = response.json()

    # Check if fuel is in the list
    fuel_ids = [f['id'] for f in fuels]

    if fuel_id not in fuel_ids:
        available_fuels = [f['fuel'] for f in fuels]
        raise ValueError(
            f"Fuel {fuel_id} is not compatible with vehicle type '{vehicle_type}'. "
            f"Available fuels: {', '.join(available_fuels)}"
        )

    return True

# Usage
try:
    validate_fuel_for_vehicle_type(
        fuel_id="diesel-fuel-uuid",
        vehicle_type="passenger_car",
        country="ES"
    )
    print("✅ Fuel is compatible")
except ValueError as e:
    print(f"❌ Validation error: {e}")
```

## Vehicle Types

The `vehicle_type` parameter accepts these values:

| Type               | Description                          | Common Fuels                            |
| ------------------ | ------------------------------------ | --------------------------------------- |
| `passenger_car`    | Standard passenger cars              | Gasoline, Diesel, Electric, Hybrid, CNG |
| `light_commercial` | Vans and small trucks                | Diesel, Gasoline, Electric, CNG         |
| `rigid`            | Rigid trucks                         | Diesel, CNG, LNG                        |
| `articulated`      | Semi-trailers and articulated trucks | Diesel, LNG                             |
| `motorcycle`       | Motorcycles and scooters             | Gasoline, Electric                      |
| `bus`              | Buses and coaches                    | Diesel, CNG, Electric, Hybrid           |

## Fuel Types

Common vehicle fuel types in the system:

### Fossil Fuels

* **Diesel** - Most common for commercial vehicles
* **Gasoline** (Petrol) - Standard passenger car fuel
* **LPG** (Liquefied Petroleum Gas) - Alternative fuel for cars and vans

### Alternative Fuels

* **CNG** (Compressed Natural Gas) - Cleaner alternative for trucks and buses
* **LNG** (Liquefied Natural Gas) - For heavy-duty trucks
* **Biodiesel** - Renewable diesel alternative
* **Bioethanol** - Renewable gasoline alternative

### Electric & Hybrid

* **Electric** - Battery electric vehicles (BEV)
* **Hybrid** - Combined electric and combustion
* **Plug-in Hybrid** - Rechargeable hybrid vehicles

## Units per Fuel

Each fuel has specific units for measuring consumption:

### Liquid Fuels (Diesel, Gasoline, LPG liquid)

* **L** (liters) - Standard volume measurement
* **kWh** - Energy content
* **kg** - Mass measurement (for some fuels)

### Gaseous Fuels (CNG, LNG)

* **kg** - Mass measurement (most common)
* **m³** - Volume measurement
* **kWh** - Energy content

### Electric

* **kWh** - Electricity consumption (only unit)

<Tip>
  Always check the `units` array for each fuel to see which units are available. Using an incompatible unit will result in an error when creating vehicles or invoices.
</Tip>

## Country-Specific Behavior

### Spain (ES)

Spain has country-specific emission factors for vehicle fuels based on:

* National fuel composition standards
* Regional grid mix for electric vehicles
* Fuel production and distribution emissions

### Global (GLO)

For countries other than Spain, the system returns global emission factors based on:

* **IPCC** guidelines
* **GHG Protocol** standards
* International fuel standards

<Warning>
  If you need country-specific vehicle fuels beyond Spain, contact Dcycle support. We're continuously expanding our fuel databases.
</Warning>

## Best Practices

### 1. Cache Reference Data

Vehicle fuels don't change frequently, so cache them:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Good - Cache for 24 hours
fuels_cache = cache.get_fuels("passenger_car", "ES")

# Bad - Fetch every time
fuels = requests.get(f"https://api.dcycle.io/api/v1/vehicle_fuels?vehicle_type=passenger_car")
```

### 2. Filter by Vehicle Type

Always filter by vehicle type when creating vehicles:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Good - Only fetch relevant fuels
passenger_fuels = get_fuels(vehicle_type="passenger_car", country="ES")

# Less efficient - Fetch all and filter client-side
all_fuels = get_fuels()
passenger_fuels = [f for f in all_fuels if 'passenger_car' in f.get('vehicle_types', [])]
```

### 3. Validate Unit Before Use

Check that the unit is available for the selected fuel:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def validate_unit_for_fuel(fuel_id, unit_id):
    fuel = cache.get_fuel_by_id(fuel_id)
    unit_ids = [u['id'] for u in fuel['units']]

    if unit_id not in unit_ids:
        raise ValueError(f"Invalid unit for fuel '{fuel['fuel']}'")

    return True
```

### 4. Store Common Fuel IDs

For frequently used fuels, store their IDs:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# config.py
COMMON_VEHICLE_FUELS_ES = {
    'diesel': 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
    'gasoline': 'b2c3d4e5-f6g7-8901-bcde-fg2345678901',
    'electric': 'c3d4e5f6-g7h8-9012-cdef-gh3456789012'
}

# Usage - No API call needed
vehicle_data = {
    "vehicle_fuel_id": COMMON_VEHICLE_FUELS_ES['diesel'],
    # ... other fields
}
```

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Bulk Upload Vehicles" icon="upload" href="/api-docs/vehicles/bulk-upload">
    Upload vehicles with fuel IDs
  </Card>

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

  <Card title="List Units" icon="ruler" href="/api-docs/units/list">
    Get measurement units
  </Card>

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