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

# Get Packages

> Retrieve a paginated list of logistics packages with aggregated emissions

# Get Packages

Retrieve all logistics packages created by your organization with pagination support. Packages group multiple legs of a shipment and provide aggregated distance and emissions data.

<Note>
  **New API**: This endpoint is part of the new API architecture with improved design and maintainability.
</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="page" type="integer" default="1">
  Page number to retrieve

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

<ParamField query="size" type="integer" default="10">
  Number of items per page (1-100)

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

<ParamField query="movement_id" type="string">
  Filter packages by movement ID (shipment identifier). Use this to get all packages belonging to a specific shipment.

  **Example:** `SHIP-2024-001`
</ParamField>

<ParamField query="client" type="string">
  Filter packages by client identifier. Use this to get all packages for a specific client (e.g., corporate customers like Amazon).

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

<ParamField query="package_key" type="string">
  Filter by package key to find a specific package. Useful when you have the package identifier from a label or tracking system.

  **Note:** When filtering by `package_key`, the response includes the `legs` array with the complete journey details.

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

## Response

<ResponseField name="page" type="integer">
  Current page number
</ResponseField>

<ResponseField name="size" type="integer">
  Number of items per page
</ResponseField>

<ResponseField name="total" type="integer">
  Total number of packages
</ResponseField>

<ResponseField name="items" type="array">
  Array of package objects

  <Expandable title="Package Object">
    <ResponseField name="id" type="string">
      Unique identifier for the package (UUID)
    </ResponseField>

    <ResponseField name="shipment_id" type="string">
      Shipment identifier (groups packages from the same shipment)
    </ResponseField>

    <ResponseField name="package_key" type="string">
      Unique package identifier provided during creation
    </ResponseField>

    <ResponseField name="client_billing_id" type="string">
      Client billing identifier (optional)
    </ResponseField>

    <ResponseField name="weight_kg" type="number">
      Package weight in kilograms
    </ResponseField>

    <ResponseField name="total_distance_km" type="number">
      Total distance across all legs in kilometers
    </ResponseField>

    <ResponseField name="total_co2e" type="number">
      Total CO2 equivalent emissions across all legs in kilograms
    </ResponseField>

    <ResponseField name="status" type="string">
      Package status (active, inactive)
    </ResponseField>

    <ResponseField name="created_at" type="datetime">
      Timestamp when the package was created
    </ResponseField>

    <ResponseField name="updated_at" type="datetime | null">
      Timestamp when the package was last updated
    </ResponseField>
  </Expandable>
