Skip to main content
PATCH
https://api.dcycle.io
/
v1
/
purchases
/
{purchase_id}
Update Purchase
const options = {
  method: 'PATCH',
  headers: {
    'x-api-key': '<x-api-key>',
    'x-organization-id': '<x-organization-id>',
    'Content-Type': '<content-type>'
  },
  body: JSON.stringify({
    product_name: '<string>',
    sector: '<string>',
    country: '<string>',
    quantity: 123,
    unit_id: '<string>',
    purchase_date: '<string>',
    expense_type: '<string>',
    description: '<string>',
    purchase_type: '<string>',
    status: '<string>',
    recycled: 123,
    supplier_id: '<string>',
    custom_emission_factor_id: '<string>',
    frequency: '<string>',
    file_id: '<string>',
    file_name: '<string>',
    file_url: '<string>'
  })
};

fetch('https://api.dcycle.io/v1/purchases/{purchase_id}', options)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err));
{
  "id": "<string>",
  "organization_id": "<string>",
  "product_name": {},
  "description": {},
  "sector": {},
  "country": {},
  "quantity": {},
  "unit_id": {},
  "purchase_date": {},
  "purchase_type": {},
  "expense_type": {},
  "status": {},
  "recycled": {},
  "supplier_id": {},
  "custom_emission_factor_id": {},
  "file_id": {},
  "file_name": {},
  "file_url": {},
  "co2e": {},
  "frequency": {},
  "created_at": {},
  "updated_at": {}
}

Update Purchase

Update an existing purchase’s information. You can modify any combination of the purchase’s fields.
Partial Updates: Only include the fields you want to update. Fields not included in the request body will remain unchanged.

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
Content-Type
string
required
Must be application/json

Path Parameters

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

Body Parameters

product_name
string
Name of the product or service purchased (max 255 characters)Example: "Office Supplies - Updated"
sector
string
Economic sector for emission factor lookup (max 255 characters)Example: "Retail trade"
country
string
2-letter ISO country code where the purchase was madeExample: "DE"
quantity
number
Purchase amount (must be >= 0). For spend-based, this is the monetary value.Example: 2000.00
unit_id
string
Unit of measurement (e.g., EUR, USD, kg)Example: "EUR"
purchase_date
string
Date of purchase in YYYY-MM-DD formatExample: "2024-03-20"
expense_type
string
Expense classificationAvailable values: capex, opexExample: "capex"
description
string
Optional description of the purchase (max 500 characters)Example: "Updated Q1 2024 order with additional items"
purchase_type
string
Calculation method for emissionsAvailable values: spend_based, supplier_specificExample: "supplier_specific"
status
string
Purchase statusAvailable values: active, pending, in_progress, in_review, inactiveExample: "in_review"
recycled
number
Recycled content percentage (0 to 1). Reduces calculated emissions.Example: 0.5 (50% recycled content)
supplier_id
string
Optional supplier identifier for referenceExample: "supplier-456"
custom_emission_factor_id
string
UUID of custom emission factor for supplier-specific calculationsExample: "770e8400-e29b-41d4-a716-446655440000"
frequency
string
Purchase frequencyAvailable values: onceExample: "once"
file_id
string
UUID of linked file/documentExample: "660e8400-e29b-41d4-a716-446655440000"
file_name
string
Name of linked file (max 255 characters)Example: "invoice_q1_2024_updated.pdf"
file_url
string
URL of linked fileExample: "https://storage.dcycle.io/..."

Response

Returns the updated purchase object with recalculated emissions.
id
string
Unique identifier (UUID)
organization_id
string
Organization UUID
product_name
string | null
Name of the product or service
description
string | null
Optional description
sector
string | null
Economic sector
country
string | null
2-letter ISO country code
quantity
number | null
Purchase amount
unit_id
string | null
Unit of measurement
purchase_date
date | null
Date of purchase
purchase_type
string | null
Calculation method: spend_based or supplier_specific
expense_type
string | null
Classification: capex or opex
status
string | null
Purchase status
recycled
number | null
Recycled content percentage (0-1)
supplier_id
string | null
Supplier identifier
custom_emission_factor_id
string | null
Custom emission factor UUID
file_id
string | null
Linked file UUID
file_name
string | null
Linked file name
file_url
string | null
Linked file download URL
co2e
number | null
Recalculated CO2 equivalent emissions (kg)
frequency
string | null
Purchase frequency
created_at
datetime | null
Timestamp when the purchase was created
updated_at
datetime | null
Timestamp when the purchase was last updated

Example

curl -X PATCH "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}" \
  -H "Content-Type: application/json" \
  -d '{
    "quantity": 2000.00,
    "recycled": 0.5,
    "description": "Updated order with additional items"
  }'

Successful Response

