Delete Knowledge

Delete a knowledge item from your workspace. Optionally cascade delete to remove all related child knowledge items using a dedicated endpoint.

Endpoints

Delete Single Knowledge Item

DELETE /v1/workspaces/{workspaceId}/knowledge/{knowledgeId}

Delete a single knowledge item.

Delete Knowledge with Children

DELETE /v1/workspaces/{workspaceId}/knowledge/{knowledgeId}/children

Delete a knowledge item and all its children in one operation.

Authentication

Requires Bearer token authentication. See Authentication for details.

Path Parameters

ParameterTypeRequiredDescription
workspaceIdstring (UUID)YesThe ID of your workspace
knowledgeIdstring (UUID)YesThe ID of the knowledge item to delete

Understanding Knowledge Hierarchies

Some knowledge types automatically create parent-child relationships forming a tree structure. Understanding these relationships is essential for choosing the correct deletion method.

Knowledge Types That Create Children

The following knowledge types automatically create child knowledge items:

  • WEBSITE - When you add a website URL, the system crawls it and creates a child knowledge item for each discovered page
  • Folders (OneDrive, Google Drive) - Each file within the folder becomes a child knowledge item
  • SHOPIFY_STORE - Each product in the store becomes a child knowledge item
  • ELASTICSEARCH_INDEX - Each indexed document becomes a child knowledge item

Example Hierarchy

When you create a WEBSITE knowledge item:

Parent: https://docs.example.com (WEBSITE)
├── Child: https://docs.example.com/getting-started (WEBSITE)
├── Child: https://docs.example.com/api-reference (WEBSITE)
└── Child: https://docs.example.com/tutorials (WEBSITE)

If you later try to delete only the parent using the regular delete endpoint, the operation will fail to prevent orphaning the child pages.

Single Files vs. Hierarchical Knowledge

  • Single items (FILE, URL without crawling, LINK, STRING) - Have no children, can be deleted with regular endpoint
  • Hierarchical items (WEBSITE, folders, stores) - Have children, require cascade delete endpoint

Deletion Modes

Single Item Delete

DELETE /v1/workspaces/{workspaceId}/knowledge/{knowledgeId}

Deletes only the specified knowledge item. Important: This endpoint will fail if the knowledge item has children.

  • Processing: Synchronous, immediate response
  • Use case: Removing a single knowledge item that has no children (FILE, URL, LINK, STRING)
  • Speed: Fast (< 1 second)
  • Behavior: Returns an error if children exist to prevent orphaning child items

Cascade Delete (With Children)

DELETE /v1/workspaces/{workspaceId}/knowledge/{knowledgeId}/children

Deletes the knowledge item and all its children recursively.

  • Processing: Asynchronous background job for complex trees
  • Use case: Removing a parent item and all its descendants
  • Speed: Depends on number of children (may take several minutes for large trees)

Response

Success Response

Status Code: 200 OK

Headers:

X-API-Version: v1

Body:

{
  "success": true
}

Examples

Delete Single Knowledge Item

Delete a specific knowledge item:

curl -X DELETE \
  'https://api.sharely.ai/v1/workspaces/your-workspace-id/knowledge/123e4567-e89b-12d3-a456-426614174000' \
  -H 'Authorization: Bearer YOUR_API_KEY'

Response:

{
  "success": true
}

Delete with All Children

Delete a knowledge item and all its children using the dedicated endpoint:

curl -X DELETE \
  'https://api.sharely.ai/v1/workspaces/your-workspace-id/knowledge/123e4567-e89b-12d3-a456-426614174000/children' \
  -H 'Authorization: Bearer YOUR_API_KEY'

Response:

{
  "success": true,
  "message": "Knowledge and children deletion queued",
  "jobId": "job-550e8400-e29b-41d4-a716-446655440000"
}

Batch Delete Multiple Items

# Delete multiple knowledge items
KNOWLEDGE_IDS=(
  "123e4567-e89b-12d3-a456-426614174000"
  "987fcdeb-51a2-43f7-b8c9-123456789abc"
  "456e7890-e12b-34d5-a678-426614174999"
)
 
