> ## 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 Custom Emission Factor

> Remove a custom emission factor permanently

# Delete Custom Emission Factor

Permanently delete a custom emission factor from a Custom Emission Group. This action cannot be undone.

<Warning>
  Deleting a custom emission factor is permanent. If the factor is currently in use by purchases, wastes, or other records, this may affect historical data calculations. Consider archiving by setting end dates instead of deleting.
</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:** `ff4adcc7-8172-45fe-9cf1-e90a6de53aa9`
</ParamField>

<ParamField header="x-user-id" type="string" required>
  Your user UUID

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

### Path Parameters

<ParamField path="id" type="string" required>
  UUID of the Custom Emission Factor to delete

  **Example:** `"factor-uuid-here"`
</ParamField>

## Response

Returns HTTP 204 No Content on successful deletion.

## Example

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X DELETE "https://api.dcycle.io/api/v1/custom_emission_factors/factor-uuid" \
    -H "Authorization: Bearer ${DCYCLE_API_KEY}" \
    -H "x-organization-id: ${DCYCLE_ORG_ID}" \
    -H "x-user-id: ${DCYCLE_USER_ID}"
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import requests
  import os

  headers = {
      "Authorization": f"Bearer {os.getenv('DCYCLE_API_KEY')}",
      "x-organization-id": os.getenv("DCYCLE_ORG_ID"),
      "x-user-id": os.getenv("DCYCLE_USER_ID")
  }

  factor_id = "factor-uuid"

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

  if response.status_code == 204:
      print("✅ Custom emission factor deleted successfully")
  else:
      print(f"❌ Error: {response.json()}")
  ```

  ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const axios = require('axios');

  const headers = {
    'Authorization': `Bearer ${process.env.DCYCLE_API_KEY}`,
    'x-organization-id': process.env.DCYCLE_ORG_ID,
    'x-user-id': process.env.DCYCLE_USER_ID
  };

  const factorId = 'factor-uuid';

  axios.delete(
    `https://api.dcycle.io/api/v1/custom_emission_factors/${factorId}`,
    { headers }
  )
  .then(response => {
    if (response.status === 204) {
      console.log('✅ Custom emission factor deleted successfully');
    }
  })
  .catch(error => console.error(error));
  ```
</CodeGroup>

## Use Cases

### Remove Outdated Factors

Delete factors that are no longer relevant:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Get all factors in a group
factors = requests.get(
    f"https://api.dcycle.io/api/v1/custom_emission_factors/list/{group_id}",
    headers=headers,
    params={"page": 1, "size": 100}
).json()

# Delete outdated factors
from datetime import date

today = date.today()
for factor in factors['items']:
    if factor['factor_end_date'] and date.fromisoformat(factor['factor_end_date']) < today:
        requests.delete(
            f"https://api.dcycle.io/api/v1/custom_emission_factors/{factor['id']}",
            headers=headers
        )
        print(f"Deleted expired factor: {factor['ef_name']}")
```

### Safe Delete with Confirmation

Always fetch and confirm before deleting:

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
async function deleteFactorSafely(factorId) {
  // First, get the factor details
  const factor = await axios.get(
    `https://api.dcycle.io/api/v1/custom_emission_factors/${factorId}`,
    { headers }
  ).then(res => res.data);

  // Show confirmation
  console.log(`About to delete: ${factor.ef_name}`);
  console.log(`Uploaded by: ${factor.factor_uploaded_by}`);
  console.log(`Valid until: ${factor.factor_end_date}`);

  // Confirm and delete
  const confirmed = true; // Replace with actual user confirmation
  if (confirmed) {
    await axios.delete(
      `https://api.dcycle.io/api/v1/custom_emission_factors/${factorId}`,
      { headers }
    );
    console.log('✅ Deleted successfully');
  }
}
```

### Bulk Delete by Criteria

Delete multiple factors matching certain criteria:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# List all factors in a group
response = requests.get(
    f"https://api.dcycle.io/api/v1/custom_emission_factors/list/{group_id}",
    headers=headers,
    params={"page": 1, "size": 100}
)

factors = response.json()['items']

# Delete factors with high uncertainty
for factor in factors:
    if factor.get('uncertainty_grade', 0) > 80:
        requests.delete(
            f"https://api.dcycle.io/api/v1/custom_emission_factors/{factor['id']}",
            headers=headers
        )
        print(f"Deleted high-uncertainty factor: {factor['ef_name']} ({factor['uncertainty_grade']}%)")
```

