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

# Generate Report

> Generate an ISO 14083 emissions report for a specified period

# Generate ISO 14083 Report

Generate a complete logistics emissions report following ISO 14083 methodology. Includes aggregated KPIs, breakdowns by transport category, fleet-type analysis, and electrification savings.

<Note>
  **New API**: This endpoint is part of the new API architecture with improved design and maintainability. It automatically detects whether to use packages (new API) or requests (legacy API) based on your data.
</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>

### Query Parameters

<ParamField query="start_date" type="string" required>
  Period start date (format: YYYY-MM-DD)

  **Example:** `2025-01-01`
</ParamField>

<ParamField query="end_date" type="string" required>
  Period end date (format: YYYY-MM-DD)

  **Example:** `2025-12-31`
</ParamField>

<ParamField query="client" type="string">
  Filter by client identifier (optional)

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

<ParamField query="project_id" type="uuid">
  Filter the report by project UUID

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

## Response

<ResponseField name="client" type="string">
  Client filter applied (null if not filtered)
</ResponseField>

<ResponseField name="period" type="object">
  <Expandable title="properties">
    <ResponseField name="start_date" type="date">
      Start date (YYYY-MM-DD)
    </ResponseField>

    <ResponseField name="end_date" type="date">
      End date (YYYY-MM-DD)
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="summary" type="object">
  <Expandable title="properties">
    <ResponseField name="total_items" type="integer">
      Total number of packages (new API) or shipments (legacy)
    </ResponseField>

    <ResponseField name="total_co2e_kg" type="number">
      Total emissions in kg CO2e
    </ResponseField>

    <ResponseField name="total_distance_km" type="number">
      Total distance in km
    </ResponseField>

    <ResponseField name="avg_co2e_per_item" type="number">
      Average CO2e per package/shipment
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="by_category" type="array">
  Breakdown by transport category

  <Expandable title="properties">
    <ResponseField name="category" type="string">
      Transport category (road, rail, maritime, air)
    </ResponseField>

    <ResponseField name="items" type="integer">
      Number of packages/shipments
    </ResponseField>

    <ResponseField name="co2e_kg" type="number">
      Emissions in kg CO2e
    </ResponseField>

    <ResponseField name="distance_km" type="number">
      Distance in km
    </ResponseField>

    <ResponseField name="percentage_co2e" type="number">
      Percentage of total emissions
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="by_fleet_type" type="array">
  Breakdown by fleet type — cross-tabulation of ownership (own vs third-party) and energy type (conventional, electrified, renewable)

  <Expandable title="properties">
    <ResponseField name="fleet_type" type="string">
      Fleet type key in format `{ownership}_{energy}`. Possible values: `own_conventional`, `own_electrified`, `own_renewable`, `third_party_conventional`, `third_party_electrified`, `third_party_renewable`, `own_unknown`, `third_party_unknown`
    </ResponseField>

    <ResponseField name="items" type="integer">
      Number of shipments/legs
    </ResponseField>

    <ResponseField name="co2e_kg" type="number">
      Emissions in kg CO2e
    </ResponseField>

    <ResponseField name="distance_km" type="number">
      Distance in km
    </ResponseField>

    <ResponseField name="percentage_items" type="number">
      Percentage of total trips
    </ResponseField>

    <ResponseField name="percentage_distance" type="number">
      Percentage of total distance
    </ResponseField>

    <ResponseField name="percentage_co2e" type="number">
      Percentage of total CO2e
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="electrification_savings" type="object">
  Electrification savings analysis comparing actual electric trip emissions vs hypothetical diesel equivalent. `null` when no electric trips exist in the period.

  <Expandable title="properties">
    <ResponseField name="electric_trips" type="integer">
      Number of electric trips/legs
    </ResponseField>

    <ResponseField name="actual_co2e_kg" type="number">
      Actual CO2e from electric trips (kg)
    </ResponseField>

    <ResponseField name="hypothetical_diesel_co2e_kg" type="number">
      Hypothetical CO2e if those trips used diesel equivalents (kg)
    </ResponseField>

    <ResponseField name="avoided_co2e_kg" type="number">
      CO2e avoided vs diesel (can be negative if electric WTW exceeds diesel WTW)
    </ResponseField>

    <ResponseField name="percentage_reduction" type="number">
      Percentage reduction vs diesel
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="data_source" type="string">
  Source of data: `packages` (new API) or `requests` (legacy API)
</ResponseField>

