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

# Update Vehicle

> Modify vehicle details and update fleet information

# Update Vehicle

Update specific fields of an existing vehicle. All fields are optional - only include fields you want to modify. Omitted fields will retain their current values.

<Note>
  **CO2e Recalculation**: When you update fields like `vehicle_fuel_id`, `registration_year`, or `market_segment`, CO2e emissions are automatically recalculated.
</Note>

## Request

### Path Parameters

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

  **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>

### Body Parameters

All parameters are optional. Only include fields you want to update.

<ParamField body="name" type="string">
  Custom name or alias for the vehicle

  **Example:** `"Updated Fleet Car Name"`
</ParamField>

<ParamField body="type" type="string">
  Type of vehicle usage

  **Available values:** `passenger`, `freight`

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

<ParamField body="ownership" type="string">
  Vehicle ownership type

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

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

<ParamField body="license_plate" type="string">
  Vehicle registration/license plate number

  **Example:** `"XYZ-9999"`
</ParamField>

<ParamField body="country" type="string">
  ISO 3166-1 country code (2-3 characters)

  **Examples:** `"US"`, `"GB"`, `"ES"`, `"DE"`

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

<ParamField body="vehicle_fuel_id" type="uuid">
  UUID of the vehicle fuel type

  Retrieve available options from `GET /v1/vehicle-fuels`

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

<ParamField body="custom_emission_factor_id" type="uuid">
  UUID of a custom emission factor

  For organizations with custom emission data

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

<ParamField body="registration_year" type="integer">
  Year of vehicle registration (YYYY format)

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

<ParamField body="market_segment" type="string">
  Vehicle market segment for classification

  **Available values:** `mini`, `supermini`, `lower_medium`, `upper_medium`, `executive`, `luxury`, `sports`, `dual_purpose_4x4`, `mpv`

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

<ParamField body="size" type="string">
  Vehicle size category

  **Available values:** `small_car`, `medium`, `large_car`, `average_car`

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

<ParamField body="unknown_vehicle_id" type="uuid">
  UUID of the unknown vehicle type

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

## Response

<ResponseField name="id" type="string">
  Unique identifier (UUID) for the vehicle
</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">
  Updated CO2 equivalent emissions in kg CO2e
</ResponseField>

<ResponseField name="vehicle_fuel_id" type="string | null">
  UUID of the fuel type
</ResponseField>

<ResponseField name="vehicle_fuel" type="string | null">
  Fuel type name (e.g. `diesel`, `petrol`, `electric`)
</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 name of the unknown vehicle type (e.g. `Truck`, `Van`)
</ResponseField>

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

<ResponseField name="registration_year" type="integer | null">
  Year of vehicle registration
</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">
  Error codes when status is `error`
</ResponseField>

<ResponseField name="file_id" type="string | null">
  UUID of the import file, if created via CSV import
</ResponseField>

<ResponseField name="file_name" type="string | null">
  Name of the import file, if created via CSV import
