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

# Logistics API

> Calculate and track CO2e emissions for freight transport and logistics operations following ISO 14083

# Logistics API

The Logistics API allows you to calculate, track, and report CO2e emissions for freight transport operations. Following the **ISO 14083** standard, it provides accurate Well-to-Wheel (WTW) emissions calculations for road, rail, maritime, and air transport.

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

## Key Features

* **ISO 14083 Compliant**: Calculations follow the international standard for transport emissions
* **Multiple Transport Modes**: Support for road, rail, maritime, and air freight
* **Flexible Distance Input**: Provide addresses for automatic calculation or direct distance values
* **Hub Integration**: Use registered logistics hubs as origin/destination points
* **Package Tracking**: Track emissions across multi-leg shipments with package aggregation
* **High-Volume Processing**: Bulk endpoint for processing up to 5,000 records per request
* **Client Segmentation**: Track emissions by client for reporting and billing

## Authentication

All endpoints require authentication using:

* **API Key**: Include in `x-api-key` header

## Headers

All requests must include:

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

## Available Endpoints

<CardGroup cols={2}>
  <Card title="Get Summary" icon="chart-pie" href="/api-reference/logistics/get-summary">
    Get counts and last updated timestamps
  </Card>

  <Card title="Get Vehicle Types (TOCs)" icon="truck" href="/api-reference/logistics/get-tocs">
    List available Transport Operation Categories
  </Card>

  <Card title="List Clients" icon="users" href="/api-reference/logistics/get-clients">
    Get all unique client identifiers
  </Card>

  <Card title="Generate Report" icon="chart-bar" href="/api-reference/logistics/get-report">
    Generate ISO 14083 emissions report
  </Card>

  <Card title="Create Request" icon="plus" href="/api-reference/logistics/create-request">
    Calculate emissions for a single shipment
  </Card>

  <Card title="Create Requests (Bulk)" icon="layer-group" href="/api-reference/logistics/create-requests-bulk">
    Process up to 5,000 shipments in one request
  </Card>

  <Card title="List Requests" icon="list" href="/api-reference/logistics/get-requests">
    Retrieve logistics requests with pagination
  </Card>

  <Card title="Delete Request" icon="trash" href="/api-reference/logistics/delete-request">
    Delete a single shipment request
  </Card>

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

  <Card title="Create Recharge" icon="plus" href="/api-reference/logistics/create-recharge">
    Create a single fuel consumption record
  </Card>

  <Card title="Create Recharges (Bulk)" icon="layer-group" href="/api-reference/logistics/create-recharges-bulk">
    Create up to 5,000 fuel consumption records
  </Card>

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

  <Card title="Delete Recharge" icon="trash" href="/api-reference/logistics/delete-recharge">
    Delete a single fuel consumption record
  </Card>

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

  <Card title="List Packages" icon="boxes-stacked" href="/api-reference/logistics/get-packages">
    Get packages with aggregated emissions
  </Card>

  <Card title="Get Package" icon="box" href="/api-reference/logistics/get-package">
    Get a specific package with all its legs
  </Card>
</CardGroup>

## Core Concepts

### Transport Operation Categories (TOCs)

ISO 14083 defines standard vehicle categories for emissions calculation:

| Category   | Examples                            | Typical Use            |
| ---------- | ----------------------------------- | ---------------------- |
| `road`     | van, rigid truck, articulated truck | Ground freight         |
| `rail`     | freight train                       | Bulk goods, intermodal |
| `maritime` | container ship, bulk carrier        | International shipping |
| `air`      | cargo aircraft                      | Express shipments      |

### Well-to-Wheel (WTW) Methodology

Emissions include the complete fuel cycle:

* **WTT (Well-to-Tank)**: Fuel extraction, refining, and distribution
* **TTW (Tank-to-Wheel)**: Direct combustion emissions

### Distance Calculation