<ResponseField name="methodology" type="string">
  Methodology used (always "ISO 14083")
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET "https://api.dcycle.io/v1/logistics/report?start_date=2025-01-01&end_date=2025-12-31&client=AMAZON" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}"
  ```

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

  params = {
      "start_date": "2025-01-01",
      "end_date": "2025-12-31",
      "client": "AMAZON"  # Optional
  }

  response = requests.get(
      "https://api.dcycle.io/v1/logistics/report",
      headers=headers,
      params=params
  )

  report = response.json()
  print(f"Total CO2e: {report['summary']['total_co2e_kg']:.2f} kg")
  print(f"Total packages: {report['summary']['total_items']}")
  print(f"Data source: {report['data_source']}")

  # Fleet type breakdown
  for ft in report.get("by_fleet_type", []):
      print(f"  {ft['fleet_type']}: {ft['co2e_kg']:.2f} kg ({ft['percentage_co2e']}%)")

  # Electrification savings
  savings = report.get("electrification_savings")
  if savings:
      print(f"Electric trips: {savings['electric_trips']}")
      print(f"CO2e avoided: {savings['avoided_co2e_kg']:.2f} kg ({savings['percentage_reduction']}% reduction)")
  ```

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

  const params = {
    start_date: '2025-01-01',
    end_date: '2025-12-31',
    client: 'AMAZON'  // Optional
  };

  axios.get(
    'https://api.dcycle.io/v1/logistics/report',
    { headers, params }
  )
  .then(response => {
    const { summary, by_fleet_type, electrification_savings, data_source } = response.data;
    console.log(`Total CO2e: ${summary.total_co2e_kg.toFixed(2)} kg`);
    console.log(`Total packages: ${summary.total_items}`);
    console.log(`Data source: ${data_source}`);

    by_fleet_type.forEach(ft => {
      console.log(`  ${ft.fleet_type}: ${ft.co2e_kg.toFixed(2)} kg (${ft.percentage_co2e}%)`);
    });

    if (electrification_savings) {
      console.log(`CO2e avoided: ${electrification_savings.avoided_co2e_kg.toFixed(2)} kg`);
    }
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "client": "AMAZON",
  "period": {
    "start_date": "2025-01-01",
    "end_date": "2025-12-31"
  },
  "summary": {
    "total_items": 1500,
    "total_co2e_kg": 12500.50,
    "total_distance_km": 45000.00,
    "avg_co2e_per_item": 8.3337
  },
  "by_category": [
    {
      "category": "road",
      "items": 1400,
      "co2e_kg": 11000.00,
      "distance_km": 40000.00,
      "percentage_co2e": 88.0
    },
    {
      "category": "rail",
      "items": 100,
      "co2e_kg": 1500.50,
      "distance_km": 5000.00,
      "percentage_co2e": 12.0
    }
  ],
  "by_fleet_type": [
    {
      "fleet_type": "own_conventional",
      "items": 900,
      "co2e_kg": 8500.00,
      "distance_km": 28000.00,
      "percentage_items": 60.0,
      "percentage_distance": 62.2,
      "percentage_co2e": 68.0
    },
    {
      "fleet_type": "own_electrified",
      "items": 200,
      "co2e_kg": 400.50,
      "distance_km": 5000.00,
      "percentage_items": 13.3,
      "percentage_distance": 11.1,
      "percentage_co2e": 3.2
    },
    {
      "fleet_type": "third_party_conventional",
      "items": 400,
      "co2e_kg": 3600.00,
      "distance_km": 12000.00,
      "percentage_items": 26.7,
      "percentage_distance": 26.7,
      "percentage_co2e": 28.8
    }
  ],
  "electrification_savings": {
    "electric_trips": 200,
    "actual_co2e_kg": 400.50,
    "hypothetical_diesel_co2e_kg": 2800.00,
    "avoided_co2e_kg": 2399.50,
    "percentage_reduction": 85.7
  },
  "data_source": "packages",
  "methodology": "ISO 14083"
}
```

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

### 404 Not Found

**Cause:** Organization not found

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

### 422 Validation Error

**Cause:** Invalid date format

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Invalid date format. Use YYYY-MM-DD"
}
```

**Solution:** Use the `YYYY-MM-DD` format (for example: `2025-01-01`)

## Use Cases

### Annual Report

Generate the complete annual report for sustainability audits:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def generate_annual_report(year, client=None):
    """Generate annual ISO 14083 report"""
    params = {
        "start_date": f"{year}-01-01",
        "end_date": f"{year}-12-31"
    }
    if client:
        params["client"] = client

    response = requests.get(
        "https://api.dcycle.io/v1/logistics/report",
        headers=headers,
        params=params
    )

    report = response.json()

    # Convert to tonnes for reporting
    total_tonnes = report['summary']['total_co2e_kg'] / 1000

    print(f"Annual Emissions Report {year}")
    print("=" * 40)
    print(f"Total emissions: {total_tonnes:.2f} tCO2e")
    print(f"Total packages: {report['summary']['total_items']}")
    print(f"Average per package: {report['summary']['avg_co2e_per_item']:.2f} kgCO2e")

    return report

# Generate for all clients
annual = generate_annual_report(2025)

# Generate for specific client
amazon_report = generate_annual_report(2025, client="AMAZON")
```

### Monthly Comparison

Compare emissions month by month:

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

def monthly_comparison(year, client=None):
    """Compare emissions by month"""
    monthly_data = []

    for month in range(1, 13):
        last_day = calendar.monthrange(year, month)[1]

        params = {
            "start_date": f"{year}-{month:02d}-01",
            "end_date": f"{year}-{month:02d}-{last_day}"
        }
        if client:
            params["client"] = client

        response = requests.get(
            "https://api.dcycle.io/v1/logistics/report",
            headers=headers,
            params=params
        )

        report = response.json()

        monthly_data.append({
            "month": calendar.month_name[month],
            "co2e_kg": report['summary']['total_co2e_kg'],
            "packages": report['summary']['total_items']
        })

    return monthly_data

# Usage
comparison = monthly_comparison(2025, client="AMAZON")
for month_data in comparison:
    print(f"{month_data['month']}: {month_data['co2e_kg']:.2f} kgCO2e ({month_data['packages']} packages)")
```

### Compare Clients

Compare emissions across different clients:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def compare_clients(start_date, end_date):
    """Compare emissions across all clients"""
    # First, get all clients
    clients_response = requests.get(
        "https://api.dcycle.io/v1/logistics/clients",
        headers=headers
    )
    clients = clients_response.json()

    comparison = []
    for client in clients:
        response = requests.get(
            "https://api.dcycle.io/v1/logistics/report",
            headers=headers,
            params={
                "start_date": start_date,
                "end_date": end_date,
                "client": client
            }
        )
        report = response.json()

        comparison.append({
            "client": client,
            "total_co2e_kg": report['summary']['total_co2e_kg'],
            "packages": report['summary']['total_items'],
            "avg_per_package": report['summary']['avg_co2e_per_item']
        })

    # Sort by emissions (highest first)
    comparison.sort(key=lambda x: x['total_co2e_kg'], reverse=True)

    return comparison

# Usage
client_comparison = compare_clients("2025-01-01", "2025-12-31")
for c in client_comparison:
    print(f"{c['client']}: {c['total_co2e_kg']:.2f} kgCO2e ({c['packages']} packages)")
```

### Fleet & Electrification Analysis

Analyze fleet composition and electrification impact:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def fleet_electrification_report(year, client=None):
    """Analyze fleet composition and electrification savings"""
    params = {
        "start_date": f"{year}-01-01",
        "end_date": f"{year}-12-31"
    }
    if client:
        params["client"] = client

    response = requests.get(
        "https://api.dcycle.io/v1/logistics/report",
        headers=headers,
        params=params
    )

    report = response.json()

    # Fleet type breakdown
    print("Fleet Composition")
    print("=" * 50)
    for ft in report.get("by_fleet_type", []):
        print(f"  {ft['fleet_type']:30s} {ft['items']:>6} trips  {ft['co2e_kg']:>10.2f} kgCO2e  ({ft['percentage_co2e']}%)")

    # Electrification savings
    savings = report.get("electrification_savings")
    if savings:
        print(f"\nElectrification Savings")
        print("=" * 50)
        print(f"  Electric trips:        {savings['electric_trips']}")
        print(f"  Actual emissions:      {savings['actual_co2e_kg']:.2f} kgCO2e")
        print(f"  Diesel equivalent:     {savings['hypothetical_diesel_co2e_kg']:.2f} kgCO2e")
        print(f"  CO2e avoided:          {savings['avoided_co2e_kg']:.2f} kgCO2e")
        print(f"  Reduction:             {savings['percentage_reduction']}%")
    else:
        print("\nNo electric trips in this period.")

    return report

# Usage
fleet_electrification_report(2025, client="AMAZON")
```

## Data Source Detection

The endpoint automatically detects which data source to use:

<CardGroup cols={2}>
  <Card title="Packages (New API)" icon="box">
    Used when you have data created via `POST /v1/logistics/requests` with package tracking.

    * Aggregates from `logistic_packages` table
    * Pre-calculated CO2e per package
    * `data_source: "packages"`
  </Card>

  <Card title="Requests (Legacy API)" icon="truck">
    Used when you have data from the legacy logistics API.

    * Aggregates from `logistic_requests` table
    * CO2e calculated on-the-fly (tkm \* emission factor)
    * `data_source: "requests"`
  </Card>
</CardGroup>

## ISO 14083 Compliance

This report complies with ISO 14083:2023 standard requirements:

* **WTW (Well-to-Wheel) Emissions** - Includes complete fuel cycle emissions
* **Transport Mode Breakdown** - Clear separation by transport category
* **Traceability** - Each emission is linked to specific packages/shipments
* **Documented Methodology** - Transparent emission factors and calculations
* **Temporal Aggregation** - Reports by defined periods

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Export Detailed Report" icon="file-export" href="/api-reference/logistics/get-report-export">
    Queue an async, line-level export emailed as a download link
  </Card>

  <Card title="List Clients" icon="list" href="/api-reference/logistics/get-clients">
    Get available clients for filtering
  </Card>

  <Card title="Get Packages" icon="box" href="/api-reference/logistics/get-packages">
    View individual packages
  </Card>

  <Card title="Create Request" icon="calculator" href="/api-reference/logistics/create-request">
    Create new logistics requests
  </Card>

  <Card title="Get Vehicle Types" icon="truck" href="/api-reference/logistics/get-tocs">
    View available vehicle types and emission factors
  </Card>
</CardGroup>
