Skip to main content
DELETE
https://api.dcycle.io
/
v1
/
purchases
/
{purchase_id}
Delete Purchase
const options = {
  method: 'DELETE',
  headers: {'x-api-key': '<x-api-key>', 'x-organization-id': '<x-organization-id>'}
};

fetch('https://api.dcycle.io/v1/purchases/{purchase_id}', options)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err));

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

Request

Headers

x-api-key
string
required
Your API key for authenticationExample: sk_live_1234567890abcdef
x-organization-id
string
required
Your organization UUIDExample: a8315ef3-dd50-43f8-b7ce-d839e68d51fa

Path Parameters

purchase_id
string
required
The unique identifier (UUID) of the purchase to deleteExample: 550e8400-e29b-41d4-a716-446655440000

Response

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

Example

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

Successful Response

HTTP/1.1 204 No Content
No response body is returned.

Common Errors

401 Unauthorized

Cause: Missing or invalid API key
{
  "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
{
  "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
{
  "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:
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:
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:
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:
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:
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:
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:
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"
)