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

> Retrieve all vehicles with filtering and pagination support

# List Vehicles

Retrieve a paginated list of vehicles in your organization with support for filtering, searching, and sorting.

<Note>
  **Performance Optimized**: This endpoint uses correlated subqueries for efficient CO2e calculation, computing emissions only for the paginated result set rather than all vehicles.
</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:** `a8315ef3-dd50-43f8-b7ce-d839e68d51fa`
</ParamField>

### Query Parameters

<ParamField query="include_children" type="boolean" default="false">
  Include vehicles from child organizations

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

<ParamField query="search" type="string">
  Search vehicles by name or license plate (partial match)

  **Example:** `"Company Fleet"`
</ParamField>

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

  **Available values:** `active`, `archived`, `error`

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

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

  **Available values:** `owned`, `rented`

  **Example:** `ownership[]=owned`
</ParamField>

<ParamField query="unknown_vehicle_id[]" type="array[uuid]">
  Filter by unknown vehicle type UUID

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

<ParamField query="vehicle_fuel_id[]" type="array[uuid]">
  Filter by fuel type UUID

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

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

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

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

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

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

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

<ParamField query="start_date" type="integer">
  Filter by reporting period start year (inclusive)

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

<ParamField query="end_date" type="integer">
  Filter by reporting period end year (inclusive)

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

<ParamField query="sort" type="array[string]">
  Sort results (prefix with `-` for descending)

  **Available values:** `name`, `license_plate`, `created_at`, `updated_at`, `-name`, `-license_plate`, `-created_at`, `-updated_at`

  **Example:** `sort=name&sort=-created_at`
</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 vehicle objects

  <Expandable title="Vehicle Object">
    <ResponseField name="id" type="string">
      Unique identifier (UUID)
    </ResponseField>

    <ResponseField name="name" type="string | null">
      Custom name or alias for the vehicle
    </ResponseField>

    <ResponseField name="type" type="string">
      Type of vehicle usage: `passenger` or `freight`
    </ResponseField>

    <ResponseField name="ownership" type="string">
      Ownership type: `owned` or `rented`
    </ResponseField>

    <ResponseField name="license_plate" type="string">
      Vehicle registration/license plate number
    </ResponseField>

    <ResponseField name="country" type="string">
      ISO 3166-1 country code
    </ResponseField>

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

    <ResponseField name="co2e" type="number">
      Calculated CO2 equivalent emissions in kg CO2e
    </ResponseField>

    <ResponseField name="vehicle_fuel_id" type="string | null">
      UUID of the fuel type (for known vehicles)
    </ResponseField>

    <ResponseField name="vehicle_fuel" type="string | null">
      Human-readable label for the fuel type
    </ResponseField>

    <ResponseField name="vehicle_fuel_units" type="array[object] | null">
      Available fuel units for this vehicle's fuel type

      <Expandable title="Fuel Unit Object">
        <ResponseField name="id" type="string">Unit UUID</ResponseField>
        <ResponseField name="name" type="string">Unit name (e.g. `litre_(l)`, `kilogram_(kg)`)</ResponseField>
        <ResponseField name="type" type="string">Unit category</ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="unknown_vehicle_id" type="string | null">
      UUID of the unknown vehicle type
    </ResponseField>

    <ResponseField name="unknown_vehicle_type" type="string | null">
      String representation of unknown vehicle type
    </ResponseField>

    <ResponseField name="custom_emission_factor_id" type="string | null">
      UUID of a custom emission factor applied to this vehicle, if any
    </ResponseField>

    <ResponseField name="registration_year" type="integer | null">
      Year of vehicle registration (YYYY format)
    </ResponseField>

    <ResponseField name="market_segment" type="string | null">
      Vehicle market segment classification
    </ResponseField>

    <ResponseField name="size" type="string | null">
      Vehicle size category
    </ResponseField>

    <ResponseField name="error_messages" type="array[string] | null">
      List of error codes when status is `error`
    </ResponseField>

    <ResponseField name="file_id" type="string | null">
      UUID of the source bulk-upload file, if any
    </ResponseField>

    <ResponseField name="file_name" type="string | null">
      Name of the source file, if any
    </ResponseField>

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

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

<ResponseField name="total" type="integer">
  Total number of vehicles matching the filter