</ResponseField>

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET "https://api.dcycle.io/v1/logistics/packages?page=1&size=10" \
    -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 = {
      "page": 1,
      "size": 10
  }

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

  result = response.json()
  print(f"Total packages: {result['total']}")
  for pkg in result['items']:
      print(f"  - Package {pkg['package_key']}: {pkg['total_co2e']:.2f} kg CO2e")
  ```

  ```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 = {
    page: 1,
    size: 10
  };

  axios.get(
    'https://api.dcycle.io/v1/logistics/packages',
    { headers, params }
  )
  .then(response => {
    console.log(`Total packages: ${response.data.total}`);
    response.data.items.forEach(pkg => {
      console.log(`  - Package ${pkg.package_key}: ${pkg.total_co2e?.toFixed(2)} kg CO2e`);
    });
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Filter by Shipment

Get all packages for a specific shipment:

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET "https://api.dcycle.io/v1/logistics/packages?movement_id=SHIP-2024-001" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}"
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  # Get all packages for a specific shipment
  response = requests.get(
      "https://api.dcycle.io/v1/logistics/packages",
      headers=headers,
      params={"movement_id": "SHIP-2024-001"}
  )

  shipment_packages = response.json()
  total_emissions = sum(pkg['total_co2e'] or 0 for pkg in shipment_packages['items'])
  print(f"Shipment total emissions: {total_emissions:.2f} kg CO2e")
  ```
</CodeGroup>

### Filter by Client (Corporate Customer Report)

Get all packages for a specific client like Amazon to generate their environmental impact report:

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET "https://api.dcycle.io/v1/logistics/packages?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"}}
  # Get all packages for Amazon
  response = requests.get(
      "https://api.dcycle.io/v1/logistics/packages",
      headers=headers,
      params={"client": "AMAZON", "size": 100}
  )

  amazon_packages = response.json()
  total_co2e = sum(pkg['total_co2e'] or 0 for pkg in amazon_packages['items'])
  total_distance = sum(pkg['total_distance_km'] or 0 for pkg in amazon_packages['items'])

  print(f"Amazon Environmental Report:")
  print(f"  Total packages: {amazon_packages['total']}")
  print(f"  Total distance: {total_distance:.2f} km")
  print(f"  Total emissions: {total_co2e:.2f} kg CO2e")
  ```
</CodeGroup>

### Find Package by Key (with Complete Journey)

Find a specific package using its key from the shipping label. When filtering by `package_key`, the response includes the complete journey with all legs:

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X GET "https://api.dcycle.io/v1/logistics/packages?package_key=26830007899150601093463" \
    -H "x-api-key: ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}"
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  # Find package by its key (from label) - includes journey details
  package_key = "26830007899150601093463"
  response = requests.get(
      "https://api.dcycle.io/v1/logistics/packages",
      headers=headers,
      params={"package_key": package_key}
  )

  result = response.json()
  if result['items']:
      package = result['items'][0]
      print(f"Package {package_key}:")
      print(f"  Total distance: {package['total_distance_km']:.2f} km")
      print(f"  CO2e emissions: {package['total_co2e']:.2f} kg")

      # Journey details are included when filtering by package_key
      if package.get('legs'):
          print(f"\n  Journey ({len(package['legs'])} legs):")
          for i, leg in enumerate(package['legs'], 1):
              print(f"    {i}. {leg['origin']} → {leg['destination']}")
              print(f"       Distance: {leg['distance_km']:.1f} km | CO2e: {leg['co2e']:.2f} kg")
  else:
      print(f"Package {package_key} not found")
  ```
</CodeGroup>

Response when filtering by `package_key`:

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "page": 1,
  "size": 10,
  "total": 1,
  "items": [
    {
      "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "shipment_id": "SHIP-2024-001",
      "package_key": "26830007899150601093463",
      "weight_kg": 15.0,
      "total_distance_km": 850.5,
      "total_co2e": 42.75,
      "status": "active",
      "legs": [
        {
          "id": "leg-uuid-1",
          "origin": "Madrid Hub",
          "destination": "Valencia Hub",
          "distance_km": 350.2,
          "co2e": 17.51
        },
        {
          "id": "leg-uuid-2",
          "origin": "Valencia Hub",
          "destination": "Barcelona Hub",
          "distance_km": 350.3,
          "co2e": 17.52
        },
        {
          "id": "leg-uuid-3",
          "origin": "Barcelona Hub",
          "destination": "Final Address, Barcelona",
          "distance_km": 150.0,
          "co2e": 7.72
        }
      ]
    }
  ]
}
```

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "page": 1,
  "size": 10,
  "total": 25,
  "items": [
    {
      "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "shipment_id": "SHIP-2024-001",
      "package_key": "PKG-2024-123456",
      "client_billing_id": "CLIENT-001",
      "weight_kg": 15.0,
      "total_distance_km": 850.5,
      "total_co2e": 42.75,
      "status": "active",
      "created_at": "2024-11-24T10:30:00Z",
      "updated_at": "2024-11-24T14:45:00Z"
    },
    {
      "id": "b2c3d4e5-f6a7-8901-bcde-f23456789012",
      "shipment_id": "SHIP-2024-001",
      "package_key": "PKG-2024-123457",
      "client_billing_id": "CLIENT-001",
      "weight_kg": 22.5,
      "total_distance_km": 850.5,
      "total_co2e": 64.12,
      "status": "active",
      "created_at": "2024-11-24T10:31:00Z",
      "updated_at": "2024-11-24T14:46: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

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

## Use Cases

### Corporate Client Environmental Report

Generate an environmental impact report for a corporate client (e.g., Amazon requesting their carbon footprint from your logistics operations):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def generate_client_environmental_report(client_name: str) -> dict:
    """Generate environmental impact report for a corporate client"""
    all_packages = []
    page = 1

    # Paginate through all packages for this client
    while True:
        response = requests.get(
            "https://api.dcycle.io/v1/logistics/packages",
            headers=headers,
            params={"client": client_name, "page": page, "size": 100}
        )

        data = response.json()
        all_packages.extend(data['items'])

        if len(data['items']) < 100:
            break
        page += 1

    # Calculate totals
    total_packages = len(all_packages)
    total_weight = sum(pkg['weight_kg'] or 0 for pkg in all_packages)
    total_distance = sum(pkg['total_distance_km'] or 0 for pkg in all_packages)
    total_co2e = sum(pkg['total_co2e'] or 0 for pkg in all_packages)

    return {
        "client": client_name,
        "report_date": datetime.now().isoformat(),
        "total_packages": total_packages,
        "total_weight_kg": total_weight,
        "total_distance_km": total_distance,
        "total_co2e_kg": total_co2e,
        "avg_co2e_per_package": total_co2e / total_packages if total_packages > 0 else 0,
    }

# Example: Generate report for Amazon
report = generate_client_environmental_report("AMAZON")
print(f"=== Environmental Report for {report['client']} ===")
print(f"Packages delivered: {report['total_packages']}")
print(f"Total weight transported: {report['total_weight_kg']:.2f} kg")
print(f"Total distance: {report['total_distance_km']:.2f} km")
print(f"Total CO2e emissions: {report['total_co2e_kg']:.2f} kg")
print(f"Average emissions per package: {report['avg_co2e_per_package']:.2f} kg CO2e")
```

### End Customer Package Impact (Label Lookup)

Provide environmental impact information to an end customer who received a package. The customer can look up their package using the tracking code from the label:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_package_impact_for_customer(package_key: str) -> dict:
    """Get package environmental impact for end customer display"""
    # Find the package by its key
    response = requests.get(
        "https://api.dcycle.io/v1/logistics/packages",
        headers=headers,
        params={"package_key": package_key}
    )

    result = response.json()

    if not result['items']:
        return {"error": "Package not found"}

    package = result['items'][0]

    # Get detailed journey if needed
    detail_response = requests.get(
        f"https://api.dcycle.io/v1/logistics/packages/{package['id']}",
        headers=headers
    )
    package_detail = detail_response.json()

    # Build customer-friendly response
    return {
        "package_key": package_key,
        "total_distance_km": package['total_distance_km'],
        "total_co2e_kg": package['total_co2e'],
        "journey_legs": len(package_detail.get('legs', [])),
        "environmental_context": {
            "equivalent_car_km": package['total_co2e'] / 0.12 if package['total_co2e'] else 0,  # ~120g CO2/km for avg car
            "equivalent_trees_day": package['total_co2e'] / 0.022 if package['total_co2e'] else 0,  # ~22g CO2 absorbed per tree per day
        }
    }

# Example: Customer Pedro looks up his package
package_info = get_package_impact_for_customer("26830007899150601093463")
if "error" not in package_info:
    print(f"Your package traveled {package_info['total_distance_km']:.0f} km")
    print(f"Carbon footprint: {package_info['total_co2e_kg']:.2f} kg CO2e")
    print(f"Equivalent to driving a car {package_info['environmental_context']['equivalent_car_km']:.1f} km")
```

### Calculate Shipment Total Emissions

Get total emissions for all packages in a shipment:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_shipment_emissions(movement_id: str) -> dict:
    """Calculate total emissions for a shipment"""
    response = requests.get(
        "https://api.dcycle.io/v1/logistics/packages",
        headers=headers,
        params={"movement_id": movement_id}
    )

    data = response.json()

    total_distance = sum(pkg['total_distance_km'] or 0 for pkg in data['items'])
    total_co2e = sum(pkg['total_co2e'] or 0 for pkg in data['items'])
    total_weight = sum(pkg['weight_kg'] or 0 for pkg in data['items'])

    return {
        "movement_id": movement_id,
        "package_count": len(data['items']),
        "total_weight_kg": total_weight,
        "total_distance_km": total_distance,
        "total_co2e_kg": total_co2e
    }

# Example usage
shipment_summary = get_shipment_emissions("SHIP-2024-001")
print(f"Shipment {shipment_summary['movement_id']}:")
print(f"  Packages: {shipment_summary['package_count']}")
print(f"  Total weight: {shipment_summary['total_weight_kg']:.2f} kg")
print(f"  Total emissions: {shipment_summary['total_co2e_kg']:.2f} kg CO2e")
```

### Export Packages Report

Generate a report of all packages with their emissions:

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

def export_packages_report(filename="packages_report.csv"):
    """Export all packages to CSV report"""
    all_packages = []
    page = 1

    while True:
        response = requests.get(
            "https://api.dcycle.io/v1/logistics/packages",
            headers=headers,
            params={"page": page, "size": 100}
        )

        data = response.json()
        all_packages.extend(data['items'])

        if len(data['items']) < data['size']:
            break
        page += 1

    fields = ['package_key', 'shipment_id', 'weight_kg',
              'total_distance_km', 'total_co2e', 'created_at']

    with open(filename, 'w', newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fields)
        writer.writeheader()

        for pkg in all_packages:
            row = {field: pkg.get(field) for field in fields}
            writer.writerow(row)

    print(f"Exported {len(all_packages)} packages to {filename}")

export_packages_report()
```

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Get Package by ID" icon="box-open" href="/api-reference/logistics/get-package">
    Get a specific package with all its legs
  </Card>

  <Card title="Create Logistics Request" icon="plus" href="/api-reference/logistics/create-request">
    Create a new leg (with optional package association)
  </Card>

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

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