</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>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X PATCH "https://api.dcycle.io/v1/vehicles/550e8400-e29b-41d4-a716-446655440000" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Updated Fleet Car #1",
      "registration_year": 2023,
      "market_segment": "executive"
    }'
  ```

  ```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,
      "Content-Type": "application/json"
  }

  payload = {
      "name": "Updated Fleet Car #1",
      "registration_year": 2023,
      "market_segment": "executive"
  }

  response = requests.patch(
      f"https://api.dcycle.io/v1/vehicles/{vehicle_id}",
      headers=headers,
      json=payload
  )

  vehicle = response.json()
  print(f"Vehicle updated: {vehicle['id']}")
  print(f"New CO2e: {vehicle['co2e']} kg")
  ```

  ```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,
    'Content-Type': 'application/json'
  };

  const payload = {
    name: "Updated Fleet Car #1",
    registration_year: 2023,
    market_segment: "executive"
  };

  axios.patch(
    `https://api.dcycle.io/v1/vehicles/${vehicleId}`,
    payload,
    { headers }
  )
  .then(response => {
    const vehicle = response.data;
    console.log(`Vehicle updated: ${vehicle.id}`);
    console.log(`New CO2e: ${vehicle.co2e} kg`);
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Updated Fleet Car #1",
  "type": "passenger",
  "ownership": "owned",
  "license_plate": "ABC-1234",
  "country": "ES",
  "status": "active",
  "co2e": 248.3,
  "vehicle_fuel_id": "660e8400-e29b-41d4-a716-446655440000",
  "vehicle_fuel": "diesel",
  "vehicle_fuel_units": [
    { "id": "unit-uuid", "name": "litres", "type": "volume" }
  ],
  "unknown_vehicle_id": null,
  "unknown_vehicle_type": null,
  "custom_emission_factor_id": null,
  "registration_year": 2023,
  "market_segment": "executive",
  "size": "medium",
  "error_messages": null,
  "file_id": null,
  "file_name": null,
  "created_at": "2024-11-24T10:30:00Z",
  "updated_at": "2024-11-24T15:45:00Z"
}
```

## 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 values for enumerated fields

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": [
    {
      "loc": ["body", "type"],
      "msg": "value is not a valid enumeration member; permitted: 'passenger', 'freight'",
      "type": "type_error.enum"
    }
  ]
}
```

**Solution:** Ensure enum values are exactly as specified. Use valid country codes (2-3 characters) and permitted values for `type`, `ownership`, `market_segment`, and `size`.

## Use Cases

### Update Vehicle Ownership Status

Change vehicle ownership from owned to rented:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def change_vehicle_ownership(vehicle_id, new_ownership):
    """Update vehicle ownership status"""
    payload = {"ownership": new_ownership}

    response = requests.patch(
        f"https://api.dcycle.io/v1/vehicles/{vehicle_id}",
        headers=headers,
        json=payload
    )

    return response.json()

# Change to rented
updated = change_vehicle_ownership(
    "550e8400-e29b-41d4-a716-446655440000",
    "rented"
)
print(f"Updated: {updated['license_plate']} now {updated['ownership']}")
```

### Update Fuel Type and Recalculate Emissions

Switch a vehicle to electric fuel to see emissions change:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def switch_to_electric(vehicle_id, electric_fuel_id):
    """Switch vehicle to electric fuel"""
    payload = {"vehicle_fuel_id": electric_fuel_id}

    response = requests.patch(
        f"https://api.dcycle.io/v1/vehicles/{vehicle_id}",
        headers=headers,
        json=payload
    )

    vehicle = response.json()
    return {
        "vehicle_id": vehicle["id"],
        "new_fuel": "electric",
        "co2e": vehicle["co2e"]
    }

# Get electric fuel ID first, then switch
electric_vehicle = switch_to_electric(
    "550e8400-e29b-41d4-a716-446655440000",
    "880e8400-e29b-41d4-a716-446655440000"
)
print(f"New CO2e after electric switch: {electric_vehicle['co2e']} kg")
```

### Update Multiple Vehicles Simultaneously

Update vehicles in bulk:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def bulk_update_vehicles(updates):
    """Update multiple vehicles with new information"""
    results = []

    for vehicle_id, update_payload in updates.items():
        response = requests.patch(
            f"https://api.dcycle.io/v1/vehicles/{vehicle_id}",
            headers=headers,
            json=update_payload
        )

        if response.status_code == 200:
            results.append(response.json())
        else:
            print(f"Failed to update vehicle {vehicle_id}")

    return results

# Bulk update example
updates = {
    "550e8400-e29b-41d4-a716-446655440000": {
        "registration_year": 2023,
        "market_segment": "executive"
    },
    "550e8400-e29b-41d4-a716-446655440001": {
        "ownership": "rented",
        "name": "Rental Van"
    }
}

updated_vehicles = bulk_update_vehicles(updates)
print(f"Updated {len(updated_vehicles)} vehicles")
```

### Rename Vehicle Fleet

Update vehicle names for better organization:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def rename_vehicle(vehicle_id, new_name):
    """Rename a vehicle"""
    response = requests.patch(
        f"https://api.dcycle.io/v1/vehicles/{vehicle_id}",
        headers=headers,
        json={"name": new_name}
    )

    return response.json()

# Rename vehicles
rename_vehicle(
    "550e8400-e29b-41d4-a716-446655440000",
    "Executive Car - Spain HQ"
)
```

## Related 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="Delete Vehicle" icon="trash" href="/api-reference/vehicles/delete">
    Remove a vehicle from your fleet
  </Card>

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