Get Category Knowledge

Retrieve all knowledge items within a specific category. This endpoint returns the full list of knowledge associated with a category ID.

Endpoint

GET /v1/workspaces/{workspaceId}/categories/{categoryId}/knowledge

Authentication

Requires Bearer token authentication. See Authentication for details.

Path Parameters

ParameterTypeRequiredDescription
workspaceIdstring (UUID)YesThe ID of your workspace
categoryIdstring (UUID)YesThe ID of the category

Response

Success Response

Status Code: 200 OK

Headers:

X-API-Version: v1

Body:

{
  "knowledge": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "title": "Getting Started Guide",
      "type": "FILE",
      "url": "https://storage.example.com/guide.pdf",
      "content": "This guide helps you get started...",
      "metadata": {
        "author": "Jane Smith",
        "version": "2.0"
      },
      "categoryId": "123e4567-e89b-12d3-a456-426614174000",
      "createdAt": "2025-01-10T14:20:00Z",
      "updatedAt": "2025-01-15T10:30:00Z"
    },
    {
      "id": "987fcdeb-51a2-43f7-b8c9-123456789abc",
      "title": "API Reference",
      "type": "URL",
      "url": "https://docs.example.com/api",
      "content": "Complete API reference documentation...",
      "metadata": {
        "department": "Engineering"
      },
      "categoryId": "123e4567-e89b-12d3-a456-426614174000",
      "createdAt": "2025-01-12T09:15:00Z",
      "updatedAt": "2025-01-14T16:45:00Z"
    }
  ]
}

Response Fields

FieldTypeDescription
knowledgearrayArray of knowledge objects in this category
knowledge[].idstring (UUID)Unique identifier for the knowledge item
knowledge[].titlestringTitle of the knowledge item
knowledge[].typestringKnowledge type: FILE, URL, LINK, or STRING
knowledge[].urlstringURL or file path
knowledge[].contentstringContent excerpt or full content
knowledge[].metadataobjectCustom metadata
knowledge[].categoryIdstring (UUID)Category ID (matches path parameter)
knowledge[].createdAtstring (ISO 8601)Creation timestamp
knowledge[].updatedAtstring (ISO 8601)Last update timestamp

Examples

Basic Request

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

Response:

{
  "knowledge": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "title": "Product Documentation",
      "type": "FILE",
      "url": "https://storage.example.com/product-docs.pdf",
      "content": "Complete product documentation...",
      "metadata": {
        "version": "1.0",
        "language": "en"
      },
      "categoryId": "123e4567-e89b-12d3-a456-426614174000",
      "createdAt": "2025-01-10T10:00:00Z",
      "updatedAt": "2025-01-10T10:00:00Z"
    }
  ]
}

JavaScript Example

const API_KEY = 'YOUR_API_KEY';
const WORKSPACE_ID = 'your-workspace-id';
const BASE_URL = 'https://api.sharely.ai/v1';
 
async function getCategoryKnowledge(categoryId) {
  const response = await fetch(
    `${BASE_URL}/workspaces/${WORKSPACE_ID}/categories/${categoryId}/knowledge`,
    {
      headers: {
        'Authorization': `Bearer ${API_KEY}`
      }
    }
  );
 
  if (!response.ok) {
    throw new Error(`Failed to fetch knowledge: ${response.statusText}`);
  }
 
  const data = await response.json();
  return data.knowledge;
}
 
// Usage
try {
  const categoryId = '123e4567-e89b-12d3-a456-426614174000';
  const knowledge = await getCategoryKnowledge(categoryId);
 
  console.log(`Found ${knowledge.length} knowledge items`);
  knowledge.forEach(item => {
    console.log(`- ${item.title} (${item.type})`);
  });
} catch (error) {
  console.error('Error:', error.message);
}

Python Example

import requests
 
API_KEY = 'YOUR_API_KEY'
WORKSPACE_ID = 'your-workspace-id'
BASE_URL = 'https://api.sharely.ai/v1'
 
def get_category_knowledge(category_id):
    response = requests.get(
        f'{BASE_URL}/workspaces/{WORKSPACE_ID}/categories/{category_id}/knowledge',
        headers={'Authorization': f'Bearer {API_KEY}'}
    )
 
    response.raise_for_status()
    return response.json()['knowledge']
 
# Usage
try:
    category_id = '123e4567-e89b-12d3-a456-426614174000'
    knowledge = get_category_knowledge(category_id)
 
    print(f"Found {len(knowledge)} knowledge items")
    for item in knowledge:
        print(f"- {item['title']} ({item['type']})")
except requests.exceptions.HTTPError as error:
    print(f"Error: {error}")

Browse All Categories

Combine with the list categories endpoint to browse all knowledge:

async function browseAllKnowledge() {
  // Get all categories
  const categoriesResponse = await fetch(
    `${BASE_URL}/workspaces/${WORKSPACE_ID}/categories`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );
 
  const { categories } = await categoriesResponse.json();
 
  // Get knowledge for each category
  for (const category of categories) {
    const knowledge = await getCategoryKnowledge(category.id);
 
    console.log(`\n${category.name} (${knowledge.length} items):`);
    knowledge.forEach(item => {
      console.log(`  - ${item.title}`);
    });
  }
}