When you provide `origin` and `destination` addresses instead of a direct `distance_km` value, Dcycle automatically calculates the route distance. The method depends on the transport mode:

| Transport mode               | Calculation method                                                                                                                |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| **Road**                     | Google Maps Distance Matrix API (driving route)                                                                                   |
| **Rail**                     | Google Maps Distance Matrix API (transit route)                                                                                   |
| **Air**                      | Haversine formula (great-circle straight-line distance)                                                                           |
| **Maritime (cross-country)** | CERDI sea-distance table (country-to-country navigable distance)                                                                  |
| **Maritime (same country)**  | Navigable-water graph (searoute) between the two points, falling back to straight-line haversine if the graph cannot find a route |

After the raw distance is obtained, a **Distance Adjustment Factor (DAF)** is applied to align with ISO 14083 methodology:

| Transport mode | DAF  |
| -------------- | ---- |
| Road           | 0.95 |
| Rail           | 1.0  |
| Maritime       | 0.85 |
| Air            | 1.0  |

Calculated distances are cached per route and transport mode. Submitting the same origin/destination pair again returns the cached result instantly without calling any external API.

<Tip>
  If you already know the exact distance (e.g., from your own routing system), pass `distance_km` directly. It will be used as-is, bypassing geocoding and routing entirely.
</Tip>

### Packages and Legs

* **Leg**: A single transport segment (origin → destination)
* **Package**: A tracked item that may travel through multiple legs
* **Package Key**: Unique identifier linking legs to a package

## Workflow

### Single Shipment Calculation

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

response = requests.post(
    "https://api.dcycle.io/v1/logistics/requests",
    headers={
        "x-api-key": api_key,
        "x-organization-id": org_id
    },
    json={
        "origin": "Madrid, Spain",
        "destination": "Barcelona, Spain",
        "load": 1000,
        "load_unit": "kg",
        "category": "road"
    }
)

result = response.json()
print(f"Distance: {result['distance_km']} km")
print(f"CO2e: {result['co2e']} kg")
```

### Bulk Processing

For high-volume operations (e.g., daily batch uploads):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
response = requests.post(
    "https://api.dcycle.io/v1/logistics/requests/bulk",
    headers=headers,
    json={
        "records": [
            {"origin": "Madrid", "destination": "Barcelona", "load": 500, "category": "road"},
            {"origin": "Madrid", "destination": "Valencia", "load": 300, "category": "road"},
            # ... up to 5,000 records
        ],
        "options": {"continue_on_error": True}
    }
)

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

### Multi-leg Package Tracking

Track a package through its journey:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Leg 1: Hub to regional center
requests.post(url, json={
    "origin": "Madrid Hub",
    "destination": "Valencia Hub",
    "package_key": "PKG-12345",
    "movement_id": "SHIP-001",
    "load": 15, "category": "road"
})

# Leg 2: Regional center to final destination
requests.post(url, json={
    "origin": "Valencia Hub",
    "destination": "Customer Address",
    "package_key": "PKG-12345",  # Same package
    "movement_id": "SHIP-001",
    "load": 15, "category": "road"
})

# Get aggregated package emissions
package = requests.get(f"{url}/packages?package_key=PKG-12345")
print(f"Total CO2e: {package.json()['items'][0]['total_co2e']} kg")
```

## Request Attributes

### Location Input

You can specify locations in two ways:

**Option 1: Addresses** (auto-calculate distance)

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "origin": "Madrid, Spain",
  "destination": "Barcelona, Spain"
}
```

**Option 2: Direct distance**

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "distance_km": 620
}
```

### Load Specification

* **load** (`number`): Cargo weight/quantity
* **load\_unit** (`string`): `kg`, `ton`, `pallets`, `teu`, `feu`
* **load\_factor** (`number`): Multiplier 0-1 (e.g., 0.5 for half load)

### Vehicle Selection

