Skip to main content

Integration Examples

Practical examples of how to integrate with the Sakneen API.

Creating a Lead

The most common operation is creating a new lead in the system.

Basic Lead Creation

const createLead = async (leadData) => {
try {
const baseDomain = process.env.SAKNEEN_DOMAIN; // your assigned domain
const response = await fetch(`https://${baseDomain}/external/apis/v1.0/leads`, {
method: 'POST',
headers: {
'api-key': process.env.SAKNEEN_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify(leadData)
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const result = await response.text();
console.log('Lead created successfully:', result);
return result;
} catch (error) {
console.error('Error creating lead:', error);
throw error;
}
};

// Usage
const leadData = {
name: 'Jane Smith',
phoneNumber: '+1987654321',
project: 'Riverside Apartments',
email: '[email protected]'
};

createLead(leadData);

Lead Creation with Validation

const validateLead = (leadData) => {
const errors = [];

if (!leadData.name || leadData.name.trim().length === 0) {
errors.push('Name is required');
}

if (!leadData.phoneNumber || !/^\+\d{10,15}$/.test(leadData.phoneNumber)) {
errors.push('Valid phone number is required');
}

if (!leadData.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(leadData.email)) {
errors.push('Valid email is required');
}

if (!leadData.project || leadData.project.trim().length === 0) {
errors.push('Project is required');
}

return errors;
};

const createLeadSafely = async (leadData) => {
// Validate input
const validationErrors = validateLead(leadData);
if (validationErrors.length > 0) {
throw new Error(`Validation failed: ${validationErrors.join(', ')}`);
}

// Create lead
return await createLead(leadData);
};

Error Handling

Comprehensive Error Handling

const handleApiResponse = async (response) => {
if (response.ok) {
return response.text();
}

let errorMessage = `HTTP ${response.status}: ${response.statusText}`;

try {
const errorData = await response.json();
if (errorData.message) {
errorMessage = Array.isArray(errorData.message)
? errorData.message.join(', ')
: errorData.message;
}
} catch (e) {
// If response is not JSON, use default error message
}

throw new Error(errorMessage);
};

const createLeadWithErrorHandling = async (leadData) => {
try {
const baseDomain = process.env.SAKNEEN_DOMAIN; // your assigned domain
const response = await fetch(`https://${baseDomain}/external/apis/v1.0/leads`, {
method: 'POST',
headers: {
'api-key': process.env.SAKNEEN_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify(leadData)
});

return await handleApiResponse(response);
} catch (error) {
console.error('Failed to create lead:', error.message);
throw error;
}
};

Webhook Integration

If you need to receive notifications when leads are processed:

const express = require('express');
const app = express();

app.use(express.json());

// Webhook endpoint to receive lead status updates
app.post('/webhook/lead-status', (req, res) => {
const { leadId, status, timestamp } = req.body;

console.log(`Lead ${leadId} status updated to: ${status} at ${timestamp}`);

// Process the webhook data
// Update your local database, send notifications, etc.

res.status(200).send('OK');
});

app.listen(3001, () => {
console.log('Webhook server listening on port 3001');
});

Best Practices

  1. Always validate input data before sending to the API
  2. Implement proper error handling for all API calls
  3. Use environment variables for sensitive data like API keys
  4. Implement retry logic for transient failures
  5. Log API interactions for debugging and monitoring
  6. Rate limit your requests to avoid overwhelming the API