REST API Integration
Direct API access to your Knowledge AI project for custom integrations, automation, and third-party tool connections.
🚀 Overview
The REST API provides:
- Direct Access: Full programmatic access to your knowledge base
- Custom Integrations: Build your own tools and integrations
- Automation: Automate content management and workflows
- Third-Party Connections: Connect with any system that supports HTTP APIs
- Flexible Authentication: Secure API key-based authentication
🔗 API Capabilities
The REST API supports:
- ✅ Unified intelligent search across your knowledge base
- ✅ Create, read, update, and delete notes
- ✅ Folder-based organization and management
- ✅ Relationship analysis and graph connections
- ✅ Tag-based categorization and filtering
- ✅ Semantic search with AI enhancements
- ✅ Bulk operations for content management
📋 Prerequisites
- Active Knowledge AI project
- Project API key
- HTTP client or programming environment
- Basic understanding of REST APIs
⚙️ Quick Start
Step 1: Get Your API Key
- Navigate to your project's API Keys section in Knowledge AI
- Generate a new API key for REST API access
- Copy the API key - you'll use it in the
X-API-Keyheader
Step 2: Get Your Project URL
Your API base URL follows this pattern:
https://api.knowledge-ai.app/api/mcp/project/YOUR_PROJECT_IDReplace YOUR_PROJECT_ID with your actual project ID.
Step 3: Test Connection
Test your connection with a simple API call:
curl -H "X-API-Key: YOUR_API_KEY" \
"https://api.knowledge-ai.app/api/mcp/project/YOUR_PROJECT_ID/notes?limit=5"📖 API Reference
Authentication
All API requests require authentication using an API key in the header:
X-API-Key: YOUR_PROJECT_API_KEYBase URL
https://api.knowledge-ai.app/api/mcp/project/{projectId}Core Endpoints
1. Search Notes (Unified)
POST /notes/search/unified
Intelligent search across your knowledge base with multiple search modes.
curl -X POST \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "authentication patterns",
"mode": "auto",
"intelligence_level": "enhanced",
"limit": 10,
"include_relationships": true
}' \
"https://api.knowledge-ai.app/api/mcp/project/YOUR_PROJECT_ID/notes/search/unified"Request Parameters:
query(string, required): Search querymode(string): Search mode - "auto", "keyword", "semantic", "graph" (default: "auto")intelligence_level(string): "basic" or "enhanced" (default: "enhanced")limit(number): Maximum results to return (default: 20)include_relationships(boolean): Include relationship context (default: true)include_graph_context(boolean): Include graph connections (default: true)include_entity_analysis(boolean): Include entity analysis (default: true)
2. List Notes
GET /notes
Browse existing notes in your project.
curl -H "X-API-Key: YOUR_API_KEY" \
"https://api.knowledge-ai.app/api/mcp/project/YOUR_PROJECT_ID/notes?limit=20&virtual_folder=research"Query Parameters:
limit(number): Maximum notes to return (default: 20)virtual_folder(string): Filter by folder path (e.g., "research", "projects/client-work")
3. Create Note
POST /notes
Create new content in your knowledge base.
curl -X POST \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"title": "API Integration Guide",
"content": "# API Integration\n\nThis guide covers...",
"virtual_folder": "documentation",
"tags": ["api", "integration", "guide"]
}' \
"https://api.knowledge-ai.app/api/mcp/project/YOUR_PROJECT_ID/notes"Request Body:
title(string, required): Note title (avoid # symbol)content(string, required): Note content (supports markdown)virtual_folder(string): Folder path for organizationtags(array): Array of tag strings
4. Get Note
GET /notes/{noteId}
Retrieve a specific note by ID.
curl -H "X-API-Key: YOUR_API_KEY" \
"https://api.knowledge-ai.app/api/mcp/project/YOUR_PROJECT_ID/notes/NOTE_ID"5. Update Note
PATCH /notes/{noteId}
Update existing note content or metadata.
curl -X PATCH \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"old_str": "old content to replace",
"new_str": "new replacement content",
"preview": false
}' \
"https://api.knowledge-ai.app/api/mcp/project/YOUR_PROJECT_ID/notes/NOTE_ID"Request Body:
old_str(string): Text to replace (for content edits)new_str(string): Replacement texttitle(string): New title (for metadata updates)tags(array): Updated tags arraypreview(boolean): Preview changes without applying (default: false)
6. Get Connections
GET /graph/notes/{noteId}/connections
Get existing connections and AI-suggested relationships for a note.
curl -H "X-API-Key: YOUR_API_KEY" \
"https://api.knowledge-ai.app/api/mcp/project/YOUR_PROJECT_ID/graph/notes/NOTE_ID/connections"7. Add Connection
POST /graph/notes/{noteId}/links
Create connections between related content.
curl -X POST \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"target_note_id": "TARGET_NOTE_ID",
"relationship_type": "related_to"
}' \
"https://api.knowledge-ai.app/api/mcp/project/YOUR_PROJECT_ID/graph/notes/NOTE_ID/links"Request Body:
target_note_id(string, required): ID of the target noterelationship_type(string): Type of relationship - "related_to", "part_of", "similar_to", "feature_of" (default: "related_to")
💻 Code Examples
Python Example
import requests
import json
class KnowledgeAI:
def __init__(self, project_id, api_key):
self.project_id = project_id
self.api_key = api_key
self.base_url = f"https://api.knowledge-ai.app/api/mcp/project/{project_id}"
self.headers = {
"X-API-Key": api_key,
"Content-Type": "application/json"
}
def search(self, query, limit=10):
"""Search the knowledge base"""
url = f"{self.base_url}/notes/search/unified"
data = {
"query": query,
"mode": "auto",
"intelligence_level": "enhanced",
"limit": limit,
"include_relationships": True
}
response = requests.post(url, headers=self.headers, json=data)
return response.json()
def create_note(self, title, content, folder=None, tags=None):
"""Create a new note"""
url = f"{self.base_url}/notes"
data = {
"title": title,
"content": content
}
if folder:
data["virtual_folder"] = folder
if tags:
data["tags"] = tags
response = requests.post(url, headers=self.headers, json=data)
return response.json()
def get_note(self, note_id):
"""Get a specific note"""
url = f"{self.base_url}/notes/{note_id}"
response = requests.get(url, headers=self.headers)
return response.json()
def update_note(self, note_id, old_str, new_str):
"""Update note content"""
url = f"{self.base_url}/notes/{note_id}"
data = {
"old_str": old_str,
"new_str": new_str
}
response = requests.patch(url, headers=self.headers, json=data)
return response.json()
# Usage example
kb = KnowledgeAI("your-project-id", "your-api-key")
# Search for content
results = kb.search("authentication patterns")
print(f"Found {len(results.get('results', []))} results")
# Create a new note
note = kb.create_note(
title="Meeting Notes",
content="# Team Meeting\n\nDiscussed API improvements...",
folder="meetings",
tags=["meeting", "api", "team"]
)
print(f"Created note with ID: {note.get('id')}")JavaScript/Node.js Example
class KnowledgeAI {
constructor(projectId, apiKey) {
this.projectId = projectId;
this.apiKey = apiKey;
this.baseUrl = `https://api.knowledge-ai.app/api/mcp/project/${projectId}`;
this.headers = {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
};
}
async search(query, limit = 10) {
const response = await fetch(`${this.baseUrl}/notes/search/unified`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify({
query,
mode: 'auto',
intelligence_level: 'enhanced',
limit,
include_relationships: true
})
});
return response.json();
}
async createNote(title, content, folder = null, tags = null) {
const data = { title, content };
if (folder) data.virtual_folder = folder;
if (tags) data.tags = tags;
const response = await fetch(`${this.baseUrl}/notes`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify(data)
});
return response.json();
}
async getNote(noteId) {
const response = await fetch(`${this.baseUrl}/notes/${noteId}`, {
headers: this.headers
});
return response.json();
}
async updateNote(noteId, oldStr, newStr) {
const response = await fetch(`${this.baseUrl}/notes/${noteId}`, {
method: 'PATCH',
headers: this.headers,
body: JSON.stringify({
old_str: oldStr,
new_str: newStr
})
});
return response.json();
}
}
// Usage
const kb = new KnowledgeAI('your-project-id', 'your-api-key');
// Search and create workflow
async function example() {
// Search for existing content
const results = await kb.search('project roadmap');
if (results.results.length === 0) {
// Create new roadmap if none exists
const note = await kb.createNote(
'Project Roadmap',
'# Project Roadmap\n\n## Q1 Goals\n- Feature A\n- Feature B',
'planning',
['roadmap', 'planning', 'goals']
);
console.log('Created new roadmap:', note.id);
} else {
console.log('Found existing roadmap:', results.results[0].title);
}
}cURL Scripts
Search Script (search.sh):
#!/bin/bash
API_KEY="your-api-key"
PROJECT_ID="your-project-id"
QUERY="$1"
if [ -z "$QUERY" ]; then
echo "Usage: ./search.sh 'your search query'"
exit 1
fi
curl -X POST \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d "{\"query\": \"$QUERY\", \"limit\": 10}" \
"https://api.knowledge-ai.app/api/mcp/project/$PROJECT_ID/notes/search/unified" | jq '.'Create Note Script (create-note.sh):
#!/bin/bash
API_KEY="your-api-key"
PROJECT_ID="your-project-id"
TITLE="$1"
CONTENT="$2"
FOLDER="$3"
if [ -z "$TITLE" ] || [ -z "$CONTENT" ]; then
echo "Usage: ./create-note.sh 'Title' 'Content' 'folder'"
exit 1
fi
DATA="{\"title\": \"$TITLE\", \"content\": \"$CONTENT\""
if [ -n "$FOLDER" ]; then
DATA="${DATA}, \"virtual_folder\": \"$FOLDER\""
fi
DATA="${DATA}}"
curl -X POST \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d "$DATA" \
"https://api.knowledge-ai.app/api/mcp/project/$PROJECT_ID/notes" | jq '.'🔧 Common Use Cases
1. Content Migration
Migrate content from other systems:
# Example: Migrate from Notion export
import json
def migrate_from_notion(notion_export_file):
with open(notion_export_file, 'r') as f:
data = json.load(f)
for item in data['pages']:
kb.create_note(
title=item['title'],
content=item['content'],
folder='imported/notion',
tags=['migrated', 'notion']
)2. Automated Documentation
Generate documentation from code:
def document_api_endpoint(endpoint_info):
content = f"""
# {endpoint_info['name']} API Endpoint
## Overview
{endpoint_info['description']}
## Request Format
```json
{json.dumps(endpoint_info['request_example'], indent=2)}Response Format
{json.dumps(endpoint_info['response_example'], indent=2)}"""
return kb.create_note(
title=f"API: {endpoint_info['name']}",
content=content,
folder="api-docs",
tags=["api", "documentation", "auto-generated"]
)
### 3. Content Synchronization
Keep content synchronized with external systems:
```python
def sync_with_external_system():
# Get recent changes from external system
external_changes = get_external_changes()
for change in external_changes:
# Search for existing content
results = kb.search(change['identifier'])
if results['results']:
# Update existing
note_id = results['results'][0]['id']
kb.update_note(note_id, change['old_content'], change['new_content'])
else:
# Create new
kb.create_note(
title=change['title'],
content=change['content'],
folder=change['folder']
)4. Analytics and Reporting
Analyze your knowledge base:
def generate_content_report():
# Get all notes
all_notes = []
offset = 0
limit = 100
while True:
batch = kb.list_notes(limit=limit, offset=offset)
if not batch['results']:
break
all_notes.extend(batch['results'])
offset += limit
# Analyze content
total_notes = len(all_notes)
folders = {}
tags = {}
for note in all_notes:
# Count by folder
folder = note.get('virtual_folder', 'root')
folders[folder] = folders.get(folder, 0) + 1
# Count by tags
for tag in note.get('tags', []):
tags[tag] = tags.get(tag, 0) + 1
print(f"Total Notes: {total_notes}")
print("Top Folders:", sorted(folders.items(), key=lambda x: x[1], reverse=True)[:5])
print("Top Tags:", sorted(tags.items(), key=lambda x: x[1], reverse=True)[:10])🔒 Security & Best Practices
API Key Management
- Environment Variables: Store API keys in environment variables
- Key Rotation: Regularly rotate your API keys
- Scope Limitation: Use project-specific keys to limit access scope
- Monitoring: Monitor API usage for unusual activity
Rate Limiting
- Respect Limits: Follow API rate limiting guidelines
- Batch Operations: Use bulk operations when available
- Exponential Backoff: Implement retry logic with exponential backoff
- Caching: Cache responses when appropriate
Error Handling
import time
from requests.exceptions import RequestException
def api_call_with_retry(func, max_retries=3, backoff_factor=1):
"""Make API call with retry logic"""
for attempt in range(max_retries):
try:
response = func()
if response.status_code == 429: # Rate limited
wait_time = backoff_factor * (2 ** attempt)
time.sleep(wait_time)
continue
response.raise_for_status()
return response.json()
except RequestException as e:
if attempt == max_retries - 1:
raise e
time.sleep(backoff_factor * (2 ** attempt))
return NoneData Validation
def validate_note_data(title, content):
"""Validate note data before API call"""
if not title or len(title.strip()) == 0:
raise ValueError("Title cannot be empty")
if not content or len(content.strip()) == 0:
raise ValueError("Content cannot be empty")
if len(title) > 200:
raise ValueError("Title too long (max 200 characters)")
if len(content) > 1000000: # 1MB limit
raise ValueError("Content too large (max 1MB)")
return True📊 Response Formats
Search Response
{
"results": [
{
"id": "note-123",
"title": "Authentication Patterns",
"content": "# Authentication Patterns\n\nThis document covers...",
"virtual_folder": "security",
"tags": ["auth", "security", "patterns"],
"created_at": "2025-01-14T10:00:00Z",
"updated_at": "2025-01-14T15:30:00Z",
"score": 0.95,
"relationships": [
{
"id": "note-456",
"title": "OAuth Implementation",
"relationship_type": "related_to",
"strength": 0.8
}
]
}
],
"total": 1,
"query_analysis": {
"intent": "search",
"entities": ["authentication"],
"suggested_filters": ["security", "implementation"]
}
}Note Response
{
"id": "note-123",
"title": "Meeting Notes - Q1 Planning",
"content": "# Q1 Planning Meeting\n\n## Attendees\n- Alice\n- Bob\n\n## Goals\n- Feature X\n- Feature Y",
"virtual_folder": "meetings/2025",
"tags": ["meeting", "planning", "q1"],
"created_at": "2025-01-14T10:00:00Z",
"updated_at": "2025-01-14T15:30:00Z",
"metadata": {
"word_count": 85,
"reading_time": "1 min",
"last_editor": "user-456"
}
}Error Response
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Title cannot be empty",
"details": {
"field": "title",
"validation": "required"
}
},
"request_id": "req-789"
}🚀 Advanced Integration Patterns
Webhook Integration
Set up webhooks to receive real-time updates:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhook/knowledge-ai', methods=['POST'])
def handle_webhook():
event = request.json
if event['type'] == 'note.created':
handle_note_created(event['data'])
elif event['type'] == 'note.updated':
handle_note_updated(event['data'])
return jsonify({'status': 'received'})
def handle_note_created(note_data):
# Send notification, update cache, etc.
print(f"New note created: {note_data['title']}")
def handle_note_updated(note_data):
# Update external systems, invalidate cache, etc.
print(f"Note updated: {note_data['title']}")Batch Processing
Process multiple notes efficiently:
def batch_update_tags():
"""Add 'reviewed' tag to all notes in 'draft' folder"""
notes = kb.list_notes(virtual_folder='draft', limit=1000)
for note in notes['results']:
current_tags = note.get('tags', [])
if 'reviewed' not in current_tags:
new_tags = current_tags + ['reviewed']
kb.update_note(note['id'], tags=new_tags)
print(f"Updated tags for: {note['title']}")Smart Content Management
Implement intelligent content workflows:
def smart_content_workflow(user_input):
"""Intelligent content creation workflow"""
# 1. Search for existing content first
search_results = kb.search(user_input, limit=5)
if search_results['results']:
# Content exists - suggest update instead
existing = search_results['results'][0]
print(f"Found similar content: '{existing['title']}'")
print("Consider updating existing content instead of creating new.")
return existing
# 2. Generate content using AI assistance
# (Integration with your AI service)
generated_content = generate_ai_content(user_input)
# 3. Create new note with AI-generated content
note = kb.create_note(
title=generated_content['title'],
content=generated_content['content'],
folder=generated_content['suggested_folder'],
tags=generated_content['suggested_tags']
)
# 4. Find and create relationships
related_notes = kb.search(
f"related to {generated_content['title']}",
limit=3
)
for related in related_notes['results']:
kb.add_connection(
note['id'],
related['id'],
'related_to'
)
return note📞 Support
Need help with REST API integration?
- Email: feedback@knowledge-ai.app
- Documentation: docs.knowledge-ai.app
- API Reference: docs.knowledge-ai.app/api
- Examples Repository: github.com/knowledge-ai/examples
When Contacting Support
Include:
- Your project ID
- API endpoint you're trying to use
- Request/response details (remove sensitive data)
- Programming language and environment
- Error messages or unexpected behavior
Last updated: 2025-01-14