Skip to main content
File deletions are tracked and can trigger blockchain events for complete audit trail.
File deletion is permanent and cannot be undone. Ensure you have proper backups if needed before deleting files.

Endpoint

curl -X DELETE "https://api.g2cplatform.com/v2/companies/{COMPANY_ID}/files/{FILE_ID}" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json"

Request

HTTP Method

DELETE

URL

https://api.g2cplatform.com/v2/companies/{COMPANY_ID}/files/{FILE_ID}

Path Parameters

ParameterTypeRequiredDescription
COMPANY_IDstring (UUID)Company identifier
FILE_IDstring (UUID)File identifier to delete

Headers

X-API-Key: YOUR_API_KEY
Content-Type: application/json

Response

Success Response (204 No Content)

HTTP/1.1 204 No Content
A successful deletion returns no content body. The 204 status code indicates the file was deleted successfully.

Error Responses

404 Not Found

{
  "error": "File not found",
  "code": "FILE_NOT_FOUND",
  "timestamp": "2025-08-03T10:30:00Z"
}

401 Unauthorized

{
  "error": "Invalid or missing API key",
  "code": "UNAUTHORIZED",
  "timestamp": "2025-08-03T10:30:00Z"
}

403 Forbidden

{
  "error": "Access denied to delete file",
  "code": "FILE_DELETE_DENIED",
  "timestamp": "2025-08-03T10:30:00Z"
}

Implementation Examples

Basic File Deletion

async function deleteFile(companyId, fileId) {
  try {
    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${companyId}/files/${fileId}`,
      {
        method: 'DELETE',
        headers: {
          'X-API-Key': process.env.G2C_API_KEY,
          'Content-Type': 'application/json'
        }
      }
    );

    if (response.ok) {
      console.log('✅ File deleted successfully');
      return true;
    } else {
      const error = await response.json();
      throw new Error(`Delete failed: ${error.error}`);
    }
  } catch (error) {
    console.error('❌ File deletion error:', error.message);
    throw error;
  }
}

// Usage
await deleteFile('company-uuid', 'file-uuid');

Safe File Deletion with Confirmation

async function safeDeleteFile(companyId, fileId, confirmationCallback = null) {
  try {
    // Optional confirmation step
    if (confirmationCallback) {
      const confirmed = await confirmationCallback(fileId);
      if (!confirmed) {
        console.log('File deletion cancelled by user');
        return { cancelled: true };
      }
    }

    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${companyId}/files/${fileId}`,
      {
        method: 'DELETE',
        headers: {
          'X-API-Key': process.env.G2C_API_KEY,
          'Content-Type': 'application/json'
        }
      }
    );

    if (response.ok) {
      console.log('✅ File deleted successfully');
      return { success: true };
    } else {
      const error = await response.json();
      throw new Error(`Delete failed: ${error.error}`);
    }
  } catch (error) {
    console.error('❌ File deletion error:', error.message);
    return { success: false, error: error.message };
  }
}

// Usage with confirmation
const result = await safeDeleteFile('company-uuid', 'file-uuid', async (fileId) => {
  return confirm(`Are you sure you want to delete file ${fileId}?`);
});

if (result.success) {
  console.log('File deleted successfully');
} else if (result.cancelled) {
  console.log('Deletion cancelled');
} else {
  console.error('Deletion failed:', result.error);
}

Batch File Deletion

async function deleteMultipleFiles(companyId, fileIds) {
  const results = [];

  for (const fileId of fileIds) {
    try {
      await deleteFile(companyId, fileId);
      results.push({
        success: true,
        fileId
      });

      // Add small delay to avoid overwhelming the server
      await new Promise(resolve => setTimeout(resolve, 100));
    } catch (error) {
      results.push({
        success: false,
        fileId,
        error: error.message
      });
    }
  }

  const successful = results.filter(r => r.success);
  const failed = results.filter(r => !r.success);

  console.log(`✅ Deleted ${successful.length} files successfully`);
  if (failed.length > 0) {
    console.log(`❌ Failed to delete ${failed.length} files:`, failed);
  }

  return { successful, failed };
}

// Usage
const fileIds = ['file-1', 'file-2', 'file-3'];
const results = await deleteMultipleFiles('company-uuid', fileIds);

File Deletion with Object Update Tracking