for id in "${KNOWLEDGE_IDS[@]}"
do
  curl -X DELETE \
    "https://api.sharely.ai/v1/workspaces/your-workspace-id/knowledge/$id" \
    -H 'Authorization: Bearer YOUR_API_KEY'
  echo "Deleted: $id"
done

JavaScript Example

const API_KEY = 'YOUR_API_KEY';
const WORKSPACE_ID = 'your-workspace-id';
const BASE_URL = 'https://api.sharely.ai/v1';
 
async function deleteKnowledge(knowledgeId, withChildren = false) {
  const url = withChildren
    ? `${BASE_URL}/workspaces/${WORKSPACE_ID}/knowledge/${knowledgeId}/children`
    : `${BASE_URL}/workspaces/${WORKSPACE_ID}/knowledge/${knowledgeId}`;
 
  const response = await fetch(url, {
    method: 'DELETE',
    headers: {
      'Authorization': `Bearer ${API_KEY}`
    }
  });
 
  if (!response.ok) {
    throw new Error(`Delete failed: ${response.statusText}`);
  }
 
  return await response.json();
}
 
// Usage - Delete single item
try {
  await deleteKnowledge('123e4567-e89b-12d3-a456-426614174000');
  console.log('Knowledge deleted successfully');
} catch (error) {
  console.error('Delete failed:', error.message);
}
 
// Usage - Delete with all children
try {
  const result = await deleteKnowledge('123e4567-e89b-12d3-a456-426614174000', true);
  console.log('Deletion queued:', result.jobId);
} catch (error) {
  console.error('Delete failed:', error.message);
}

Python Example

import requests
 
API_KEY = 'YOUR_API_KEY'
WORKSPACE_ID = 'your-workspace-id'
BASE_URL = 'https://api.sharely.ai/v1'
 
def delete_knowledge(knowledge_id, with_children=False):
    if with_children:
        url = f'{BASE_URL}/workspaces/{WORKSPACE_ID}/knowledge/{knowledge_id}/children'
    else:
        url = f'{BASE_URL}/workspaces/{WORKSPACE_ID}/knowledge/{knowledge_id}'
 
    response = requests.delete(
        url,
        headers={'Authorization': f'Bearer {API_KEY}'}
    )
 
    response.raise_for_status()
    return response.json()
 
# Usage - Delete single item
try:
    result = delete_knowledge('123e4567-e89b-12d3-a456-426614174000')
    print(f"Delete successful: {result['success']}")
except requests.exceptions.HTTPError as error:
    print(f"Delete failed: {error}")
 
# Usage - Delete with all children
try:
    result = delete_knowledge('123e4567-e89b-12d3-a456-426614174000', with_children=True)
    print(f"Deletion queued: {result['jobId']}")
except requests.exceptions.HTTPError as error:
    print(f"Delete failed: {error}")

Error Responses

400 Bad Request

Invalid knowledge ID format:

{
  "error": "Bad Request",
  "message": "Invalid knowledge ID format"
}

Attempting to delete a knowledge item that has children:

{
  "error": "Bad Request",
  "message": "This knowledge has children, remove them first"
}

Solution: Use the cascade delete endpoint /knowledge/{knowledgeId}/children instead.

401 Unauthorized

Invalid or missing API key:

{
  "error": "Unauthorized",
  "message": "Invalid or missing API key"
}

403 Forbidden

Insufficient permissions to delete this knowledge item:

{
  "error": "Forbidden",
  "message": "Insufficient permissions to delete this knowledge item"
}

404 Not Found

Knowledge item doesn't exist or was already deleted:

{
  "error": "Not Found",
  "message": "Knowledge item not found"
}

500 Internal Server Error

Server error during deletion:

{
  "error": "Internal Server Error",
  "message": "Failed to delete knowledge item"
}

Use Cases

Delete Single Files or URLs

Use the regular delete endpoint for knowledge items without children:

// Delete a single uploaded file
await deleteKnowledge('file-knowledge-id');
 
// Delete a single URL (not crawled)
await deleteKnowledge('url-knowledge-id');
 
// Delete a link reference
await deleteKnowledge('link-knowledge-id');

Delete an Entire Website

When you delete a website knowledge item, you must use the cascade delete endpoint:

