API Usage Examples
Practical examples and code samples for common API operations.
🚀 Quick Start Examples
Basic Authentication
// Set up API base configuration
const API_BASE_URL = 'https://api.leafmove.com';
const API_TOKEN = 'your-api-token';
// Create request headers
const headers = {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json'
};
Get Data Example
// Get document list
async function getDocuments() {
try {
const response = await fetch(`${API_BASE_URL}/api/documents`, {
method: 'GET',
headers: headers
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to get documents:', error);
throw error;
}
}
Create Data Example
// Create new document
async function createDocument(documentData) {
try {
const response = await fetch(`${API_BASE_URL}/api/documents`, {
method: 'POST',
headers: headers,
body: JSON.stringify(documentData)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to create document:', error);
throw error;
}
}
// Usage example
const newDocument = {
title: 'Getting Started Guide',
content: '# Welcome to our documentation...',
category: 'guide'
};
createDocument(newDocument)
.then(doc => console.log('Document created:', doc))
.catch(error => console.error('Creation failed:', error));
🔧 Advanced Examples
Batch Operations
// Batch create documents
async function batchCreateDocuments(documents) {
const results = [];
for (const doc of documents) {
try {
const result = await createDocument(doc);
results.push({ success: true, data: result });
} catch (error) {
results.push({ success: false, error: error.message });
}
}
return results;
}
Error Handling
// Unified error handling
class APIClient {
constructor(baseURL, token) {
this.baseURL = baseURL;
this.token = token;
}
async request(endpoint, options = {}) {
const url = `${this.baseURL}${endpoint}`;
const config = {
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
...options.headers
},
...options
};
try {
const response = await fetch(url, config);
if (!response.ok) {
const errorData = await response.json();
throw new APIError(response.status, errorData.message, errorData);
}
return await response.json();
} catch (error) {
if (error instanceof APIError) {
throw error;
}
throw new APIError(0, 'Network request failed', { originalError: error });
}
}
}
// Custom error class
class APIError extends Error {
constructor(status, message, data) {
super(message);
this.name = 'APIError';
this.status = status;
this.data = data;
}
}
📱 Platform-Specific Examples
Python Example
import requests
import json
class APIClient:
def __init__(self, base_url, token):
self.base_url = base_url
self.headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
def get_documents(self, page=1, limit=20):
"""Get document list"""
url = f"{self.base_url}/api/documents"
params = {'page': page, 'limit': limit}
response = requests.get(url, headers=self.headers, params=params)
response.raise_for_status()
return response.json()
def create_document(self, document_data):
"""Create document"""
url = f"{self.base_url}/api/documents"
response = requests.post(
url,
headers=self.headers,
data=json.dumps(document_data)
)
response.raise_for_status()
return response.json()
# Usage example
client = APIClient('https://api.leafmove.com', 'your-token')
# Get documents
docs = client.get_documents(page=1, limit=10)
print(f"Retrieved {len(docs['data']['documents'])} documents")
# Create document
new_doc = {
'title': 'API Guide',
'content': '# API Documentation...'
}
result = client.create_document(new_doc)
print(f"Document created with ID: {result['data']['id']}")
cURL Examples
# Get document list
curl -X GET "https://api.leafmove.com/api/documents?page=1&limit=10" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json"
# Create document
curl -X POST "https://api.leafmove.com/api/documents" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "New Document",
"content": "# Document content...",
"category": "guide"
}'
# Update document
curl -X PUT "https://api.leafmove.com/api/documents/123" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "Updated Document",
"content": "# Updated content..."
}'
# Delete document
curl -X DELETE "https://api.leafmove.com/api/documents/123" \
-H "Authorization: Bearer YOUR_TOKEN"
🔍 Search Examples
Basic Search
// Simple text search
async function searchDocuments(query) {
const response = await fetch(`${API_BASE_URL}/api/search?q=${encodeURIComponent(query)}`, {
headers: headers
});
return await response.json();
}
// Usage
searchDocuments('getting started')
.then(results => console.log('Search results:', results))
.catch(error => console.error('Search failed:', error));
Advanced Search
// Advanced search with filters
async function advancedSearch(searchParams) {
const response = await fetch(`${API_BASE_URL}/api/search/advanced`, {
method: 'POST',
headers: headers,
body: JSON.stringify(searchParams)
});
return await response.json();
}
// Usage example
const searchParams = {
query: 'API documentation',
filters: {
category: ['guide', 'api'],
tags: ['beginner'],
dateRange: {
start: '2024-01-01',
end: '2024-12-31'
}
},
sort: 'relevance',
limit: 20
};
advancedSearch(searchParams)
.then(results => console.log('Advanced search results:', results));
🔧 Debugging and Testing
Request Logging
// Add request logging
class LoggingAPIClient extends APIClient {
async request(endpoint, options = {}) {
console.log(`[API] ${options.method || 'GET'} ${endpoint}`);
console.log('[API] Request params:', options.body);
const startTime = Date.now();
try {
const result = await super.request(endpoint, options);
const duration = Date.now() - startTime;
console.log(`[API] Request successful (${duration}ms)`);
console.log('[API] Response data:', result);
return result;
} catch (error) {
const duration = Date.now() - startTime;
console.error(`[API] Request failed (${duration}ms):`, error);
throw error;
}
}
}
Unit Testing
// Jest testing example
describe('API Client', () => {
let client;
beforeEach(() => {
client = new APIClient('https://api.leafmove.com', 'test-token');
});
test('should get document list', async () => {
// Mock fetch
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({
code: 200,
data: {
documents: [
{ id: 1, title: 'Test Document', content: 'Test content' }
]
}
})
});
const result = await client.request('/api/documents');
expect(result.code).toBe(200);
expect(result.data.documents).toHaveLength(1);
expect(fetch).toHaveBeenCalledWith(
'https://api.leafmove.com/api/documents',
expect.objectContaining({
headers: expect.objectContaining({
'Authorization': 'Bearer test-token'
})
})
);
});
});
📋 Best Practices
1. Error Handling
- Always handle network errors and HTTP errors
- Provide meaningful error messages
- Implement retry mechanisms
2. Performance Optimization
- Use connection pooling
- Implement request caching
- Avoid unnecessary requests
3. Security Considerations
- Store API tokens securely
- Use HTTPS
- Validate response data
4. Code Organization
- Create reusable API client classes
- Separate configuration from business logic
- Add appropriate logging