API Examples
This page provides practical examples and code snippets for common use cases with the TaskIP API. These examples demonstrate how to integrate TaskIP into your applications using various programming languages.
Authentication Setup
Before using any API endpoints, you need to authenticate your requests using your secret key.
JavaScript/Node.js Setup
const TASKIP_API_KEY = 'your-secret-key-here';
const BASE_URL = 'https://public-api.taskip.net/api/public-v1';
// Helper function for API requests
async function taskipRequest(endpoint, method = 'GET', data = null) {
const config = {
method,
headers: {
'X-Secret-Key': TASKIP_API_KEY,
'Content-Type': 'application/json'
}
};
if (data && method !== 'GET') {
config.body = JSON.stringify(data);
}
const response = await fetch(`${BASE_URL}${endpoint}`, config);
return await response.json();
}
Python Setup
import requests
import json
TASKIP_API_KEY = 'your-secret-key-here'
BASE_URL = 'https://public-api.taskip.net/api/public-v1'
class TaskipAPI:
def __init__(self, api_key):
self.api_key = api_key
self.headers = {
'X-Secret-Key': api_key,
'Content-Type': 'application/json'
}
def request(self, endpoint, method='GET', data=None):
url = f"{BASE_URL}{endpoint}"
if method == 'GET':
response = requests.get(url, headers=self.headers, params=data)
elif method == 'POST':
response = requests.post(url, headers=self.headers, json=data)
elif method == 'PUT':
response = requests.put(url, headers=self.headers, json=data)
elif method == 'DELETE':
response = requests.delete(url, headers=self.headers)
return response.json()
# Initialize API client
api = TaskipAPI(TASKIP_API_KEY)
PHP Setup
<?php
class TaskipAPI {
private $apiKey;
private $baseUrl;
public function __construct($apiKey, $baseUrl = 'https://public-api.taskip.net/api/public-v1') {
$this->apiKey = $apiKey;
$this->baseUrl = $baseUrl;
}
private function makeRequest($endpoint, $method = 'GET', $data = null) {
$url = $this->baseUrl . $endpoint;
$headers = [
'X-Secret-Key: ' . $this->apiKey,
'Content-Type: application/json'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if ($data && $method !== 'GET') {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
}
// Initialize API client
$api = new TaskipAPI('your-secret-key-here');
?>
Common Use Cases
1. Customer Onboarding Workflow
Complete workflow for onboarding a new customer with company and contact creation.
JavaScript Example
async function onboardNewCustomer(customerData) {
try {
// Step 1: Create the company
const company = await taskipRequest('/company', 'POST', {
name: customerData.companyName,
domain: customerData.domain,
email: customerData.companyEmail,
phone: customerData.phone,
address: customerData.address,
industry: customerData.industry,
status: 'active'
});
console.log('Company created:', company.data.id);
// Step 2: Create primary contact
const contact = await taskipRequest('/contact', 'POST', {
first_name: customerData.firstName,
last_name: customerData.lastName,
email: customerData.email,
phone: customerData.contactPhone,
company_id: company.data.id,
position: customerData.position,
is_primary: true,
contact_type: 'client'
});
console.log('Contact created:', contact.data.id);
// Step 3: Create initial project
const project = await taskipRequest('/project', 'POST', {
title: `Onboarding - ${customerData.companyName}`,
description: `Initial setup and onboarding for ${customerData.companyName}`,
priority: 4, // High priority (1-5 scale)
privacy: 1, // Public to team
status: 'planning',
started_at: new Date().toISOString().split('T')[0],
ended_at: getDatePlusMonths(new Date(), 3).toISOString().split('T')[0],
client: [contact.data.id],
project_manager: [customerData.projectManagerId],
tags: [1, 3], // Tag IDs for onboarding and new-client
notify_client: true
});
console.log('Project created:', project.data.id);
return {
success: true,
companyId: company.data.id,
contactId: contact.data.id,
projectId: project.data.id
};
} catch (error) {
console.error('Onboarding failed:', error);
return { success: false, error: error.message };
}
}
// Helper function
function getDatePlusMonths(date, months) {
const result = new Date(date);
result.setMonth(result.getMonth() + months);
return result;
}
// Usage
const newCustomer = {
companyName: 'TechStart Solutions',
domain: 'techstart.com',
companyEmail: 'info@techstart.com',
phone: '+1-555-0123',
address: '123 Innovation Ave, San Francisco, CA',
industry: 'Technology',
firstName: 'John',
lastName: 'Doe',
email: 'john@techstart.com',
contactPhone: '+1-555-0124',
position: 'CTO',
projectManagerId: 3
};
onboardNewCustomer(newCustomer);
2. Invoice Generation and Management
Create and manage invoices for project work.
Python Example
from datetime import datetime, timedelta
def create_project_invoice(api, project_id, invoice_data):
try:
# Step 1: Get project details
project = api.request(f'/project/{project_id}')
# Step 2: Get project activities for billing
activities = api.request(f'/project/{project["data"]["uuid"]}/activity', 'POST', {'type': 'time_tracking'})
# Step 3: Create invoice items from activities
items = []
if activities.get('data'):
for entry in activities['data']:
if entry.get('type') == 'time_entry':
items.append({
'description': f"{entry.get('task_title', 'Task')} - {entry.get('description', 'Time entry')}",
'quantity': entry.get('hours', 0),
'unit_price': entry.get('hourly_rate', 0),
'line_total': entry.get('total_amount', 0)
})
# Step 4: Create the invoice
due_date = (datetime.now() + timedelta(days=30)).date()
invoice_response = api.request('/invoice', 'POST', {
'client_id': project['data']['client']['id'],
'project_id': project_id,
'invoice_type': 'project_invoice',
'currency': 'USD',
'due_date': due_date.isoformat(),
'payment_terms': 'Net 30',
'tax_rate': 8.5,
'items': items,
'notes': f"Invoice for project: {project['data']['name']}",
**invoice_data
})
invoice_id = invoice_response['data']['id']
print(f"Invoice created: {invoice_id}")
# Step 5: Send to client if requested
if invoice_data.get('send_to_client'):
api.request(f'/invoice/{invoice_id}/send-to-client', 'POST', {
'custom_message': f"Please find attached the invoice for {project['data']['name']}. Thank you for your business!",
'send_copy_to_self': True
})
print('Invoice sent to client')
return invoice_response['data']
except Exception as e:
print(f"Invoice creation failed: {e}")
raise e
# Usage
invoice_data = {
'send_to_client': True,
'payment_gateway_config': {
'stripe': {
'enabled': True,
'allow_partial_payments': False
}
}
}
invoice = create_project_invoice(api, 26, invoice_data)
3. Support Ticket Automation
Automated support ticket handling with smart assignment.
JavaScript Example
async function handleSupportTicket(ticketData) {
try {
// Analyze ticket content for priority and category
const priority = determinePriority(ticketData.description);
const category = categorizeTicket(ticketData.description);
const tags = extractTags(ticketData.description);
// Create the ticket
const ticket = await taskipRequest('/ticket', 'POST', {
title: ticketData.title,
description: ticketData.description,
client_id: ticketData.clientId,
category: category,
priority: priority,
tags: tags
});
console.log('Ticket created:', ticket.data.id);
// Auto-assign based on category
const assignee = getAssigneeByCategory(category);
if (assignee) {
await taskipRequest(`/ticket/${ticket.data.id}/assign`, 'POST', {
assigned_to: assignee,
reason: 'Auto-assigned based on category',
notify_assignee: true
});
}
// Add initial response
await taskipRequest(`/ticket/${ticket.data.id}/add-reply`, 'POST', {
message: 'Thank you for contacting support. We have received your ticket and will respond within 24 hours.',
author_type: 'system',
notify_client: true
});
// Set up escalation for high priority tickets
if (priority === 'urgent' || priority === 'high') {
scheduleEscalation(ticket.data.id, 4); // 4 hours
}
return ticket.data;
} catch (error) {
console.error('Ticket handling failed:', error);
throw error;
}
}
function determinePriority(description) {
const urgentKeywords = ['urgent', 'critical', 'down', 'not working', 'broken'];
const highKeywords = ['important', 'asap', 'soon', 'issue'];
const descLower = description.toLowerCase();
if (urgentKeywords.some(keyword => descLower.includes(keyword))) {
return 'urgent';
} else if (highKeywords.some(keyword => descLower.includes(keyword))) {
return 'high';
}
return 'medium';
}
function categorizeTicket(description) {
const descLower = description.toLowerCase();
if (descLower.includes('login') || descLower.includes('password')) {
return 'Technical Support';
} else if (descLower.includes('billing') || descLower.includes('payment')) {
return 'Billing';
} else if (descLower.includes('bug') || descLower.includes('error')) {
return 'Bug Report';
}
return 'General Inquiry';
}
function extractTags(description) {
const tags = [];
const descLower = description.toLowerCase();
if (descLower.includes('login')) tags.push('login');
if (descLower.includes('password')) tags.push('password');
if (descLower.includes('email')) tags.push('email');
if (descLower.includes('billing')) tags.push('billing');
return tags;
}
function getAssigneeByCategory(category) {
const assignments = {
'Technical Support': 5,
'Billing': 8,
'General Inquiry': 3,
'Bug Report': 12
};
return assignments[category];
}
function scheduleEscalation(ticketId, hours) {
// This would integrate with your task scheduler
console.log(`Escalation scheduled for ticket ${ticketId} in ${hours} hours`);
}
// Usage
const ticketData = {
title: 'Unable to access dashboard',
description: 'I cannot log into my dashboard. Getting error message after password reset.',
clientId: 25
};
handleSupportTicket(ticketData);
4. Project Dashboard Analytics
Comprehensive project analytics for management dashboard.
Python Example
def get_project_dashboard(api):
try:
# Fetch active projects
projects_response = api.request('/project', 'GET', {'status': 'active', 'limit': 50})
projects = projects_response['data']
# Fetch activities for each project
project_analytics = []
for project in projects:
activities = api.request(f"/project/{project['uuid']}/activity", 'POST', {'period': 'month'})
project_analytics.append({
**project,
'activities': activities.get('data', [])
})
# Calculate dashboard metrics
dashboard_data = {
'total_projects': projects_response['meta']['total'],
'active_projects': len(projects),
'average_progress': sum(p['completion_percentage'] for p in projects) / len(projects) if projects else 0,
'total_tasks': sum(p['total_tasks'] for p in projects),
'completed_tasks': sum(p['completed_tasks'] for p in projects),
'projects_at_risk': [],
'upcoming_deadlines': [],
'team_performance': {}
}
# Identify at-risk projects (projects with low completion rates)
for project in project_analytics:
completion_rate = project.get('completion_percentage', 0)
if completion_rate < 30 and project['total_tasks'] > 0:
dashboard_data['projects_at_risk'].append({
'id': project['id'],
'title': project['title'],
'completion_percentage': completion_rate,
'total_tasks': project['total_tasks']
})
# Find upcoming deadlines
from datetime import datetime, timedelta
today = datetime.now().date()
for project in projects:
if project.get('ended_at'):
# Parse date format: d-M-Y (e.g., 15-Apr-2024)
try:
end_date = datetime.strptime(project['ended_at'], '%d-%b-%Y').date()
days_until_deadline = (end_date - today).days
if 0 < days_until_deadline <= 14:
dashboard_data['upcoming_deadlines'].append({
'id': project['id'],
'title': project['title'],
'ended_at': project['ended_at'],
'days_remaining': days_until_deadline
})
except ValueError:
# Skip if date format is invalid
continue
# Calculate team performance
team_stats = {}
for project in project_analytics:
# Get team members from project
for assignee in project.get('assignees', []):
user_id = assignee['id']
if user_id not in team_stats:
team_stats[user_id] = {
'name': assignee['name'],
'email': assignee['email'],
'total_projects': 0,
'completion_rate': 0
}
team_stats[user_id]['total_projects'] += 1
for manager in project.get('project_manager', []):
user_id = manager['id']
if user_id not in team_stats:
team_stats[user_id] = {
'name': manager['name'],
'email': manager['email'],
'total_projects': 0,
'role': 'Project Manager'
}
team_stats[user_id]['total_projects'] += 1
# Calculate efficiency metrics based on project completion
for user_id, stats in team_stats.items():
user_projects = [p for p in projects if
any(a['id'] == user_id for a in p.get('assignees', [])) or
any(m['id'] == user_id for m in p.get('project_manager', []))]
if user_projects:
avg_completion = sum(p.get('completion_percentage', 0) for p in user_projects) / len(user_projects)
stats['avg_project_completion'] = round(avg_completion, 1)
else:
stats['avg_project_completion'] = 0
dashboard_data['team_performance'] = list(team_stats.values())
return dashboard_data
except Exception as e:
print(f"Dashboard data fetch failed: {e}")
raise e
# Usage
dashboard = get_project_dashboard(api)
print(f"Active Projects: {dashboard['active_projects']}")
print(f"Average Progress: {dashboard['average_progress']:.1f}%")
print(f"Total Tasks: {dashboard['total_tasks']}")
print(f"Completed Tasks: {dashboard['completed_tasks']}")
print(f"Projects at Risk: {len(dashboard['projects_at_risk'])}")
5. Document Management Integration
Upload and organize project documents with automatic sharing.
PHP Example
function uploadProjectDocuments($api, $projectId, $files, $folderName = null) {
try {
// Create project folder if specified
$folderId = null;
if ($folderName) {
$folderResponse = $api->makeRequest('/document/folders', 'POST', [
'name' => "Project_{$projectId}_{$folderName}",
'parent_id' => 0,
'description' => "Documents for project {$projectId}"
]);
$folderId = $folderResponse['data']['id'];
}
$uploadedDocs = [];
foreach ($files as $file) {
// Upload document
$postFields = [
'file' => new CURLFile($file['path'], $file['mime_type'], $file['name']),
'name' => $file['display_name'] ?? $file['name'],
'description' => $file['description'] ?? '',
'folder_id' => $folderId,
'tags' => implode(',', $file['tags'] ?? []),
'is_public' => $file['is_public'] ?? false,
'notify_team' => true
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api->baseUrl . '/document');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'X-Secret-Key: ' . $api->apiKey
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 || $httpCode === 201) {
$result = json_decode($response, true);
$uploadedDocs[] = $result['data'];
// Share with project team
shareDocumentWithProjectTeam($api, $result['data']['id'], $projectId);
}
}
return $uploadedDocs;
} catch (Exception $e) {
error_log("Document upload failed: " . $e->getMessage());
throw $e;
}
}
function shareDocumentWithProjectTeam($api, $documentId, $projectId) {
// Get project team members
$project = $api->makeRequest("/project/{$projectId}");
// Extract team member IDs from assignees and project managers
$teamMemberIds = [];
if (isset($project['data']['assignees'])) {
$teamMemberIds = array_merge($teamMemberIds, array_column($project['data']['assignees'], 'id'));
}
if (isset($project['data']['project_manager'])) {
$teamMemberIds = array_merge($teamMemberIds, array_column($project['data']['project_manager'], 'id'));
}
if (!empty($teamMemberIds)) {
// Note: Document sharing endpoints may need to be implemented based on your backend
error_log("Would share document {$documentId} with team members: " . implode(', ', $teamMemberIds));
}
}
// Usage
$projectFiles = [
[
'path' => '/path/to/requirements.pdf',
'name' => 'requirements.pdf',
'display_name' => 'Project Requirements Document',
'mime_type' => 'application/pdf',
'description' => 'Detailed project requirements and specifications',
'tags' => ['requirements', 'specs'],
'is_public' => false
]
];
$uploadedDocuments = uploadProjectDocuments($api, 26, $projectFiles, 'Requirements');
Error Handling Best Practices
JavaScript Error Handling
async function robustApiCall(endpoint, method = 'GET', data = null, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const response = await fetch(`${BASE_URL}${endpoint}`, {
method,
headers: {
'X-Secret-Key': TASKIP_API_KEY,
'Content-Type': 'application/json'
},
body: data ? JSON.stringify(data) : null
});
const result = await response.json();
if (!response.ok) {
throw new Error(`API Error: ${result.message || response.statusText}`);
}
return result;
} catch (error) {
console.warn(`API call attempt ${i + 1} failed:`, error.message);
if (i === retries - 1) {
throw error;
}
// Exponential backoff
await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
}
}
}
Python Error Handling
import time
from requests.exceptions import RequestException
def safe_api_request(api, endpoint, method='GET', data=None, retries=3):
for attempt in range(retries):
try:
response = api.request(endpoint, method, data)
if response.get('success'):
return response
else:
raise Exception(f"API Error: {response.get('message', 'Unknown error')}")
except RequestException as e:
if attempt == retries - 1:
raise Exception(f"API request failed after {retries} attempts: {str(e)}")
time.sleep(2 ** attempt)
except Exception as e:
if attempt == retries - 1:
raise e
time.sleep(2 ** attempt)
Webhook Integration
Express.js Webhook Handler
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
app.post('/webhooks/taskip', (req, res) => {
const event = req.body;
console.log('Received webhook:', event.event, event.data);
switch (event.event) {
case 'invoice.paid':
console.log(`Invoice ${event.data.invoice_id} paid: $${event.data.amount}`);
break;
case 'ticket.created':
console.log(`New ticket created: ${event.data.ticket_id}`);
break;
case 'project.completed':
console.log(`Project ${event.data.project_id} completed`);
break;
}
res.status(200).json({ received: true });
});
app.listen(3000, () => {
console.log('Webhook server listening on port 3000');
});
These examples provide a solid foundation for integrating TaskIP API into your applications. Start with the authentication setup and gradually build more complex integrations.
Tip: Test these examples with small datasets first before implementing full workflows in production. Remember to handle rate limits and implement proper error handling for production use.