Status Code: 200 OK
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "organization_id": "a8315ef3-dd50-43f8-b7ce-d839e68d51fa",
  "product_name": "Office Supplies",
  "description": "Updated order with additional items",
  "sector": "Manufacturing",
  "country": "ES",
  "quantity": 2000.00,
  "unit_id": "EUR",
  "purchase_date": "2024-03-15",
  "purchase_type": "spend_based",
  "expense_type": "opex",
  "status": "active",
  "recycled": 0.5,
  "supplier_id": "supplier-123",
  "custom_emission_factor_id": null,
  "file_id": "660e8400-e29b-41d4-a716-446655440000",
  "file_name": "invoice_q1_2024.pdf",
  "file_url": "https://storage.dcycle.io/...",
  "co2e": 163.7,
  "frequency": "once",
  "created_at": "2024-03-15T10:30:00Z",
  "updated_at": "2024-03-20T14:45:00Z"
}

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 exists and belongs to the organization specified in the header.

422 Validation Error

Cause: Invalid field values
{
  "detail": [
    {
      "loc": ["body", "recycled"],
      "msg": "ensure this value is less than or equal to 1",
      "type": "value_error.number.not_le"
    }
  ]
}
Solution: Check that:
  • recycled is between 0 and 1
  • quantity is >= 0
  • country is a valid 2-letter ISO code
  • expense_type is either capex or opex
  • purchase_type is either spend_based or supplier_specific

Use Cases

Update Quantity and Recalculate Emissions

Modify the purchase amount to update the calculated CO2e:
def update_purchase_quantity(purchase_id, new_quantity):
    """Update purchase quantity and recalculate emissions"""
    response = requests.patch(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers,
        json={"quantity": new_quantity}
    )
    purchase = response.json()
    print(f"New quantity: {purchase['quantity']} {purchase['unit_id']}")
    print(f"New CO2e: {purchase['co2e']} kg")
    return purchase

# Update purchase amount
purchase = update_purchase_quantity(
    "550e8400-e29b-41d4-a716-446655440000",
    3500.00
)

Change Calculation Method

Switch from spend-based to supplier-specific calculation:
def switch_to_supplier_specific(purchase_id, custom_factor_id):
    """Change purchase to use supplier-specific emission factor"""
    response = requests.patch(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers,
        json={
            "purchase_type": "supplier_specific",
            "custom_emission_factor_id": custom_factor_id
        }
    )
    return response.json()

# Switch to supplier-specific calculation
purchase = switch_to_supplier_specific(
    "550e8400-e29b-41d4-a716-446655440000",
    "770e8400-e29b-41d4-a716-446655440000"
)
print(f"New CO2e with supplier factor: {purchase['co2e']} kg")

Update Recycled Content

Adjust the recycled percentage for more accurate emissions:
def update_recycled_percentage(purchase_id, recycled_pct):
    """Update recycled content percentage (0 to 1)"""
    response = requests.patch(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers,
        json={"recycled": recycled_pct}
    )
    return response.json()

# Set 30% recycled content
purchase = update_recycled_percentage(
    "550e8400-e29b-41d4-a716-446655440000",
    0.3
)
print(f"CO2e with recycled content: {purchase['co2e']} kg")

Mark Purchase as Inactive

Exclude a purchase from calculations:
def deactivate_purchase(purchase_id):
    """Mark purchase as inactive"""
    response = requests.patch(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers,
        json={"status": "inactive"}
    )
    return response.json()

# Deactivate purchase
purchase = deactivate_purchase("550e8400-e29b-41d4-a716-446655440000")
print(f"{purchase['product_name']} is now {purchase['status']}")
Attach an invoice or receipt to the purchase:
def link_document(purchase_id, file_id, file_name, file_url):
    """Link a document to a purchase"""
    response = requests.patch(
        f"https://api.dcycle.io/v1/purchases/{purchase_id}",
        headers=headers,
        json={
            "file_id": file_id,
            "file_name": file_name,
            "file_url": file_url
        }
    )
    return response.json()

# Link invoice
purchase = link_document(
    "550e8400-e29b-41d4-a716-446655440000",
    "660e8400-e29b-41d4-a716-446655440000",
    "invoice_updated.pdf",
    "https://storage.dcycle.io/..."
)
print(f"Linked document: {purchase['file_name']}")

Bulk Update Purchases

Update multiple purchases’ status:
def bulk_update_status(purchase_ids, new_status):
    """Update status for multiple purchases"""
    results = {"success": [], "failed": []}

    for purchase_id in purchase_ids:
        try:
            response = requests.patch(
                f"https://api.dcycle.io/v1/purchases/{purchase_id}",
                headers=headers,
                json={"status": new_status}
            )
            if response.status_code == 200:
                results["success"].append(purchase_id)
            else:
                results["failed"].append({"id": purchase_id, "error": response.text})
        except Exception as e:
            results["failed"].append({"id": purchase_id, "error": str(e)})

    return results

# Mark purchases as reviewed
purchase_ids = [
    "550e8400-e29b-41d4-a716-446655440000",
    "550e8400-e29b-41d4-a716-446655440001"
]

results = bulk_update_status(purchase_ids, "active")
print(f"Updated: {len(results['success'])}")
print(f"Failed: {len(results['failed'])}")