## Common Errors

### 404 Not Found

**Cause:** Custom emission factor not found

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

**Solution:** The factor may have already been deleted, or the ID is incorrect. Verify the factor exists first.

### 403 Forbidden

**Cause:** Insufficient permissions

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "detail": "Insufficient permissions",
  "code": "FORBIDDEN"
}
```

**Solution:** Ensure you have permission to delete factors for this organization.

## Best Practices

### 1. Archive Instead of Delete

For factors with historical usage, consider setting an end date instead of deleting:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Instead of deleting
# requests.delete(...)

# Archive by setting end date to yesterday
from datetime import date, timedelta

yesterday = date.today() - timedelta(days=1)
requests.patch(
    f"https://api.dcycle.io/api/v1/custom_emission_factors/{factor_id}",
    headers=headers,
    json={
        "factor_uploaded_by": "system@company.com",
        "factor_end_date": yesterday.isoformat(),
        "additional_docs": f"{factor['additional_docs']} | Archived {date.today().isoformat()}"
    }
)
```

**Note:** The API doesn't allow updating `factor_end_date` via PATCH. If you need to archive, you must delete and recreate with the updated date, or simply delete if no longer needed.

### 2. Audit Before Deleting

Check if factor is in use before deletion:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Get factor details
factor = requests.get(
    f"https://api.dcycle.io/api/v1/custom_emission_factors/{factor_id}",
    headers=headers
).json()

print(f"Factor: {factor['ef_name']}")
print(f"Created: {factor.get('factor_start_date', 'Unknown')}")
print(f"Uploaded by: {factor['factor_uploaded_by']}")

# Confirm before proceeding
confirm = input("Delete this factor? (yes/no): ")
if confirm.lower() == 'yes':
    requests.delete(
        f"https://api.dcycle.io/api/v1/custom_emission_factors/{factor_id}",
        headers=headers
    )
```

### 3. Clean Up Empty Groups

After deleting factors, check if the group is empty:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Delete factor
requests.delete(
    f"https://api.dcycle.io/api/v1/custom_emission_factors/{factor_id}",
    headers=headers
)

# Check if group has remaining factors
remaining = requests.get(
    f"https://api.dcycle.io/api/v1/custom_emission_factors/list/{group_id}",
    headers=headers,
    params={"page": 1, "size": 1}
).json()

if remaining['total'] == 0:
    print(f"Group {group_id} is now empty. Consider deleting the group.")
    # Optionally delete the group
    # requests.delete(f"https://api.dcycle.io/api/v1/custom_emission_groups/{group_id}", headers=headers)
```

### 4. Log Deletion Actions

Maintain audit logs of deletions:

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
async function deleteWithAudit(factorId, reason) {
  const factor = await axios.get(
    `https://api.dcycle.io/api/v1/custom_emission_factors/${factorId}`,
    { headers }
  ).then(res => res.data);

  // Log before deletion
  const auditLog = {
    action: 'delete_custom_emission_factor',
    factor_id: factorId,
    factor_name: factor.ef_name,
    deleted_by: process.env.DCYCLE_USER_ID,
    deleted_at: new Date().toISOString(),
    reason: reason
  };
  console.log('Audit log:', auditLog);
  // Save to your audit system

  // Delete
  await axios.delete(
    `https://api.dcycle.io/api/v1/custom_emission_factors/${factorId}`,
    { headers }
  );
}

// Usage
deleteWithAudit('factor-uuid', 'Supplier no longer in use');
```

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Get Factor" icon="magnifying-glass" href="/api-docs/custom-emission-factors/get">
    View before deleting
  </Card>

  <Card title="List Factors" icon="list" href="/api-docs/custom-emission-factors/list">
    View all factors in group
  </Card>

  <Card title="Create Factor" icon="plus" href="/api-docs/custom-emission-factors/create">
    Add new factor
  </Card>

  <Card title="Overview" icon="book" href="/api-docs/custom-emission-factors/overview">
    Learn about custom factors
  </Card>
</CardGroup>