// This will FAIL because the website has child pages
try {
  await deleteKnowledge('website-id');
} catch (error) {
  console.error('Error: This knowledge has children, remove them first');
}
 
// Correct: Use cascade delete for websites
await deleteKnowledge('website-id', true);
// Deletes the parent website AND all crawled page children

Delete Folders and Their Contents

Folders require cascade delete to remove all contained files:

// Delete OneDrive folder and all files within it
await deleteKnowledge('onedrive-folder-id', true);
 
// Delete Google Drive folder and all files within it
await deleteKnowledge('google-drive-folder-id', true);

Safe Deletion with Validation

Check if a knowledge item has children before attempting deletion:

// Get knowledge details first
const knowledge = await getKnowledge(knowledgeId);
 
// Check if it's a hierarchical type
const hierarchicalTypes = ['WEBSITE', 'ONEDRIVE_FOLDER', 'GOOGLE_DRIVE_FOLDER', 'SHOPIFY_STORE'];
 
if (hierarchicalTypes.includes(knowledge.type)) {
  // Use cascade delete for hierarchical types
  await deleteKnowledge(knowledgeId, true);
} else {
  // Use regular delete for single items
  await deleteKnowledge(knowledgeId, false);
}

Batch Delete Test Data

Clean up test knowledge items (that don't have children):

// Delete all test knowledge items
const testIds = await searchKnowledge({ title: 'TEST-' });
for (const item of testIds) {
  // Only works if test items don't have children
  await deleteKnowledge(item.id, false);
}

Cascade Delete Behavior

When using /knowledge/{knowledgeId}/children endpoint:

  1. Processing: The deletion is queued as a background job
  2. Dependencies: All child knowledge items are identified recursively
  3. Deletion Order: Children are deleted before parents to maintain referential integrity
  4. Completion: The job continues until all items are removed
  5. Monitoring: Use the returned jobId to monitor deletion progress

What Gets Deleted

  • The specified knowledge item
  • All direct children
  • All descendants in the knowledge tree (recursively)
  • Associated metadata and permissions
  • Related audience and role assignments

What Doesn't Get Deleted

  • Knowledge items in other categories (unless they're children)
  • User-created references in other workspaces
  • External files on original sources
  • Shared metadata schemas

Best Practices

Verify Before Deleting

Always confirm the knowledge ID before deletion:

const knowledge = await getKnowledge(knowledgeId);
console.log(`About to delete: ${knowledge.title}`);
const confirmed = await confirmWithUser();
if (confirmed) {
  await deleteKnowledge(knowledgeId);
}

Use Cascade Carefully

Cascade delete is powerful but irreversible:

// Preview what will be deleted
const children = await getKnowledgeChildren(knowledgeId);
console.log(`Will delete ${children.length + 1} items`);
 
// Only then proceed
await deleteKnowledge(knowledgeId, true);

Implement Soft Deletes in Your App

Consider implementing soft deletes in your application:

// Mark as deleted without actually deleting
await updateKnowledgeMetadata(knowledgeId, {
  deletedAt: new Date().toISOString(),
  deletedBy: userId
});
 
// Later, permanently delete
await deleteKnowledge(knowledgeId);

Handle 404 Gracefully

A 404 might mean the item was already deleted:

try {
  await deleteKnowledge(knowledgeId);
} catch (error) {
  if (error.status === 404) {
    console.log('Already deleted or never existed');
  } else {
    throw error;
  }
}

Log Deletions

Always log deletion operations for audit trails:

await deleteKnowledge(knowledgeId);
await logAuditEvent({
  action: 'KNOWLEDGE_DELETED',
  knowledgeId: knowledgeId,
  userId: currentUser.id,
  timestamp: new Date()
});

Notes

Irreversible Operation

Deletion is permanent and cannot be undone. Ensure you have backups or confirmation flows in your application.

Search Index Updates

Deleted knowledge items are removed from search indexes. This may take a few minutes to fully propagate.

Storage Cleanup

Associated files in storage are marked for cleanup and removed during routine maintenance.

Cascade Performance

Cascade deletes with many children may take several minutes. The operation is queued as a background job to prevent timeouts.

Permission Requirements

Users must have delete permissions on the knowledge item. Workspace admins can delete any knowledge in their workspace.

Related Endpoints