> ## 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 Logistics Recharges (Bulk)

> Create multiple logistics recharges (fuel consumption records) in a single request

# Create Logistics Recharges (Bulk)

Create multiple fuel consumption records in a single API call. Optimized for batch processing of up to 5,000 records per request.

## 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="records" type="array" required>
  Array of recharge records to create (1 to 5,000). Each record uses the same format as the single POST /recharges endpoint.

  Each record contains:

  * `fuel_id` (string, required): UUID of the fuel type
  * `country` (string, required): ISO 3166-1 alpha-2 country code
  * `date` (string, required): Date in YYYY-MM-DD format
  * `quantity` (number): Amount of fuel consumed
  * `vehicle_license_plate` (string): Vehicle license plate
  * `toc_id` (string): UUID of the vehicle type
  * `project_id` (string): UUID of a project to associate with
</ParamField>

<ParamField body="options" type="object">
  Processing options for the bulk operation.

  * `continue_on_error` (boolean, default: `true`): If `true`, continues processing remaining records even if some fail. If `false`, stops at the first error.
</ParamField>

## Response

Returns a summary of the bulk operation with HTTP 201.

<ResponseField name="created" type="integer">
  Number of successfully created recharges
</ResponseField>

<ResponseField name="updated" type="integer">
  Number of recharges that matched an existing record and were updated (upsert)
</ResponseField>

<ResponseField name="errors" type="array">
  Array of error objects for records that failed to process

  <Expandable title="Error object">
    <ResponseField name="index" type="integer">Zero-based index of the failed record in the input array</ResponseField>
    <ResponseField name="message" type="string">Description of the error</ResponseField>
  </Expandable>
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X POST "https://api.dcycle.io/v1/logistics/recharges/bulk" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}" \
    -H "Content-Type: application/json" \
    -d '{
      "records": [
        {
          "fuel_id": "550e8400-e29b-41d4-a716-446655440000",
          "country": "ES",
          "date": "2025-06-15",
          "quantity": 50.0,
          "vehicle_license_plate": "1234-ABC"
        },
        {
          "fuel_id": "550e8400-e29b-41d4-a716-446655440000",
          "country": "ES",
          "date": "2025-06-16",
          "quantity": 60.0,
          "vehicle_license_plate": "5678-XYZ"
        }
      ],
      "options": { "continue_on_error": true }
    }'
  ```

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

  response = requests.post(
      "https://api.dcycle.io/v1/logistics/recharges/bulk",
      headers=headers,
      json={
          "records": [
              {
                  "fuel_id": "550e8400-e29b-41d4-a716-446655440000",
                  "country": "ES",
                  "date": "2025-06-15",
                  "quantity": 50.0,
                  "vehicle_license_plate": "1234-ABC"
              },
              {
                  "fuel_id": "550e8400-e29b-41d4-a716-446655440000",
                  "country": "ES",
                  "date": "2025-06-16",
                  "quantity": 60.0,
                  "vehicle_license_plate": "5678-XYZ"
              }
          ],
          "options": {"continue_on_error": True}
      }
  )

  result = response.json()
  print(f"Success: {result['success']}, Failed: {result['failed']}")

  for item in result['results']:
      print(f"  Record {item['index']}: {item['id']}")

  for error in result['errors']:
      print(f"  Error at {error['index']}: {error['error']}")
  ```

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

  axios.post(
    'https://api.dcycle.io/v1/logistics/recharges/bulk',
    {
      records: [
        {
          fuel_id: '550e8400-e29b-41d4-a716-446655440000',
          country: 'ES',
          date: '2025-06-15',
          quantity: 50.0,
          vehicle_license_plate: '1234-ABC'
        },
        {
          fuel_id: '550e8400-e29b-41d4-a716-446655440000',
          country: 'ES',
          date: '2025-06-16',
          quantity: 60.0,
          vehicle_license_plate: '5678-XYZ'
        }
      ],
      options: { continue_on_error: true }
    },
    { headers }
  )
  .then(response => {
    const { success, failed } = response.data;
    console.log(`Success: ${success}, Failed: ${failed}`);
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "total_received": 3,
  "total_processed": 3,
  "success": 2,
  "failed": 1,
  "results": [
    { "index": 0, "id": "660e8400-e29b-41d4-a716-446655440000" },
    { "index": 2, "id": "770e8400-e29b-41d4-a716-446655440000" }
  ],
  "errors": [
    { "index": 1, "error": "Fuel with id '...' not found or inactive" }
  ]
}
```

| Field             | Type    | Description                                   |
| ----------------- | ------- | --------------------------------------------- |
| `total_received`  | integer | Number of records in the request              |
| `total_processed` | integer | Records processed (success + failed)          |
| `success`         | integer | Records created/updated successfully          |
| `failed`          | integer | Records that failed validation                |
| `results`         | array   | Successfully processed records with their IDs |
| `errors`          | array   | Error details for failed records              |

### Upsert Behavior

Records with the same combination of `country`, `date`, `quantity`, and `vehicle_license_plate` within the organization are updated instead of duplicated. This matches the deduplication behavior of CSV file uploads.

### Daily Batch Upload from CSV

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import pandas as pd
import requests

df = pd.read_csv("daily_recharges.csv")

records = [
    {
        "fuel_id": row["fuel_id"],
        "country": row["country"],
        "date": row["date"],
        "quantity": row["quantity"],
        "vehicle_license_plate": row["plate"]
    }
    for _, row in df.iterrows()
]

response = requests.post(
    "https://api.dcycle.io/v1/logistics/recharges/bulk",
    headers=headers,
    json={"records": records, "options": {"continue_on_error": True}}
)

result = response.json()
print(f"Processed: {result['success']}/{result['total_received']}")
```

## Common Errors

### 401 Unauthorized

**Cause:** Missing or invalid API key

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{"detail": "Invalid API key for organization", "code": "INVALID_API_KEY"}
```

### 403 Forbidden

**Cause:** The authenticated user is not a member of the organization

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{"detail": "Logged User is not Member of Organization", "code": "LOGGED_USER_NOT_MEMBER"}
```

### 422 Validation Error

**Cause:** Empty records array or exceeding 5,000 records.

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": [
    {
      "loc": ["body", "records"],
      "msg": "ensure this value has at most 5000 items"
    }
  ]
}
```

### Partial Failures

When `continue_on_error` is `true` (default), individual record failures are reported in the `errors` array while successfully processed records are included in `results`. Common per-record errors:

* Invalid `fuel_id`: Fuel not found or inactive
* Invalid `country`: Not Valid Country Code, must be ISO 3166-1 alpha-2

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Create Recharge" icon="plus" href="/api-reference/logistics/create-recharge">
    Create a single recharge
  </Card>

  <Card title="List Recharges" icon="gas-pump" href="/api-reference/logistics/get-recharges">
    Retrieve fuel consumption records
  </Card>

  <Card title="Batch Delete Recharges" icon="trash-can" href="/api-reference/logistics/batch-delete-recharges">
    Delete multiple recharges at once
  </Card>

  <Card title="Create Requests (Bulk)" icon="layer-group" href="/api-reference/logistics/create-requests-bulk">
    Bulk create shipment requests
  </Card>
</CardGroup>
