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

# Delete Purchase

> Remove a purchase from your organization

# Delete Purchase

Permanently delete a purchase from your organization. This will remove the purchase and its associated CO2e emissions data from your Scope 3 Category 1 calculations.

<Warning>
  **Irreversible Action**: Deleting a purchase permanently removes all its data, including emissions calculations. Consider updating the `status` to `inactive` instead if you want to preserve historical data while excluding it from calculations.
</Warning>

## 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="purchase_id" type="string" required>
  The unique identifier (UUID) of the purchase to delete

  **Example:** `550e8400-e29b-41d4-a716-446655440000`
</ParamField>

## Response

Returns `204 No Content` on successful deletion. No response body is returned.

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X DELETE "https://api.dcycle.io/v1/purchases/550e8400-e29b-41d4-a716-446655440000" \
    -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")
  purchase_id = "550e8400-e29b-41d4-a716-446655440000"

  headers = {
      "x-api-key": api_key,
      "x-organization-id": org_id
  }

  response = requests.delete(
      f"https://api.dcycle.io/v1/purchases/{purchase_id}",
      headers=headers
  )

  if response.status_code == 204:
      print("Purchase deleted successfully")
  else:
      print(f"Error: {response.text}")
  ```

  ```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 purchaseId = '550e8400-e29b-41d4-a716-446655440000';

  const headers = {
    'x-api-key': apiKey,
    'x-organization-id': orgId
  };

  axios.delete(
    `https://api.dcycle.io/v1/purchases/${purchaseId}`,
    { headers }
  )
  .then(response => {
    if (response.status === 204) {
      console.log('Purchase deleted successfully');
    }
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

### Successful Response

```
HTTP/1.1 204 No Content
```

No response body is returned.

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

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

**Solution:** Verify the purchase ID is correct and belongs to your organization.

### 422 Validation Error

**Cause:** Invalid purchase ID format

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": [
    {
      "loc": ["path", "purchase_id"],
      "msg": "value is not a valid uuid",
      "type": "type_error.uuid"
    }
  ]
}
```

**Solution:** Ensure the purchase ID is a valid UUID format.

## Use Cases

### Delete Single Purchase

Remove a purchase from the system:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def delete_purchase(purchase_id):
    """Delete a purchase by ID"""
    response = requests.delete(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers
    )

    if response.status_code == 204:
        return True
    else:
        print(f"Failed to delete: {response.text}")
        return False

success = delete_purchase("550e8400-e29b-41d4-a716-446655440000")
if success:
    print("Purchase deleted")
```

### Delete with Confirmation

Verify the purchase details before deleting:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def delete_purchase_with_confirmation(purchase_id):
    """Delete purchase after getting confirmation"""
    # First, get purchase details
    response = requests.get(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers
    )

    if response.status_code != 200:
        print("Purchase not found")
        return False

    purchase = response.json()

    # Show what will be deleted
    print(f"About to delete:")
    print(f"  Product: {purchase['product_name']}")
    print(f"  Quantity: {purchase['quantity']} {purchase['unit_id']}")
    print(f"  CO2e: {purchase['co2e']} kg")
    print(f"  Date: {purchase['purchase_date']}")

    # In a real app, you'd ask for confirmation here
    confirm = input("Delete this purchase? (yes/no): ")

    if confirm.lower() == 'yes':
        response = requests.delete(
            f"https://api.dcycle.io/v1/purchases/{purchase_id}",
            headers=headers
        )
        return response.status_code == 204

    return False
```

### Bulk Delete Purchases

Delete multiple purchases:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def bulk_delete_purchases(purchase_ids):
    """Delete multiple purchases"""
    results = {"deleted": [], "failed": []}

    for purchase_id in purchase_ids:
        response = requests.delete(
            f"https://api.dcycle.io/v1/purchases/{purchase_id}",
            headers=headers
        )

        if response.status_code == 204:
            results["deleted"].append(purchase_id)
        else:
            results["failed"].append({
                "id": purchase_id,
                "error": response.text
            })

    return results

# Delete multiple purchases
purchase_ids = [
    "550e8400-e29b-41d4-a716-446655440000",
    "550e8400-e29b-41d4-a716-446655440001"
]

results = bulk_delete_purchases(purchase_ids)
print(f"Deleted: {len(results['deleted'])}")
print(f"Failed: {len(results['failed'])}")
```