* **toc** (`string`): Specific vehicle type (e.g., `van_diesel`, `rigid_diesel`)
* **category** (`string`): General category if TOC unknown (`road`, `rail`, `maritime`, `air`)

### Traceability

* **movement\_id** (`string`): Unique shipment identifier
* **client** (`string`): Client/customer code
* **shipment\_date** (`date`): Date of shipment
* **package\_key** (`string`): Package identifier for multi-leg tracking

## Response Format

### Logistics Request Object

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "origin": "Madrid, Spain",
  "destination": "Barcelona, Spain",
  "distance_km": 621.5,
  "load": 1000,
  "load_unit": "kg",
  "category": "road",
  "toc": "generic_average_road",
  "co2e": 95.23,
  "tkm": 621.5,
  "movement_id": "SHIP-001",
  "client": "AMAZON",
  "package_id": "660e8400-e29b-41d4-a716-446655440000",
  "created_at": "2024-12-01T10:30:00Z"
}
```

### Package Object

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "id": "660e8400-e29b-41d4-a716-446655440000",
  "package_key": "PKG-12345",
  "total_distance_km": 850.0,
  "total_co2e": 130.45,
  "legs_count": 2,
  "created_at": "2024-12-01T10:30:00Z"
}
```

## Error Handling

### Common HTTP Status Codes

| Status | Meaning          | Solution                          |
| ------ | ---------------- | --------------------------------- |
| 200    | Success          | -                                 |
| 400    | Bad Request      | Check request parameters          |
| 401    | Unauthorized     | Verify API key                    |
| 404    | Not Found        | Check organization ID or resource |
| 422    | Validation Error | Review error details              |

### Error Response Format

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

### Common Validation Errors

| Error                         | Cause                       | Solution                                    |
| ----------------------------- | --------------------------- | ------------------------------------------- |
| `TOC not found`               | Invalid vehicle type        | Use `/tocs` endpoint to get valid options   |
| `Load not found`              | Missing load and no default | Provide `load` parameter                    |
| `Distance calculation failed` | Invalid addresses           | Use `distance_km` directly or fix addresses |

## Use Cases

### Logistics Provider Daily Upload

Process daily shipment data:

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

# Load daily shipments from CSV
df = pd.read_csv("daily_shipments.csv")

records = df.to_dict(orient="records")

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

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

### Client Emissions Report

Generate emissions report for a specific client:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
report = requests.get(
    "https://api.dcycle.io/v1/logistics/report",
    headers=headers,
    params={
        "start_date": "2024-01-01",
        "end_date": "2024-12-31",
        "client": "AMAZON"
    }
)

data = report.json()
print(f"Total CO2e: {data['summary']['total_co2e_kg']} kg")
print(f"Total packages: {data['summary']['total_items']}")
```

## GHG Protocol Context

Logistics emissions typically fall under **Scope 3** of the GHG Protocol:

* **Category 4**: Upstream Transportation and Distribution
* **Category 9**: Downstream Transportation and Distribution

The classification depends on who pays for the transport:

* **Category 4**: Transport paid by your organization (inbound logistics)
* **Category 9**: Transport paid by customers (outbound logistics)

## Related Documentation

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

  <Card title="Logistics Tutorial" icon="graduation-cap" href="/guides/emissions/logistics-tutorial">
    Step-by-step guide to logistics emissions
  </Card>

  <Card title="Vehicles API" icon="car" href="/api-reference/vehicles/overview">
    Manage fleet vehicles and their emissions
  </Card>

  <Card title="Business Travels API" icon="plane" href="/api-reference/business-travels/overview">
    Track employee travel emissions
  </Card>

  <Card title="MCP Tools" icon="robot" href="/mcp/logistics">
    Query logistics data from AI assistants via MCP
  </Card>
</CardGroup>

## Rate Limiting

API requests are subject to rate limiting:

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

<Tip>
  For high-volume processing, use the bulk endpoint to minimize API calls and improve throughput.
</Tip>
