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

# Create Vehicle

> Add a new vehicle to your organization's fleet

# Create Vehicle

Create a new vehicle in your organization's fleet. The system will automatically calculate CO2e emissions based on the vehicle's characteristics.

<Note>
  **Required Setup**: Before creating a vehicle, ensure you have retrieved the necessary references:

  * Unknown vehicle type IDs from `/v1/unknown-vehicles`
  * Fuel type IDs from `/v1/vehicle-fuels`
</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>

### Body Parameters

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

  **Example:** `"Company Fleet Car #1"`
</ParamField>

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

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

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

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

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

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

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

  **Example:** `"ABC-1234"`
</ParamField>

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

  Retrieve available options from `GET /v1/unknown-vehicles`

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

<ParamField body="country" type="string" required>
  ISO 3166-1 country code (2-3 characters) for regional emission calculations

  **Examples:** `"US"`, `"GB"`, `"ES"`, `"DE"`
</ParamField>

<ParamField body="vehicle_fuel_id" type="uuid">
  UUID of the vehicle fuel type (required if `custom_emission_factor_id` not provided)

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

  **Examples:** petrol, diesel, electric, hybrid

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

<ParamField body="custom_emission_factor_id" type="uuid">
  UUID of a custom emission factor (required if `vehicle_fuel_id` not provided)

  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)

  Used for age-based emission factors and vehicle classification

  **Example:** `2022`
</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>

## 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 of the vehicle (newly created vehicles are `active`)
</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
</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 POST "https://api.dcycle.io/v1/vehicles" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Company Fleet Car #1",
      "type": "passenger",
      "ownership": "owned",
      "license_plate": "ABC-1234",
      "country": "ES",
      "unknown_vehicle_id": "550e8400-e29b-41d4-a716-446655440000",
      "vehicle_fuel_id": "660e8400-e29b-41d4-a716-446655440000",
      "registration_year": 2022,
      "market_segment": "upper_medium",
      "size": "medium"
    }'
  ```

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

  payload = {
      "name": "Company Fleet Car #1",
      "type": "passenger",
      "ownership": "owned",
      "license_plate": "ABC-1234",
      "country": "ES",
      "unknown_vehicle_id": "550e8400-e29b-41d4-a716-446655440000",
      "vehicle_fuel_id": "660e8400-e29b-41d4-a716-446655440000",
      "registration_year": 2022,
      "market_segment": "upper_medium",
      "size": "medium"
  }

  response = requests.post(
      "https://api.dcycle.io/v1/vehicles",
      headers=headers,
      json=payload
  )

  vehicle = response.json()
  print(f"Vehicle created: {vehicle['id']}")
  print(f"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 headers = {
    'x-api-key': apiKey,
    'x-organization-id': orgId,
    'Content-Type': 'application/json'
  };

  const payload = {
    name: "Company Fleet Car #1",
    type: "passenger",
    ownership: "owned",
    license_plate: "ABC-1234",
    country: "ES",
    unknown_vehicle_id: "550e8400-e29b-41d4-a716-446655440000",
    vehicle_fuel_id: "660e8400-e29b-41d4-a716-446655440000",
    registration_year: 2022,
    market_segment: "upper_medium",
    size: "medium"
  };

  axios.post(
    'https://api.dcycle.io/v1/vehicles',
    payload,
    { headers }
  )
  .then(response => {
    const vehicle = response.data;
    console.log(`Vehicle created: ${vehicle.id}`);
    console.log(`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": "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",
  "vehicle_fuel_units": [
    { "id": "unit-uuid", "name": "litres", "type": "volume" }
  ],
  "unknown_vehicle_id": "550e8400-e29b-41d4-a716-446655440000",
  "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"
}
```

## 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 or invalid UUID reference

```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, and that the `unknown_vehicle_id` and `vehicle_fuel_id` are valid.

### 422 Validation Error

**Cause:** Missing required parameters or invalid values

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": [
    {
      "loc": ["body", "vehicle_fuel_id"],
      "msg": "Either vehicle_fuel_id or custom_emission_factor_id must be provided",
      "type": "value_error"
    }
  ]
}
```

**Solution:** Ensure all required fields are provided. Either `vehicle_fuel_id` or `custom_emission_factor_id` must be specified. Country code should be 2-3 characters.

## Use Cases

### Add a Passenger Vehicle to Fleet

Create a new company car with full details:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def add_company_car(license_plate, registration_year, fuel_type_id):
    """Add a new passenger vehicle to the fleet"""
    payload = {
        "name": f"Company Car - {license_plate}",
        "type": "passenger",
        "ownership": "owned",
        "license_plate": license_plate,
        "country": "ES",
        "unknown_vehicle_id": "550e8400-e29b-41d4-a716-446655440000",
        "vehicle_fuel_id": fuel_type_id,
        "registration_year": registration_year,
        "market_segment": "upper_medium"
    }

    response = requests.post(
        "https://api.dcycle.io/v1/vehicles",
        headers=headers,
        json=payload
    )

    return response.json()

# Add vehicle
vehicle = add_company_car("ABC-1234", 2022, "660e8400-e29b-41d4-a716-446655440000")
print(f"Created vehicle with CO2e: {vehicle['co2e']} kg")
```

### Register a Fleet Vehicle with Custom Emissions

Add a vehicle using a custom emission factor:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def add_custom_vehicle(license_plate, custom_factor_id):
    """Add a vehicle with custom emission factor"""
    payload = {
        "name": f"Fleet Vehicle - {license_plate}",
        "type": "freight",
        "ownership": "owned",
        "license_plate": license_plate,
        "country": "ES",
        "unknown_vehicle_id": "550e8400-e29b-41d4-a716-446655440001",
        "custom_emission_factor_id": custom_factor_id,
        "size": "large_car"
    }

    response = requests.post(
        "https://api.dcycle.io/v1/vehicles",
        headers=headers,
        json=payload
    )

    return response.json()
```

### Bulk Add Multiple Vehicles

Add multiple vehicles in a batch operation:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def bulk_add_vehicles(vehicles_data):
    """Add multiple vehicles to the fleet"""
    created_vehicles = []

    for vehicle_info in vehicles_data:
        response = requests.post(
            "https://api.dcycle.io/v1/vehicles",
            headers=headers,
            json=vehicle_info
        )

        if response.status_code == 201:
            created_vehicles.append(response.json())
        else:
            print(f"Failed to create vehicle: {response.text}")

    return created_vehicles

# Bulk add vehicles
vehicles = [
    {
        "name": "Vehicle 1",
        "type": "passenger",
        "ownership": "owned",
        "license_plate": "ABC-1234",
        "country": "ES",
        "unknown_vehicle_id": "550e8400-e29b-41d4-a716-446655440000",
        "vehicle_fuel_id": "660e8400-e29b-41d4-a716-446655440000"
    },
    {
        "name": "Vehicle 2",
        "type": "freight",
        "ownership": "rented",
        "license_plate": "XYZ-5678",
        "country": "ES",
        "unknown_vehicle_id": "550e8400-e29b-41d4-a716-446655440001",
        "vehicle_fuel_id": "760e8400-e29b-41d4-a716-446655440000"
    }
]

created = bulk_add_vehicles(vehicles)
print(f"Created {len(created)} vehicles")
```

## 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="Update Vehicle" icon="pencil" href="/api-reference/vehicles/update">
    Modify vehicle details
  </Card>

  <Card title="Unknown Vehicles" icon="question" href="/api-reference/unknown-vehicles/list">
    Get available vehicle types
  </Card>

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