Error Responses

401 Unauthorized

Invalid or missing API key:

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

403 Forbidden

Insufficient permissions:

{
  "error": "Forbidden",
  "message": "Insufficient permissions for this workspace or category"
}

404 Not Found

Category not found:

{
  "error": "Not Found",
  "message": "Category not found"
}

Invalid workspace:

{
  "error": "Not Found",
  "message": "Workspace not found"
}

500 Internal Server Error

Server error:

{
  "error": "Internal Server Error",
  "message": "Failed to retrieve knowledge items"
}

Use Cases

Display Category Contents

async function displayCategoryContents(categoryId) {
  const knowledge = await getCategoryKnowledge(categoryId);
 
  const html = knowledge.map(item => `
    <div class="knowledge-item">
      <h3>${item.title}</h3>
      <p>${item.content.substring(0, 200)}...</p>
      <span class="type-badge">${item.type}</span>
    </div>
  `).join('');
 
  document.getElementById('category-content').innerHTML = html;
}

Export Category Data

async function exportCategory(categoryId, format = 'json') {
  const knowledge = await getCategoryKnowledge(categoryId);
 
  if (format === 'json') {
    return JSON.stringify(knowledge, null, 2);
  }
 
  if (format === 'csv') {
    const headers = 'ID,Title,Type,URL,Created\n';
    const rows = knowledge.map(item =>
      `${item.id},${item.title},${item.type},${item.url},${item.createdAt}`
    ).join('\n');
 
    return headers + rows;
  }
}

Check Category Size

async function checkCategorySize(categoryId) {
  const knowledge = await getCategoryKnowledge(categoryId);
 
  const totalSize = knowledge.length;
  const byType = knowledge.reduce((acc, item) => {
    acc[item.type] = (acc[item.type] || 0) + 1;
    return acc;
  }, {});
 
  console.log(`Total items: ${totalSize}`);
  console.log('By type:', byType);
 
  return { totalSize, byType };
}

Find Knowledge by Metadata

async function findByMetadata(categoryId, key, value) {
  const knowledge = await getCategoryKnowledge(categoryId);
 
  return knowledge.filter(item =>
    item.metadata && item.metadata[key] === value
  );
}
 
// Example: Find all knowledge by a specific author
const authorKnowledge = await findByMetadata(
  categoryId,
  'author',
  'John Doe'
);

Get Recent Updates

async function getRecentUpdates(categoryId, days = 7) {
  const knowledge = await getCategoryKnowledge(categoryId);
 
  const cutoffDate = new Date();
  cutoffDate.setDate(cutoffDate.getDate() - days);
 
  return knowledge.filter(item => {
    const updatedAt = new Date(item.updatedAt);
    return updatedAt >= cutoffDate;
  }).sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt));
}

Best Practices

Handle Empty Categories

const knowledge = await getCategoryKnowledge(categoryId);
 
if (knowledge.length === 0) {
  console.log('This category is empty. Add knowledge to get started.');
} else {
  displayKnowledge(knowledge);
}

Pagination for Large Categories

For categories with many items, implement client-side pagination:

function paginateKnowledge(knowledge, page = 1, pageSize = 20) {
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
 
  return {
    items: knowledge.slice(start, end),
    page,
    pageSize,
    totalPages: Math.ceil(knowledge.length / pageSize),
    totalItems: knowledge.length
  };
}

Cache Category Data

const categoryCache = new Map();
 
async function getCachedCategoryKnowledge(categoryId, ttl = 300000) {
  const cached = categoryCache.get(categoryId);
 
  if (cached && Date.now() < cached.expiry) {
    return cached.data;
  }
 
  const knowledge = await getCategoryKnowledge(categoryId);
 
  categoryCache.set(categoryId, {
    data: knowledge,
    expiry: Date.now() + ttl
  });
 
  return knowledge;
}

Filter by Type

async function getKnowledgeByType(categoryId, type) {
  const knowledge = await getCategoryKnowledge(categoryId);
 
  return knowledge.filter(item => item.type === type);
}
 
// Get only files
const files = await getKnowledgeByType(categoryId, 'FILE');
 
// Get only URLs
const urls = await getKnowledgeByType(categoryId, 'URL');

Sort Results

async function getSortedKnowledge(categoryId, sortBy = 'title') {
  const knowledge = await getCategoryKnowledge(categoryId);
 
  const sortFunctions = {
    'title': (a, b) => a.title.localeCompare(b.title),
    'date': (a, b) => new Date(b.createdAt) - new Date(a.createdAt),
    'type': (a, b) => a.type.localeCompare(b.type)
  };
 
  return knowledge.sort(sortFunctions[sortBy] || sortFunctions.title);
}

Notes

Knowledge Ordering

Knowledge items are returned in the order they were added to the category. Use client-side sorting if you need a different order.

Content Excerpts

The content field may contain excerpts for large documents. Full content retrieval may require additional processing.

Category Permissions

Only knowledge items you have permission to access will be returned. Items with restricted access will be filtered out automatically.

Real-Time Updates

The response reflects the current state of the category. Recently added or deleted knowledge is immediately reflected.

Related Endpoints