### Delete Purchases by File

Remove all purchases linked to a specific file:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def delete_purchases_by_file(file_id):
    """Delete all purchases associated with a file"""
    # Get all purchases for the file
    response = requests.get(
        "https://api.dcycle.io/v1/purchases",
        headers=headers,
        params={"file_id[]": [file_id], "size": 100}
    )

    purchases = response.json()["items"]
    print(f"Found {len(purchases)} purchases linked to file {file_id}")

    deleted = 0
    for purchase in purchases:
        response = requests.delete(
            f"https://api.dcycle.io/v1/purchases/{purchase['id']}",
            headers=headers
        )
        if response.status_code == 204:
            deleted += 1
            print(f"Deleted: {purchase['product_name']}")

    print(f"Total deleted: {deleted}")
    return deleted
```

### Delete Inactive Purchases

Clean up purchases marked as inactive:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def cleanup_inactive_purchases():
    """Delete all inactive purchases"""
    # Get all inactive purchases
    response = requests.get(
        "https://api.dcycle.io/v1/purchases",
        headers=headers,
        params={"status[]": ["inactive"], "size": 100}
    )

    purchases = response.json()["items"]
    print(f"Found {len(purchases)} inactive purchases")

    deleted = 0
    for purchase in purchases:
        response = requests.delete(
            f"https://api.dcycle.io/v1/purchases/{purchase['id']}",
            headers=headers
        )
        if response.status_code == 204:
            deleted += 1
            print(f"Deleted: {purchase['product_name']}")

    print(f"Total deleted: {deleted}")
    return deleted

# Run cleanup
cleanup_inactive_purchases()
```

## Best Practices

### Consider Alternatives

Before deleting, consider:

1. **Set to Inactive**: Update `status: "inactive"` to preserve historical data
2. **Archive Data**: Export purchase data before deletion for audit trails
3. **Verify Impact**: Check if the purchase's CO2e data is needed for reports

### Preserve Historical Data

If you need to keep emissions records:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def archive_and_delete_purchase(purchase_id):
    """Archive purchase data before deletion"""
    # Get purchase with full data
    response = requests.get(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers
    )
    purchase = response.json()

    # Archive to file or database
    import json
    with open(f"archived_purchase_{purchase_id}.json", "w") as f:
        json.dump(purchase, f, indent=2)

    print(f"Archived purchase data to archived_purchase_{purchase_id}.json")

    # Now delete
    response = requests.delete(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers
    )

    return response.status_code == 204
```

### Audit Trail

Maintain a log of deletions:

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

def delete_with_audit(purchase_id, reason):
    """Delete purchase with audit trail"""
    # Get purchase details first
    response = requests.get(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers
    )
    purchase = response.json()

    # Log the deletion
    audit_entry = {
        "timestamp": datetime.datetime.now().isoformat(),
        "action": "delete",
        "purchase_id": purchase_id,
        "product_name": purchase["product_name"],
        "co2e": purchase["co2e"],
        "reason": reason
    }

    # Append to audit log
    import json
    with open("purchase_audit_log.json", "a") as f:
        f.write(json.dumps(audit_entry) + "\n")

    # Delete the purchase
    response = requests.delete(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers
    )

    return response.status_code == 204

# Delete with reason
delete_with_audit(
    "550e8400-e29b-41d4-a716-446655440000",
    "Duplicate entry - consolidated with purchase XYZ"
)
```

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Update Purchase" icon="pencil" href="/api-reference/purchases/update">
    Modify purchase (e.g., set as inactive instead of deleting)
  </Card>

  <Card title="List Purchases" icon="list" href="/api-reference/purchases/list">
    View all purchases
  </Card>

  <Card title="Create Purchase" icon="plus" href="/api-reference/purchases/create">
    Add a new purchase
  </Card>

  <Card title="Get Purchase" icon="receipt" href="/api-reference/purchases/get">
    View purchase details before deleting
  </Card>
</CardGroup>