async function deleteFileWithTracking(companyId, objectId, fileId, deletionMetadata) {
  try {
    // First delete the file
    await deleteFile(companyId, fileId);

    // Then update the object to track the file deletion
    const updateData = {
      action: 'update',
      eventDescription: `File deleted: ${deletionMetadata.reason || 'File removed'}`,
      performedBy: deletionMetadata.deletedBy || 'System',
      metadata: {
        ...deletionMetadata,
        deletedFileId: fileId,
        deletionTimestamp: new Date().toISOString()
      }
    };

    const updateResponse = await fetch(
      `https://api.g2cplatform.com/v2/companies/${companyId}/objects/${objectId}`,
      {
        method: 'PUT',
        headers: {
          'X-API-Key': process.env.G2C_API_KEY,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(updateData)
      }
    );

    if (updateResponse.ok) {
      console.log('✅ File deleted and object updated with tracking event');
      return true;
    } else {
      console.warn('⚠️ File deleted but object tracking update failed');
      return true; // File was still deleted successfully
    }

  } catch (error) {
    console.error('❌ File deletion or tracking update failed:', error);
    throw error;
  }
}

// Usage
await deleteFileWithTracking('company-uuid', 'object-uuid', 'file-uuid', {
  reason: 'Outdated warranty document',
  deletedBy: 'John Doe',
  category: 'document-cleanup'
});

Use Cases

File Management System

class FileManager {
  constructor(companyId, apiKey) {
    this.companyId = companyId;
    this.apiKey = apiKey;
  }

  async deleteExpiredFiles(objectId, daysOld = 30) {
    try {
      // First get object with files to check expiration
      const objectResponse = await fetch(
        `https://api.g2cplatform.com/v2/companies/${this.companyId}/objects/${objectId}?includeHistory=false`,
        {
          headers: { 'X-API-Key': this.apiKey }
        }
      );

      if (!objectResponse.ok) {
        throw new Error('Failed to get object files');
      }

      const objectData = await objectResponse.json();
      const files = objectData.files || [];

      // Filter expired files
      const cutoffDate = new Date();
      cutoffDate.setDate(cutoffDate.getDate() - daysOld);

      const expiredFiles = files.filter(file => {
        const fileDate = new Date(file.uploadedAt);
        return fileDate < cutoffDate;
      });

      if (expiredFiles.length === 0) {
        console.log('No expired files found');
        return { deleted: 0, failed: 0 };
      }

      // Delete expired files
      const results = [];
      for (const file of expiredFiles) {
        try {
          await this.deleteFile(file.id);
          results.push({ file: file.fileName, status: 'deleted' });
        } catch (error) {
          results.push({ file: file.fileName, status: 'failed', error: error.message });
        }
      }

      const deleted = results.filter(r => r.status === 'deleted').length;
      const failed = results.filter(r => r.status === 'failed').length;

      console.log(`✅ Deleted ${deleted} expired files, ${failed} failures`);
      return { deleted, failed, details: results };

    } catch (error) {
      console.error('❌ Expired file cleanup failed:', error);
      throw error;
    }
  }

  async deleteFile(fileId) {
    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${this.companyId}/files/${fileId}`,
      {
        method: 'DELETE',
        headers: {
          'X-API-Key': this.apiKey,
          'Content-Type': 'application/json'
        }
      }
    );

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error);
    }

    return true;
  }
}

// Usage
const fileManager = new FileManager('company-uuid', process.env.G2C_API_KEY);
const result = await fileManager.deleteExpiredFiles('object-uuid', 60); // Delete files older than 60 days

Cleanup Operations

class CleanupManager {
  constructor(companyId, apiKey) {
    this.companyId = companyId;
    this.apiKey = apiKey;
  }

  async cleanupFilesByTags(objectId, tagsToDelete = []) {
    try {
      // Get object files
      const objectResponse = await fetch(
        `https://api.g2cplatform.com/v2/companies/${this.companyId}/objects/${objectId}/files`,
        {
          headers: { 'X-API-Key': this.apiKey }
        }
      );

      if (!objectResponse.ok) {
        throw new Error('Failed to get object files');
      }

      const filesData = await objectResponse.json();
      const files = filesData.data || [];

      // Filter files by tags
      const filesToDelete = files.filter(file => {
        return file.tags && file.tags.some(tag => tagsToDelete.includes(tag));
      });

      if (filesToDelete.length === 0) {
        console.log('No files found with specified tags');
        return { deleted: 0, failed: 0 };
      }

      console.log(`Found ${filesToDelete.length} files to delete with tags: ${tagsToDelete.join(', ')}`);

      let deleted = 0;
      let failed = 0;

      for (const file of filesToDelete) {
        try {
          await this.deleteFile(file.id);
          console.log(`✅ Deleted: ${file.fileName}`);
          deleted++;
        } catch (error) {
          console.error(`❌ Failed to delete ${file.fileName}:`, error.message);
          failed++;
        }
      }

      return { deleted, failed };

    } catch (error) {
      console.error('❌ Cleanup operation failed:', error);
      throw error;
    }
  }

  async deleteFile(fileId) {
    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${this.companyId}/files/${fileId}`,
      {
        method: 'DELETE',
        headers: {
          'X-API-Key': this.apiKey,
          'Content-Type': 'application/json'
        }
      }
    );

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error);
    }
  }
}

// Usage
const cleanupManager = new CleanupManager('company-uuid', process.env.G2C_API_KEY);
const result = await cleanupManager.cleanupFilesByTags('object-uuid', ['temporary', 'draft', 'test']);
console.log(`Cleanup completed: ${result.deleted} deleted, ${result.failed} failed`);

User Interface Integration

class FileUI {
  constructor(companyId, apiKey) {
    this.companyId = companyId;
    this.apiKey = apiKey;
  }

  createDeleteButton(fileId, fileName, container) {
    const button = document.createElement('button');
    button.textContent = '🗑️ Delete';
    button.className = 'delete-btn btn-danger';
    button.onclick = () => this.handleDelete(fileId, fileName, button);

    container.appendChild(button);
    return button;
  }

  async handleDelete(fileId, fileName, buttonElement) {
    // Show confirmation dialog
    const confirmed = confirm(`Are you sure you want to delete "${fileName}"?`);
    if (!confirmed) {
      return;
    }

    // Show loading state
    const originalText = buttonElement.textContent;
    buttonElement.disabled = true;
    buttonElement.textContent = '⏳ Deleting...';

    try {
      await this.deleteFile(fileId);

      // Success - remove from UI
      const fileRow = buttonElement.closest('.file-row');
      if (fileRow) {
        fileRow.style.transition = 'opacity 0.3s';
        fileRow.style.opacity = '0';
        setTimeout(() => fileRow.remove(), 300);
      }

      // Show success message
      this.showMessage(`File "${fileName}" deleted successfully`, 'success');

    } catch (error) {
      // Error - restore button
      buttonElement.disabled = false;
      buttonElement.textContent = originalText;

      this.showMessage(`Failed to delete "${fileName}": ${error.message}`, 'error');
    }
  }

  async deleteFile(fileId) {
    const response = await fetch(
      `https://api.g2cplatform.com/v2/companies/${this.companyId}/files/${fileId}`,
      {
        method: 'DELETE',
        headers: {
          'X-API-Key': this.apiKey,
          'Content-Type': 'application/json'
        }
      }
    );

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error);
    }
  }

  showMessage(message, type) {
    // Create and show notification
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;

    document.body.appendChild(notification);

    // Auto-remove after 3 seconds
    setTimeout(() => {
      notification.style.transition = 'opacity 0.3s';
      notification.style.opacity = '0';
      setTimeout(() => notification.remove(), 300);
    }, 3000);
  }
}

