Categories API
The Categories API allows you to organize and retrieve knowledge items by category. Categories provide a structured way to browse and access your workspace's knowledge base.
What are Categories?
Categories are organizational units that group related knowledge items together. They help users:
- Browse knowledge by topic
- Filter content by subject area
- Organize large knowledge bases
- Create logical content hierarchies
Available Endpoints
List Categories
GET /v1/workspaces/{workspaceId}/categories
Retrieve all categories in your workspace.
Get Category Knowledge
GET /v1/workspaces/{workspaceId}/categories/{categoryId}/knowledge
Get all knowledge items within a specific category.
List Categories
Retrieve all categories defined in your workspace with their metadata and organization information.
Endpoint
GET /v1/workspaces/{workspaceId}/categoriesAuthentication
Requires Bearer token authentication. See Authentication for details.
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
workspaceId | string (UUID) | Yes | The ID of your workspace |
Response
Success Response
Status Code: 200 OK
Headers:
X-API-Version: v1Body:
{
"categories": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Product Documentation",
"description": "All product-related documentation",
"knowledgeCount": 42,
"createdAt": "2025-01-10T10:00:00Z",
"updatedAt": "2025-01-15T14:30:00Z"
},
{
"id": "987fcdeb-51a2-43f7-b8c9-123456789abc",
"name": "Customer Support",
"description": "Support articles and FAQs",
"knowledgeCount": 156,
"createdAt": "2025-01-12T09:00:00Z",
"updatedAt": "2025-01-15T16:45:00Z"
}
]
}Response Fields
| Field | Type | Description |
|---|---|---|
categories | array | Array of category objects |
categories[].id | string (UUID) | Unique identifier for the category |
categories[].name | string | Category name |
categories[].description | string | Category description |
categories[].knowledgeCount | integer | Number of knowledge items in this category |
categories[].createdAt | string (ISO 8601) | Creation timestamp |
categories[].updatedAt | string (ISO 8601) | Last update timestamp |
Examples
Basic Request
curl -X GET \
'https://api.sharely.ai/v1/workspaces/your-workspace-id/categories' \
-H 'Authorization: Bearer YOUR_API_KEY'Response:
{
"categories": [
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"name": "Documentation",
"description": "Technical documentation and guides",
"knowledgeCount": 87,
"createdAt": "2025-01-01T00:00:00Z",
"updatedAt": "2025-01-15T10:30:00Z"
},
{
"id": "456e7890-e12b-34d5-a678-426614174999",
"name": "Training Materials",
"description": "Employee training resources",
"knowledgeCount": 23,
"createdAt": "2025-01-05T12:00:00Z",
"updatedAt": "2025-01-14T09:15: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 getCategories() {
const response = await fetch(
`${BASE_URL}/workspaces/${WORKSPACE_ID}/categories`,
{
headers: {
'Authorization': `Bearer ${API_KEY}`
}
}
);
if (!response.ok) {
throw new Error(`Failed to fetch categories: ${response.statusText}`);
}
const data = await response.json();
return data.categories;
}
// Usage
try {
const categories = await getCategories();
categories.forEach(category => {
console.log(`${category.name}: ${category.knowledgeCount} items`);
});
} 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_categories():
response = requests.get(
f'{BASE_URL}/workspaces/{WORKSPACE_ID}/categories',
headers={'Authorization': f'Bearer {API_KEY}'}
)
response.raise_for_status()
return response.json()['categories']
# Usage
try:
categories = get_categories()
for category in categories:
print(f"{category['name']}: {category['knowledgeCount']} items")
except requests.exceptions.HTTPError as error:
print(f"Error: {error}")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"
}404 Not Found
Workspace not found:
{
"error": "Not Found",
"message": "Workspace not found"
}500 Internal Server Error
Server error:
{
"error": "Internal Server Error",
"message": "Failed to retrieve categories"
}Use Cases
Build Navigation Menu
async function buildCategoryNav() {
const categories = await getCategories();
const navHTML = categories.map(cat => `
<li>
<a href="/category/${cat.id}">
${cat.name} (${cat.knowledgeCount})
</a>
</li>
`).join('');
document.getElementById('category-nav').innerHTML = navHTML;
}Display Category Statistics
async function showCategoryStats() {
const categories = await getCategories();
const totalKnowledge = categories.reduce(
(sum, cat) => sum + cat.knowledgeCount,
0
);
console.log(`Total categories: ${categories.length}`);
console.log(`Total knowledge items: ${totalKnowledge}`);
const avgPerCategory = totalKnowledge / categories.length;
console.log(`Average items per category: ${avgPerCategory.toFixed(1)}`);
}Find Largest Category
async function findLargestCategory() {
const categories = await getCategories();
const largest = categories.reduce((max, cat) =>
cat.knowledgeCount > max.knowledgeCount ? cat : max
);
console.log(`Largest category: ${largest.name} with ${largest.knowledgeCount} items`);
return largest;
}Filter Empty Categories
async function getActiveCategories() {
const categories = await getCategories();
return categories.filter(cat => cat.knowledgeCount > 0);
}Best Practices
Cache Category Lists
Categories don't change frequently, so caching can improve performance:
let categoriesCache = null;
let cacheExpiry = null;
async function getCachedCategories(ttl = 300000) { // 5 minutes
const now = Date.now();
if (categoriesCache && cacheExpiry && now < cacheExpiry) {
return categoriesCache;
}
categoriesCache = await getCategories();
cacheExpiry = now + ttl;
return categoriesCache;
}Handle Empty Response
const data = await getCategories();
if (data.categories.length === 0) {
console.log('No categories found. Create your first category.');
} else {
displayCategories(data.categories);
}Sort Categories
const categories = await getCategories();
// Sort by name
const byName = [...categories].sort((a, b) =>
a.name.localeCompare(b.name)
);
// Sort by knowledge count
const byCount = [...categories].sort((a, b) =>
b.knowledgeCount - a.knowledgeCount
);
// Sort by most recent
const byDate = [...categories].sort((a, b) =>
new Date(b.updatedAt) - new Date(a.updatedAt)
);Notes
Category Management
Categories are typically managed through the Sharely.ai dashboard. The API provides read access for building custom integrations and interfaces.
Knowledge Count
The knowledgeCount field reflects the current number of knowledge items in each category. This count updates automatically as knowledge is added or removed.
Empty Categories
Categories with knowledgeCount: 0 may still appear in the list. These can represent newly created categories or categories where all knowledge has been removed.
Related Endpoints
- Get Category Knowledge - Retrieve knowledge items in a category
- Search Knowledge - Search across all knowledge
- Create Knowledge - Add knowledge to categories