> ## 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 Package by ID

> Retrieve a specific logistics package with all its legs

# Get Package by ID

Retrieve a specific logistics package by its UUID, including all associated legs and aggregated 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>

### Path Parameters

<ParamField path="package_id" type="string" required>
  The UUID of the package to retrieve

  **Example:** `a1b2c3d4-e5f6-7890-abcd-ef1234567890`
</ParamField>

## Response

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

<ResponseField name="legs" type="array">
  Array of leg objects associated with this package

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

    <ResponseField name="origin" type="string">
      Origin location of the leg
    </ResponseField>

    <ResponseField name="destination" type="string">
      Destination location of the leg
    </ResponseField>

    <ResponseField name="distance_km" type="number">
      Distance of this leg in kilometers
    </ResponseField>

    <ResponseField name="co2e" type="number">
      CO2 equivalent emissions for this leg in kilograms
    </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/a1b2c3d4-e5f6-7890-abcd-ef1234567890" \
    -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
  }

  package_id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890"

  response = requests.get(
      f"https://api.dcycle.io/v1/logistics/packages/{package_id}",
      headers=headers
  )

  package = response.json()
  print(f"Package: {package['package_key']}")
  print(f"Total emissions: {package['total_co2e']:.2f} kg CO2e")
  print(f"Legs ({len(package['legs'])}):")
  for leg in package['legs']:
      print(f"  - {leg['origin']} -> {leg['destination']}: {leg['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 packageId = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';

  axios.get(
    `https://api.dcycle.io/v1/logistics/packages/${packageId}`,
    { headers }
  )
  .then(response => {
    const pkg = response.data;
    console.log(`Package: ${pkg.package_key}`);
    console.log(`Total emissions: ${pkg.total_co2e?.toFixed(2)} kg CO2e`);
    console.log(`Legs (${pkg.legs.length}):`);
    pkg.legs.forEach(leg => {
      console.log(`  - ${leg.origin} -> ${leg.destination}: ${leg.co2e?.toFixed(2)} kg CO2e`);
    });
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "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",
  "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
    }
  ]
}
```

## 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:** Package not found or doesn't belong to your organization

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "code": "NOT_FOUND",
  "detail": "Package not found"
}
```

**Solution:** Verify that:

1. The `package_id` is a valid UUID
2. The package belongs to the organization specified in `x-organization-id`
3. The package exists and hasn't been deleted

## Use Cases

### Detailed Package Journey Analysis

Analyze the complete journey of a package:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def analyze_package_journey(package_id: str) -> dict:
    """Analyze a package's complete journey"""
    response = requests.get(
        f"https://api.dcycle.io/v1/logistics/packages/{package_id}",
        headers=headers
    )

    package = response.json()
    legs = package.get('legs', [])

    # Calculate metrics
    journey = {
        "package_key": package['package_key'],
        "total_legs": len(legs),
        "total_distance_km": package['total_distance_km'],
        "total_co2e_kg": package['total_co2e'],
        "average_co2e_per_km": (
            package['total_co2e'] / package['total_distance_km']
            if package['total_distance_km'] else 0
        ),
        "journey_details": [
            {
                "leg": i + 1,
                "route": f"{leg['origin']} -> {leg['destination']}",
                "distance_km": leg['distance_km'],
                "co2e_kg": leg['co2e'],
                "percentage_of_total": (
                    (leg['co2e'] / package['total_co2e'] * 100)
                    if package['total_co2e'] else 0
                )
            }
            for i, leg in enumerate(legs)
        ]
    }

    return journey

# Example usage
analysis = analyze_package_journey("a1b2c3d4-e5f6-7890-abcd-ef1234567890")
print(f"Package {analysis['package_key']} Journey:")
print(f"  Total legs: {analysis['total_legs']}")
print(f"  Total distance: {analysis['total_distance_km']:.2f} km")
print(f"  Total emissions: {analysis['total_co2e_kg']:.2f} kg CO2e")
print(f"\nLeg breakdown:")
for leg in analysis['journey_details']:
    print(f"  Leg {leg['leg']}: {leg['route']}")
    print(f"    Distance: {leg['distance_km']:.2f} km")
    print(f"    Emissions: {leg['co2e_kg']:.2f} kg ({leg['percentage_of_total']:.1f}%)")
```

### Generate Package Certificate Data

Prepare data for an emissions certificate:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def get_package_certificate_data(package_id: str) -> dict:
    """Get data for generating an emissions certificate"""
    response = requests.get(
        f"https://api.dcycle.io/v1/logistics/packages/{package_id}",
        headers=headers
    )

    package = response.json()

    certificate_data = {
        "certificate_type": "Package Emissions Report",
        "package_identifier": package['package_key'],
        "shipment_reference": package['shipment_id'],
        "weight_transported_kg": package['weight_kg'],
        "total_distance_km": package['total_distance_km'],
        "total_co2e_kg": package['total_co2e'],
        "legs_count": len(package.get('legs', [])),
        "calculation_date": package['updated_at'],
        "route_summary": " -> ".join(
            [package['legs'][0]['origin']] +
            [leg['destination'] for leg in package.get('legs', [])]
        ) if package.get('legs') else "N/A"
    }

    return certificate_data

# Example usage
cert = get_package_certificate_data("a1b2c3d4-e5f6-7890-abcd-ef1234567890")
print("=== EMISSIONS CERTIFICATE ===")
print(f"Package: {cert['package_identifier']}")
print(f"Shipment: {cert['shipment_reference']}")
print(f"Route: {cert['route_summary']}")
print(f"Weight: {cert['weight_transported_kg']} kg")
print(f"Distance: {cert['total_distance_km']:.2f} km")
print(f"CO2e Emissions: {cert['total_co2e_kg']:.2f} kg")
```

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Get Packages" icon="boxes-stacked" href="/api-reference/logistics/get-packages">
    List all packages with pagination
  </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>
