API Reference
Authentication
LinkedIn Automation
Voice Cloning
Lead Management
Enrichment & Prospecting
User Integrations
Manage integrations for the authenticated user
{
"userId": "65e0a32640a597f6a7f897ea",
"success": true,
"data": {
"linkedin": {
"connected": true,
"profileUrl": "https://linkedin.com/in/yourprofile",
"name": "Your Name",
"connectionCount": 1247
},
"webhooks": {
"configured": true,
"endpoints": ["https://yourapp.com/webhook"],
"status": "active"
},
"summary": {
"total": 2,
"connected": 2,
"completionPercentage": 100
}
}
}
User Integrations
Manage all integrations for your account including LinkedIn, webhooks, and other third-party services. This simplified endpoint automatically detects the user from the API key, eliminating the need for user IDs in the URL.
Requires a user-specific API key with users:read
(GET) or users:write
(POST) permission. Global API keys should use the legacy routes.
Get All Integrations
Retrieve all integration statuses for the authenticated user.
Request
Your user-specific API key with users:read
permission (format:
bna_hexstring
)
Examples
curl -X GET "https://api.buena.ai/api/v2/users/integrations" \
-H "x-api-key: bna_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Response
The authenticated user’s ID
Always true
for successful requests
All integration statuses and details
Show Integrations Data Object
Show Integrations Data Object
{
"userId": "65e0a32640a597f6a7f897ea",
"success": true,
"data": {
"linkedin": {
"connected": true,
"profileUrl": "https://linkedin.com/in/yourprofile",
"name": "Your Name",
"connectionCount": 1247
},
"webhooks": {
"configured": true,
"endpoints": ["https://yourapp.com/webhook"],
"status": "active"
},
"summary": {
"total": 2,
"connected": 2,
"completionPercentage": 100
}
}
}
Setup LinkedIn Integration
Initialize or setup LinkedIn integration for the authenticated user.
Request
Your user-specific API key with users:write
permission (format:
bna_hexstring
)
Must be application/json
Body Parameters
URL to redirect to after LinkedIn authentication (optional)
LinkedIn API scopes to request (optional, uses defaults)
Examples
curl -X POST "https://api.buena.ai/api/v2/users/integrations/linkedin" \
-H "x-api-key: bna_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
"returnUrl": "https://yourapp.com/linkedin-success"
}'
Response
The authenticated user’s ID
Always true
for successful requests
{
"userId": "65e0a32640a597f6a7f897ea",
"success": true,
"data": {
"authUrl": "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=...",
"state": "secure_random_state_string",
"expiresAt": "2024-01-20T16:30:00Z"
}
}
Advanced Use Cases
1. Integration Health Dashboard
async function createIntegrationDashboard() {
try {
const response = await fetch(
"https://api.buena.ai/api/v2/users/integrations",
{
headers: {
"x-api-key": process.env.BUENA_USER_API_KEY,
},
}
);
const data = await response.json();
const integrations = data.data;
console.log("🔗 Integration Dashboard");
console.log("========================");
// Overall status
const completion = integrations.summary.completionPercentage;
const statusIcon =
completion === 100 ? "✅" : completion >= 50 ? "⚠️" : "❌";
console.log(
`${statusIcon} Overall: ${completion}% complete (${integrations.summary.connected}/${integrations.summary.total})`
);
console.log("");
// LinkedIn status
const linkedin = integrations.linkedin;
if (linkedin.connected) {
console.log(`✅ LinkedIn: Connected as ${linkedin.name}`);
console.log(` Profile: ${linkedin.profileUrl}`);
console.log(
` Connections: ${linkedin.connectionCount.toLocaleString()}`
);
} else {
console.log("❌ LinkedIn: Not connected");
if (linkedin.setupUrl) {
console.log(` Setup: ${linkedin.setupUrl}`);
}
}
console.log("");
// Webhook status
const webhooks = integrations.webhooks;
if (webhooks.configured) {
const statusIcon =
webhooks.status === "active"
? "✅"
: webhooks.status === "error"
? "❌"
: "🔄";
console.log(
`${statusIcon} Webhooks: ${webhooks.status} (${
webhooks.endpoints.length
} endpoint${webhooks.endpoints.length !== 1 ? "s" : ""})`
);
} else {
console.log("❌ Webhooks: Not configured");
}
// Recommendations
const recommendations = generateRecommendations(integrations);
if (recommendations.length > 0) {
console.log("\n💡 Recommendations:");
recommendations.forEach((rec) => {
console.log(
` ${
rec.priority === "high"
? "🔴"
: rec.priority === "medium"
? "🟡"
: "🟢"
} ${rec.message}`
);
});
}
} catch (error) {
console.error("Failed to fetch integration data:", error);
}
}
function generateRecommendations(integrations) {
const recommendations = [];
if (!integrations.linkedin.connected) {
recommendations.push({
priority: "high",
message: "Connect LinkedIn to enable automation features",
});
}
if (!integrations.webhooks.configured) {
recommendations.push({
priority: "medium",
message:
"Configure webhooks for real-time notifications and integrations",
});
}
if (
integrations.webhooks.configured &&
integrations.webhooks.status === "error"
) {
recommendations.push({
priority: "high",
message: "Fix webhook configuration - currently not working",
});
}
return recommendations;
}
// Run dashboard
createIntegrationDashboard();
2. Automated Integration Setup
import requests
import time
import webbrowser
from urllib.parse import urlparse, parse_qs
class IntegrationManager:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = 'https://api.buena.ai/api/v2'
def get_integrations(self):
"""Get all integration statuses"""
response = requests.get(
f'{self.base_url}/users/integrations',
headers={'x-api-key': self.api_key}
)
return response.json()
def setup_linkedin_integration(self, return_url=None):
"""Setup LinkedIn integration with interactive flow"""
print("🔗 Setting up LinkedIn integration...")
payload = {}
if return_url:
payload['returnUrl'] = return_url
response = requests.post(
f'{self.base_url}/users/integrations/linkedin',
headers={
'x-api-key': self.api_key,
'Content-Type': 'application/json'
},
json=payload
)
if response.status_code == 200:
data = response.json()
auth_url = data['data']['authUrl']
state = data['data']['state']
print(f"✅ LinkedIn auth URL generated")
print(f"🌐 Opening browser: {auth_url}")
# Open browser for user authentication
webbrowser.open(auth_url)
return {
'auth_url': auth_url,
'state': state,
'status': 'pending_auth'
}
else:
print(f"❌ Failed to setup LinkedIn: {response.text}")
return None
def check_integration_health(self):
"""Check health of all integrations"""
integrations = self.get_integrations()
health_report = {
'overall_health': 'good',
'issues': [],
'recommendations': []
}
if not integrations['success']:
health_report['overall_health'] = 'error'
health_report['issues'].append('Failed to fetch integration status')
return health_report
data = integrations['data']
# Check LinkedIn
if not data['linkedin']['connected']:
health_report['issues'].append('LinkedIn not connected')
health_report['recommendations'].append('Setup LinkedIn integration for automation features')
health_report['overall_health'] = 'warning'
# Check Webhooks
if not data['webhooks']['configured']:
health_report['recommendations'].append('Consider configuring webhooks for real-time notifications')
elif data['webhooks']['status'] == 'error':
health_report['issues'].append('Webhook configuration error')
health_report['overall_health'] = 'warning'
# Overall completion check
completion = data['summary']['completionPercentage']
if completion < 50:
health_report['overall_health'] = 'poor'
elif completion < 100 and health_report['overall_health'] == 'good':
health_report['overall_health'] = 'warning'
return health_report
def auto_setup_missing_integrations(self, interactive=True):
"""Automatically setup missing integrations"""
integrations = self.get_integrations()
if not integrations['success']:
print("❌ Cannot fetch integration status")
return False
data = integrations['data']
setup_results = []
# Setup LinkedIn if not connected
if not data['linkedin']['connected']:
if interactive:
choice = input("LinkedIn not connected. Setup now? (y/n): ").lower()
if choice == 'y':
result = self.setup_linkedin_integration()
setup_results.append(('linkedin', result is not None))
else:
result = self.setup_linkedin_integration()
setup_results.append(('linkedin', result is not None))
# Note: Webhook setup would require user input, so we just recommend
if not data['webhooks']['configured']:
print("💡 Recommendation: Configure webhook endpoints for real-time notifications")
print(" Use the webhook management dashboard to set this up")
return setup_results
def get_setup_progress(self):
"""Get integration setup progress"""
integrations = self.get_integrations()
if not integrations['success']:
return None
data = integrations['data']
summary = data['summary']
progress = {
'completion_percentage': summary['completionPercentage'],
'completed_integrations': summary['connected'],
'total_integrations': summary['total'],
'next_steps': []
}
if not data['linkedin']['connected']:
progress['next_steps'].append({
'integration': 'linkedin',
'action': 'Connect LinkedIn account',
'priority': 'high',
'benefit': 'Enables LinkedIn automation features'
})
if not data['webhooks']['configured']:
progress['next_steps'].append({
'integration': 'webhooks',
'action': 'Configure webhook endpoints',
'priority': 'medium',
'benefit': 'Enables real-time notifications and integrations'
})
return progress
# Usage
manager = IntegrationManager(os.getenv('BUENA_USER_API_KEY'))
# Check current status
integrations = manager.get_integrations()
print(f"Integration completion: {integrations['data']['summary']['completionPercentage']}%")
# Check health
health = manager.check_integration_health()
print(f"Overall health: {health['overall_health']}")
if health['issues']:
print("Issues found:")
for issue in health['issues']:
print(f" ❌ {issue}")
if health['recommendations']:
print("Recommendations:")
for rec in health['recommendations']:
print(f" 💡 {rec}")
# Auto-setup missing integrations
setup_results = manager.auto_setup_missing_integrations(interactive=False)
if setup_results:
print("Setup results:")
for integration, success in setup_results:
status = "✅" if success else "❌"
print(f" {status} {integration}")
3. Integration Monitoring and Alerts
class IntegrationMonitor {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = "https://api.buena.ai/api/v2";
}
async getIntegrations() {
const response = await fetch(`${this.baseUrl}/users/integrations`, {
headers: {
"x-api-key": this.apiKey,
},
});
return response.json();
}
async monitorIntegrations() {
try {
const data = await this.getIntegrations();
const integrations = data.data;
const alerts = this.checkForAlerts(integrations);
if (alerts.length > 0) {
console.log("🚨 Integration Alerts:");
alerts.forEach((alert) => {
console.log(
` ${alert.severity === "high" ? "🔴" : "🟡"} ${alert.message}`
);
});
// Send alerts via webhook, email, etc.
await this.sendAlerts(alerts);
} else {
console.log("✅ All integrations healthy");
}
return alerts;
} catch (error) {
console.error("Integration monitoring failed:", error);
return [
{ severity: "high", message: "Failed to check integration status" },
];
}
}
checkForAlerts(integrations) {
const alerts = [];
// LinkedIn alerts
if (!integrations.linkedin.connected) {
alerts.push({
severity: "high",
integration: "linkedin",
message:
"LinkedIn integration not connected - automation features disabled",
});
}
// Webhook alerts
if (
integrations.webhooks.configured &&
integrations.webhooks.status === "error"
) {
alerts.push({
severity: "medium",
integration: "webhooks",
message: "Webhook endpoints failing - real-time notifications disabled",
});
}
// Overall completion alerts
if (integrations.summary.completionPercentage < 50) {
alerts.push({
severity: "medium",
integration: "general",
message: `Low integration completion: ${integrations.summary.completionPercentage}%`,
});
}
return alerts;
}
async sendAlerts(alerts) {
// Example: Send to webhook
for (const alert of alerts) {
try {
await fetch("https://your-webhook-url.com/alerts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
timestamp: new Date().toISOString(),
source: "buena-integration-monitor",
alert,
}),
});
} catch (error) {
console.error("Failed to send alert:", error);
}
}
}
async startMonitoring(intervalMinutes = 30) {
console.log(
`🔍 Starting integration monitoring (every ${intervalMinutes} minutes)`
);
// Initial check
await this.monitorIntegrations();
// Periodic checks
setInterval(async () => {
await this.monitorIntegrations();
}, intervalMinutes * 60 * 1000);
}
}
// Usage
const monitor = new IntegrationMonitor(process.env.BUENA_USER_API_KEY);
// Start monitoring every 30 minutes
monitor.startMonitoring(30);
Legacy Routes
For backward compatibility, these legacy routes are still supported but require explicit user IDs:
GET /api/v2/users/integrations/linkedin-integration/:userId
- Get LinkedIn integration for specific userPOST /api/v2/users/integrations/setup-linkedin-integration
- Setup LinkedIn integration (legacy)
Error Responses
Global API Key Used (400)
{
"error": "When using global API key, please use the specific route: /api/v2/users/integrations/linkedin-integration/:userId",
"availableRoute": "/api/v2/users/integrations/linkedin-integration/:userId"
}
LinkedIn Already Connected (400)
{
"error": true,
"code": "LINKEDIN_ALREADY_CONNECTED",
"message": "LinkedIn account is already connected",
"version": "2.0",
"timestamp": "2024-01-20T15:30:00Z",
"details": {
"profileUrl": "https://linkedin.com/in/yourprofile",
"connectedAt": "2024-01-15T10:30:00Z"
}
}
Invalid Permission (403)
{
"error": true,
"code": "PERMISSION_DENIED",
"message": "Insufficient permissions for integration management",
"version": "2.0",
"timestamp": "2024-01-20T15:30:00Z",
"permissionHelp": {
"required": "users:write",
"available": ["users:read"],
"documentation": "https://docs.buena.ai/authentication"
}
}
Next Steps
{
"userId": "65e0a32640a597f6a7f897ea",
"success": true,
"data": {
"linkedin": {
"connected": true,
"profileUrl": "https://linkedin.com/in/yourprofile",
"name": "Your Name",
"connectionCount": 1247
},
"webhooks": {
"configured": true,
"endpoints": ["https://yourapp.com/webhook"],
"status": "active"
},
"summary": {
"total": 2,
"connected": 2,
"completionPercentage": 100
}
}
}