API Code Examples
Complete, production-ready examples for common Solatis API use cases.
Document Analysis
Analyze a Contract (JavaScript)
javascript
const analyzeContract = async (contractUrl) => {
const response = await fetch(
'https://api.solatis.team/v2/documents/analyze',
{
method: 'POST',
headers: {
'Authorization': 'Bearer ' + process.env.SOLATIS_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
document_url: contractUrl,
analysis_type: 'contract_review',
extract_fields: [
'parties',
'contract_date',
'end_date',
'payment_terms',
'termination_clause',
'renewal_terms'
]
})
}
);
if (!response.ok) {
throw new Error(`Analysis failed: ${response.statusText}`);
}
return await response.json();
};
// Usage
const result = await analyzeContract('https://example.com/contract.pdf');
console.log('Contract Analysis:', result);Analyze a Contract (Python)
python
import requests
import os
def analyze_contract(contract_url):
headers = {
'Authorization': f'Bearer {os.getenv("SOLATIS_API_KEY")}',
'Content-Type': 'application/json'
}
payload = {
'document_url': contract_url,
'analysis_type': 'contract_review',
'extract_fields': [
'parties',
'contract_date',
'end_date',
'payment_terms',
'termination_clause'
]
}
response = requests.post(
'https://api.solatis.team/v2/documents/analyze',
headers=headers,
json=payload
)
response.raise_for_status()
return response.json()
# Usage
result = analyze_contract('https://example.com/contract.pdf')
print('Contract Analysis:', result)Analyze Multiple Documents (Python with Batch)
python
import requests
import concurrent.futures
import os
def analyze_documents_batch(document_urls):
"""Analyze multiple documents in parallel"""
headers = {
'Authorization': f'Bearer {os.getenv("SOLATIS_API_KEY")}',
'Content-Type': 'application/json'
}
def analyze_one(url):
payload = {
'document_url': url,
'analysis_type': 'document_review'
}
response = requests.post(
'https://api.solatis.team/v2/documents/analyze',
headers=headers,
json=payload
)
response.raise_for_status()
return response.json()
# Process up to 5 documents concurrently
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(analyze_one, document_urls))
return results
# Usage
urls = [
'https://example.com/contract1.pdf',
'https://example.com/contract2.pdf',
'https://example.com/contract3.pdf'
]
results = analyze_documents_batch(urls)Meeting Transcription
Transcribe Meeting (JavaScript)
javascript
const transcribeMeeting = async (audioUrl, webhookUrl) => {
const response = await fetch(
'https://api.solatis.team/v2/transcribe',
{
method: 'POST',
headers: {
'Authorization': 'Bearer ' + process.env.SOLATIS_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
audio_url: audioUrl,
language: 'en',
speaker_labels: true,
webhook_url: webhookUrl
})
}
);
const data = await response.json();
return data;
};
// Usage
const transcription = await transcribeMeeting(
'https://example.com/meeting.mp3',
'https://yourapp.com/webhooks/transcription'
);
console.log('Transcription ID:', transcription.id);
console.log('Status:', transcription.status);Extract Action Items from Meeting (Python)
python
import requests
import os
def extract_action_items(transcript_id):
headers = {
'Authorization': f'Bearer {os.getenv("SOLATIS_API_KEY")}',
'Content-Type': 'application/json'
}
payload = {
'transcript_id': transcript_id,
'assign_to_speakers': True,
'extract_deadlines': True
}
response = requests.post(
'https://api.solatis.team/v2/meetings/action-items',
headers=headers,
json=payload
)
response.raise_for_status()
return response.json()
# Usage
action_items = extract_action_items('trans_abc123xyz')
for item in action_items['action_items']:
print(f"- {item['description']} (Due: {item['due_date']})")Content Generation
Generate Blog Post (JavaScript)
javascript
const generateBlogPost = async (topic, keywords) => {
const response = await fetch(
'https://api.solatis.team/v2/generate/content',
{
method: 'POST',
headers: {
'Authorization': 'Bearer ' + process.env.SOLATIS_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
type: 'blog_post',
topic: topic,
tone: 'professional',
length: 'long',
keywords: keywords,
include_seo: true
})
}
);
const data = await response.json();
return data;
};
// Usage
const post = await generateBlogPost(
'AI in Healthcare',
['AI', 'healthcare', 'diagnostics', 'machine learning']
);
console.log('Title:', post.title);
console.log('Content:', post.content);
console.log('SEO Meta:', post.seo_metadata);Generate Email (Python)
python
import requests
import os
def generate_email(recipient_name, purpose, tone='professional'):
headers = {
'Authorization': f'Bearer {os.getenv("SOLATIS_API_KEY")}',
'Content-Type': 'application/json'
}
payload = {
'type': 'email',
'recipient_name': recipient_name,
'purpose': purpose,
'tone': tone,
'length': 'medium'
}
response = requests.post(
'https://api.solatis.team/v2/generate/content',
headers=headers,
json=payload
)
response.raise_for_status()
return response.json()
# Usage
email = generate_email(
'John Smith',
'Follow up on proposal',
'professional'
)
print('Subject:', email['subject'])
print('Body:', email['body'])Task Management
Create Task from Meeting (JavaScript)
javascript
const createTaskFromMeeting = async (meetingId, taskTitle, assignee) => {
// First, get meeting details
const meetingResponse = await fetch(
`https://api.solatis.team/v2/meetings/${meetingId}`,
{
headers: {
'Authorization': 'Bearer ' + process.env.SOLATIS_API_KEY
}
}
);
const meeting = await meetingResponse.json();
// Create task
const taskResponse = await fetch(
'https://api.solatis.team/v2/tasks',
{
method: 'POST',
headers: {
'Authorization': 'Bearer ' + process.env.SOLATIS_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: taskTitle,
description: `Task from meeting: ${meeting.title}`,
assigned_to: assignee,
due_date: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
.toISOString()
.split('T')[0],
related_meeting_id: meetingId
})
}
);
return await taskResponse.json();
};
// Usage
const task = await createTaskFromMeeting(
'meeting_abc123',
'Send proposal to client',
'john@example.com'
);Sync Tasks to Jira (Python)
python
import requests
import os
def sync_tasks_to_jira(workspace_id, jira_project_key):
"""Sync all tasks from Solatis to Jira"""
# Get tasks from Solatis
solatis_headers = {
'Authorization': f'Bearer {os.getenv("SOLATIS_API_KEY")}'
}
tasks_response = requests.get(
'https://api.solatis.team/v2/tasks',
headers=solatis_headers,
params={'workspace_id': workspace_id}
)
tasks_response.raise_for_status()
tasks = tasks_response.json()['tasks']
# Create issues in Jira
jira_headers = {
'Authorization': f'Bearer {os.getenv("JIRA_API_TOKEN")}',
'Content-Type': 'application/json'
}
created_issues = []
for task in tasks:
jira_payload = {
'fields': {
'project': {'key': jira_project_key},
'summary': task['title'],
'description': task['description'],
'issuetype': {'name': 'Task'}
}
}
response = requests.post(
f'{os.getenv("JIRA_INSTANCE")}/rest/api/3/issue',
headers=jira_headers,
json=jira_payload
)
response.raise_for_status()
created_issues.append(response.json())
return created_issues
# Usage
issues = sync_tasks_to_jira('workspace_xyz', 'PROJ')
print(f'Created {len(issues)} issues in Jira')Webhook Integration
Verify Webhook Signature (Express.js)
javascript
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
// Verify webhook signature
const verifyWebhookSignature = (payload, signature, secret) => {
const hmac = crypto.createHmac('sha256', secret);
const digest = hmac.update(payload).digest('hex');
return crypto.timingSafeEqual(signature, digest);
};
// Webhook endpoint
app.post('/webhooks/solatis', (req, res) => {
const signature = req.headers['x-solatis-signature'];
const payload = JSON.stringify(req.body);
if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
// Handle event
const event = req.body;
if (event.event === 'document.analyzed') {
console.log('Document analyzed:', event.id);
// Process document analysis
}
if (event.event === 'transcription.completed') {
console.log('Transcription completed:', event.id);
// Process transcription
}
res.status(200).send('OK');
});
app.listen(3000);Verify Webhook Signature (Flask)
python
from flask import Flask, request
import hmac
import hashlib
app = Flask(__name__)
WEBHOOK_SECRET = os.getenv('WEBHOOK_SECRET')
@app.route('/webhooks/solatis', methods=['POST'])
def handle_webhook():
signature = request.headers.get('X-Solatis-Signature')
payload = request.get_data()
# Verify signature
expected_signature = hmac.new(
WEBHOOK_SECRET.encode(),
payload,
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature, expected_signature):
return 'Invalid signature', 401
# Handle event
event = request.json
if event['event'] == 'document.analyzed':
print(f"Document analyzed: {event['id']}")
# Process document
if event['event'] == 'transcription.completed':
print(f"Transcription completed: {event['id']}")
# Process transcription
return 'OK', 200
if __name__ == '__main__':
app.run()Error Handling & Retries
Retry with Exponential Backoff (JavaScript)
javascript
const retryWithBackoff = async (
fn,
maxRetries = 3,
baseDelay = 1000
) => {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (i === maxRetries - 1) throw error;
// 429 (Rate Limited) or 5xx (Server Error)
if (error.status === 429 || error.status >= 500) {
const delay = baseDelay * Math.pow(2, i);
console.log(`Retrying in ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw error;
}
}
};
// Usage
const analyzeWithRetry = () => retryWithBackoff(() =>
fetch('https://api.solatis.team/v2/documents/analyze', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + process.env.SOLATIS_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
document_url: 'https://example.com/contract.pdf',
analysis_type: 'contract_review'
})
}).then(r => {
if (!r.ok) {
const error = new Error(r.statusText);
error.status = r.status;
throw error;
}
return r.json();
})
);
const result = await analyzeWithRetry();Retry with Exponential Backoff (Python)
python
import requests
import time
def retry_with_backoff(fn, max_retries=3, base_delay=1):
"""Retry function with exponential backoff"""
for i in range(max_retries):
try:
return fn()
except requests.exceptions.RequestException as e:
if i == max_retries - 1:
raise
# Retry on 429 (Rate Limited) or 5xx
if hasattr(e.response, 'status_code'):
if e.response.status_code == 429 or e.response.status_code >= 500:
delay = base_delay * (2 ** i)
print(f'Retrying in {delay}s...')
time.sleep(delay)
continue
raise
# Usage
def analyze_document():
response = requests.post(
'https://api.solatis.team/v2/documents/analyze',
headers={
'Authorization': f'Bearer {os.getenv("SOLATIS_API_KEY")}',
'Content-Type': 'application/json'
},
json={
'document_url': 'https://example.com/contract.pdf',
'analysis_type': 'contract_review'
}
)
response.raise_for_status()
return response.json()
result = retry_with_backoff(analyze_document)Using Official SDKs
JavaScript SDK
javascript
import { Solatis } from '@solatis/sdk';
const client = new Solatis({
apiKey: process.env.SOLATIS_API_KEY
});
// Analyze document
const analysis = await client.documents.analyze({
documentUrl: 'https://example.com/contract.pdf',
analysisType: 'contract_review'
});
// Transcribe meeting
const transcription = await client.transcribe({
audioUrl: 'https://example.com/meeting.mp3',
language: 'en',
speakerLabels: true
});
// Extract action items
const actionItems = await client.meetings.actionItems({
transcriptId: transcription.id,
assignToSpeakers: true
});Python SDK
python
from solatis import Solatis
client = Solatis(api_key=os.getenv('SOLATIS_API_KEY'))
# Analyze document
analysis = client.documents.analyze(
document_url='https://example.com/contract.pdf',
analysis_type='contract_review'
)
# Transcribe meeting
transcription = client.transcribe(
audio_url='https://example.com/meeting.mp3',
language='en',
speaker_labels=True
)
# Extract action items
action_items = client.meetings.action_items(
transcript_id=transcription.id,
assign_to_speakers=True
)Next Steps
- API Reference - Complete endpoint documentation
- Webhooks Guide - Real-time event notifications
- Error Handling - Status codes and solutions
- Rate Limiting - Understanding limits and backoff strategies