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

# Vehicles API

> Manage vehicles and calculate CO2e emissions for your fleet

# Vehicles API

The Vehicles API allows you to create, retrieve, update, and delete vehicles within your organization. Each vehicle is configured with specific attributes that enable accurate CO2e emissions calculations based on fuel type, vehicle characteristics, and usage patterns.

<Note>
  **New API**: This endpoint is part of the new API architecture with improved design and maintainability.
</Note>

## Key Features

* **Fleet Management**: Create and manage vehicles in your organization
* **Flexible Vehicle Configuration**: Support for both known vehicles (with fuel types) and unknown vehicle types
* **CO2e Calculation**: Automatic emissions calculation based on vehicle characteristics
* **Regional Support**: ISO country codes for region-specific emission factors
* **Market Segmentation**: Classify vehicles by market segment for accurate categorization
* **Pagination Support**: Efficiently retrieve large lists of vehicles

## Authentication

All endpoints require authentication using an API key included in the `x-api-key` header.

## Headers

All requests must include:

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

  **Example:** `a8315ef3-dd50-43f8-b7ce-d839e68d51fa`
</ParamField>

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

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

## Available Endpoints

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

  <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="Market Segments" icon="tags" href="/api-reference/vehicles/market-segments">
    Get available vehicle market segments
  </Card>

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

## Vehicle Attributes

### Core Vehicle Information

* **name** (`string`, optional): Custom name or alias for the vehicle (e.g., "Company Fleet Car #1")
* **type** (`string`, required): Type of vehicle usage - `passenger` or `freight`
* **ownership** (`string`, required): Ownership type - `owned` or `rented`
* **license\_plate** (`string`, required): Vehicle registration/license plate number
* **country** (`string`, required): ISO 3166-1 country code (2-3 characters)

### Vehicle Classification

* **unknown\_vehicle\_id** (`UUID`, required): UUID of the unknown vehicle type for categorization
* **vehicle\_fuel\_id** (`UUID`, optional): UUID of the vehicle fuel type (petrol, diesel, electric, hybrid, etc.)
* **registration\_year** (`integer`, optional): Year of vehicle registration (YYYY format)
* **market\_segment** (`string`, optional): Vehicle market segment classification
* **size** (`string`, optional): Vehicle size category (small, medium, large)

### Emission Data

* **custom\_emission\_factor\_id** (`UUID`, optional): UUID of a custom emission factor for organizations with custom emission data
* **co2e** (`float`, read-only): Calculated CO2 equivalent emissions in kg CO2e

## Workflow

### Creating a Fleet Vehicle

1. **Retrieve available options** (if needed):
   * Get unknown vehicle types from `/unknown-vehicles` endpoint
   * Get fuel types from `/vehicle-fuels` endpoint
   * Get market segments from `/vehicles/market-segments` endpoint

2. **Create the vehicle** with:
   * Required fields: `type`, `ownership`, `license_plate`, `country`, `unknown_vehicle_id`
   * Either `vehicle_fuel_id` or `custom_emission_factor_id` for emissions calculation

3. **Track emissions** through the `co2e` field in responses

### Filtering and Pagination

Use query parameters to:

* Filter by status (`active`, `archived`, `error`)
* Filter by ownership type (`owned`, `rented`)
* Filter by fuel type or unknown vehicle type
* Search by vehicle name or license plate
* Sort results (by name, license plate, creation date)
* Include child organizations in results

## Response Format

All responses include:

### Vehicle Object

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "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",
  "unknown_vehicle_type": null,
  "registration_year": 2022,
  "market_segment": "upper_medium",
  "size": "medium",
  "created_at": "2024-11-24T10:30:00Z",
  "updated_at": "2024-11-24T10:30:00Z"
}
```

### Pagination Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "items": [
    { "vehicle object" },
    { "vehicle object" }
  ],
  "total": 150,
  "page": 1,
  "size": 50,
  "filter_hash": "a1b2c3d4e5f67890"
}
```

## Error Handling

### Common HTTP Status Codes

| Status | Meaning                        | Solution                            |
| ------ | ------------------------------ | ----------------------------------- |
| 200    | Success                        | -                                   |
| 201    | Created                        | -                                   |
| 204    | No Content (delete successful) | -                                   |
| 400    | Bad Request                    | Check request parameters and format |
| 401    | Unauthorized                   | Verify API key or JWT token         |
| 404    | Not Found                      | Check resource ID or organization   |
| 422    | Validation Error               | Review error details in response    |
| 500    | Server Error                   | Contact support if persists         |

### Error Response Format

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Error description",
  "code": "ERROR_CODE"
}
```

## Use Cases

### Track Corporate Fleet Emissions

Monitor CO2e emissions for all vehicles in your organization:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Get all active vehicles
vehicles = requests.get(
    "https://api.dcycle.io/v1/vehicles",
    headers={
        "x-api-key": api_key,
        "x-organization-id": org_id
    },
    params={"status": ["active"]}
)

total_co2e = sum(v["co2e"] for v in vehicles.json()["items"])
print(f"Fleet total: {total_co2e} kg CO2e")
```

### Compare Vehicle Options

Evaluate different vehicle options based on emissions:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Create vehicles with different fuel types
vehicles_to_test = [
    {"name": "Diesel Van", "vehicle_fuel_id": diesel_uuid},
    {"name": "Electric Van", "vehicle_fuel_id": electric_uuid},
    {"name": "Hybrid Van", "vehicle_fuel_id": hybrid_uuid}
]

for vehicle in vehicles_to_test:
    response = requests.post(
        "https://api.dcycle.io/v1/vehicles",
        headers=headers,
        json=vehicle
    )
    data = response.json()
    print(f"{data['name']}: {data['co2e']} kg CO2e")
```

## Related Documentation

<CardGroup cols={2}>
  <Card title="Authentication Guide" icon="key" href="/docs/authentication">
    Learn how to get your API key and authenticate requests
  </Card>

  <Card title="Unknown Vehicles" icon="question" href="/api-reference/unknown-vehicles/list">
    Manage unknown vehicle types in your system
  </Card>

  <Card title="Vehicle Fuels" icon="droplet" href="/api-reference/vehicle-fuels/list">
    View available fuel types for vehicle configuration
  </Card>

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

## Rate Limiting

API requests are subject to rate limiting. Include rate limit information from response headers:

* `X-RateLimit-Limit`: Maximum requests per minute
* `X-RateLimit-Remaining`: Requests remaining
* `X-RateLimit-Reset`: Unix timestamp when limit resets