</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/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?page=1&size=50&status[]=active" \
    -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")

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

  params = {
      "page": 1,
      "size": 50,
      "status[]": ["active"],
      "sort": ["name"]
  }

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

  result = response.json()
  for vehicle in result["items"]:
      print(f"{vehicle['name'] or vehicle['license_plate']}: {vehicle['co2e']} 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 headers = {
    'x-api-key': apiKey,
    'x-organization-id': orgId
  };

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

  axios.get(
    'https://api.dcycle.io/v1/vehicles',
    { headers, params }
  )
  .then(response => {
    response.data.items.forEach(vehicle => {
      console.log(`${vehicle.name || vehicle.license_plate}: ${vehicle.co2e} kg CO2e`);
    });
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "items": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "Company Fleet Car #1",
      "type": "passenger",
      "ownership": "owned",
      "license_plate": "ABC-1234",
      "country": "ES",
      "status": "active",
      "co2e": 245.5,
      "vehicle_fuel_id": "660e8400-e29b-41d4-a716-446655440000",
      "vehicle_fuel": "Diesel",
      "unknown_vehicle_id": null,
      "unknown_vehicle_type": null,
      "custom_emission_factor_id": null,
      "registration_year": 2022,
      "market_segment": "upper_medium",
      "size": "medium",
      "error_messages": null,
      "file_id": null,
      "file_name": null,
      "created_at": "2024-11-24T10:30:00Z",
      "updated_at": "2024-11-24T10:30:00Z"
    },
    {
      "id": "550e8400-e29b-41d4-a716-446655440001",
      "name": "Company Fleet Van",
      "type": "freight",
      "ownership": "owned",
      "license_plate": "XYZ-5678",
      "country": "ES",
      "status": "active",
      "co2e": 385.2,
      "vehicle_fuel_id": "760e8400-e29b-41d4-a716-446655440000",
      "vehicle_fuel": "Petrol",
      "unknown_vehicle_id": null,
      "unknown_vehicle_type": null,
      "custom_emission_factor_id": null,
      "registration_year": 2020,
      "market_segment": null,
      "size": "large_car",
      "error_messages": null,
      "file_id": null,
      "file_name": null,
      "created_at": "2024-11-23T14:15:00Z",
      "updated_at": "2024-11-24T09:45:00Z"
    }
  ],
  "total": 42,
  "page": 1,
  "size": 50,
  "filter_hash": "a1b2c3d4e5f67890"
}
```

## 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:** Organization not found

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

**Solution:** Verify that the `x-organization-id` header contains a valid organization UUID.

### 422 Validation Error

**Cause:** Invalid query parameters

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": [
    {
      "loc": ["query", "size"],
      "msg": "ensure this value is less than or equal to 100",
      "type": "value_error.number.not_le"
    }
  ]
}
```

**Solution:** Check that page size is between 1 and 100, and that filter values are valid enums.

## Use Cases

### Get All Active Vehicles

Retrieve only active vehicles for current fleet monitoring:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_active_vehicles():
    """Get all active vehicles in the organization"""
    response = requests.get(
        "https://api.dcycle.io/v1/vehicles",
        headers=headers,
        params={"status[]": ["active"], "size": 100}
    )
    return response.json()["items"]

active_vehicles = get_active_vehicles()
total_co2e = sum(v["co2e"] for v in active_vehicles)
print(f"Fleet CO2e: {total_co2e} kg")
```

### Search and Filter by Criteria

Find specific vehicles and get their emissions:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def search_vehicles(search_term=None, ownership=None, fuel_type=None):
    """Search vehicles with multiple filters"""
    params = {"size": 100}
    if search_term:
        params["search"] = search_term
    if ownership:
        params["ownership[]"] = [ownership]
    if fuel_type:
        params["vehicle_fuel_id[]"] = [fuel_type]

    response = requests.get(
        "https://api.dcycle.io/v1/vehicles",
        headers=headers,
        params=params
    )
    return response.json()["items"]

# Find all rented diesel vehicles
rented_diesel = search_vehicles(
    ownership="rented",
    fuel_type="760e8400-e29b-41d4-a716-446655440000"
)
```

### Export Fleet Data

Export vehicle data for reporting:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def export_fleet_to_csv():
    """Export all vehicles to CSV format"""
    response = requests.get(
        "https://api.dcycle.io/v1/vehicles",
        headers=headers,
        params={"size": 100}
    )

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

    import csv
    with open("fleet.csv", "w", newline="") as f:
        writer = csv.DictWriter(
            f,
            fieldnames=["name", "license_plate", "type", "ownership", "co2e", "status"]
        )
        writer.writeheader()
        for v in vehicles:
            writer.writerow({
                "name": v.get("name", ""),
                "license_plate": v["license_plate"],
                "type": v["type"],
                "ownership": v["ownership"],
                "co2e": v["co2e"],
                "status": v["status"]
            })
```

## Pagination Guide

Navigate through large vehicle lists efficiently:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def iterate_all_vehicles(batch_size=50):
    """Iterate through all vehicles in organization"""
    page = 1
    while True:
        response = requests.get(
            "https://api.dcycle.io/v1/vehicles",
            headers=headers,
            params={"page": page, "size": batch_size}
        )
        data = response.json()

        for vehicle in data["items"]:
            yield vehicle

        if len(data["items"]) < batch_size:
            break
        page += 1

# Process all vehicles
for vehicle in iterate_all_vehicles():
    print(f"Processing {vehicle['license_plate']}: {vehicle['co2e']} kg CO2e")
```

## Related Endpoints

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

  <Card title="Update Vehicle" icon="pencil" href="/api-reference/vehicles/update">
    Modify vehicle details
  </Card>

  <Card title="Delete Vehicle" icon="trash" href="/api-reference/vehicles/delete">
    Remove a vehicle from your fleet
  </Card>

  <Card title="Vehicle Consumptions" icon="chart-line" href="/api-reference/vehicles/consumptions">
    Retrieve consumption data for a specific vehicle
  </Card>
</CardGroup>