// Usage
const fileUI = new FileUI('company-uuid', process.env.G2C_API_KEY);

// Add delete buttons to file list
document.querySelectorAll('.file-item').forEach(fileItem => {
  const fileId = fileItem.dataset.fileId;
  const fileName = fileItem.dataset.fileName;
  const actionsContainer = fileItem.querySelector('.file-actions');

  fileUI.createDeleteButton(fileId, fileName, actionsContainer);
});

Best Practices

Always implement proper safeguards:
  • Require user confirmation for deletions
  • Show clear information about what will be deleted
  • Consider implementing soft delete with restore functionality
  • Keep audit logs of all deletion operations
Handle deletion errors gracefully:
  • Check if file exists before attempting deletion
  • Provide clear error messages to users
  • Log deletion attempts for audit purposes
  • Implement retry logic for network failures
Maintain proper audit trails:
  • Record who deleted files and when
  • Document reasons for deletion
  • Update associated objects with deletion events
  • Maintain deletion logs for compliance
Optimize deletion operations:
  • Use batch operations for multiple files
  • Implement rate limiting to avoid overwhelming the API
  • Handle concurrent deletion requests properly
  • Clean up related data and references

Security Considerations

Access Control

  • File deletion requires appropriate API key permissions
  • Users can only delete files from their company
  • Consider implementing role-based deletion permissions
  • Log all deletion attempts for security auditing

Data Protection

  • Ensure sensitive files are securely deleted
  • Consider data residency and privacy regulations
  • Implement proper backup and recovery procedures
  • Follow data retention policies

Compliance

  • Some industries require retention policies
  • Certain files may not be deletable due to legal requirements
  • Maintain audit trails for regulatory compliance
  • Consider implementing approval workflows for critical files

Next Steps