Skip to content

Code Examples

This guide provides practical code examples for common API operations in multiple programming languages. All examples include proper error handling and best practices.

Quick Start Examples

cURL (Command Line)

List Contacts

Terminal window
curl -X GET "https://api.sellercockpit.com/v1/contacts?limit=10" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json"

Get Single Contact

Terminal window
curl -X GET "https://api.sellercockpit.com/v1/contacts/CONTACT_ID" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json"

Create Contact

Terminal window
curl -X POST "https://api.sellercockpit.com/v1/contacts" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"first_name": "Jane",
"last_name": "Smith",
"job_title": "CTO",
"organization_id": "ORGANIZATION_ID",
"emails": [
{
"email": "jane.smith@example.com",
"type": "work",
"is_primary": true
}
],
"phones": [
{
"number": "+1234567890",
"type": "work",
"is_primary": true
}
]
}'

Update Contact

Terminal window
curl -X PATCH "https://api.sellercockpit.com/v1/contacts/CONTACT_ID" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"job_title": "VP of Engineering"
}'

Delete Contact (Soft Delete)

Terminal window
curl -X DELETE "https://api.sellercockpit.com/v1/contacts/CONTACT_ID" \
-H "Authorization: Bearer YOUR_API_KEY"

JavaScript/TypeScript

Setup API Client

api-client.ts
const API_BASE_URL = 'https://api.sellercockpit.com/v1';
const API_KEY = process.env.SELLERCOCKPIT_API_KEY;
interface ApiResponse<T> {
data?: T;
pagination?: {
total: number;
limit: number;
offset: number;
has_more: boolean;
};
error?: {
code: string;
message: string;
details?: Array<{ field: string; message: string }>;
};
}
class SellerCockpitAPI {
private baseUrl: string;
private apiKey: string;
constructor(apiKey: string, baseUrl = API_BASE_URL) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
}
private async request<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const url = `${this.baseUrl}${endpoint}`;
const headers = {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
...options.headers,
};
const response = await fetch(url, { ...options, headers });
const data: ApiResponse<T> = await response.json();
if (!response.ok) {
throw new Error(
`API Error: ${data.error?.code} - ${data.error?.message}`
);
}
return data.data as T;
}
// GET request
async get<T>(endpoint: string, params?: Record<string, any>): Promise<T> {
const queryString = params
? '?' + new URLSearchParams(params).toString()
: '';
return this.request<T>(`${endpoint}${queryString}`, { method: 'GET' });
}
// POST request
async post<T>(endpoint: string, body: any): Promise<T> {
return this.request<T>(endpoint, {
method: 'POST',
body: JSON.stringify(body),
});
}
// PATCH request
async patch<T>(endpoint: string, body: any): Promise<T> {
return this.request<T>(endpoint, {
method: 'PATCH',
body: JSON.stringify(body),
});
}
// DELETE request
async delete<T>(endpoint: string): Promise<T> {
return this.request<T>(endpoint, { method: 'DELETE' });
}
}
export const api = new SellerCockpitAPI(API_KEY!);

List Contacts with Pagination

interface Contact {
id: string;
first_name: string;
last_name: string;
job_title?: string;
organization_id?: string;
emails: Array<{
email: string;
type: string;
is_primary: boolean;
}>;
}
async function listContacts() {
try {
const response = await api.get<Contact[]>('/contacts', {
limit: 20,
offset: 0,
});
console.log('Contacts:', response);
} catch (error) {
console.error('Error fetching contacts:', error);
}
}

Create Contact

async function createContact() {
try {
const newContact = await api.post<Contact>('/contacts', {
first_name: 'John',
last_name: 'Doe',
job_title: 'Sales Manager',
emails: [
{
email: 'john.doe@example.com',
type: 'work',
is_primary: true,
},
],
phones: [
{
number: '+1234567890',
type: 'mobile',
is_primary: true,
},
],
});
console.log('Created contact:', newContact);
return newContact;
} catch (error) {
console.error('Error creating contact:', error);
throw error;
}
}

Update Contact

async function updateContact(contactId: string) {
try {
const updated = await api.patch<Contact>(`/contacts/${contactId}`, {
job_title: 'Senior Sales Manager',
});
console.log('Updated contact:', updated);
return updated;
} catch (error) {
console.error('Error updating contact:', error);
throw error;
}
}

Python

Setup API Client

import os
import requests
from typing import Optional, Dict, Any, List
API_BASE_URL = 'https://api.sellercockpit.com/v1'
API_KEY = os.getenv('SELLERCOCKPIT_API_KEY')
class SellerCockpitAPI:
def __init__(self, api_key: str, base_url: str = API_BASE_URL):
self.api_key = api_key
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json',
})
def _request(
self,
method: str,
endpoint: str,
params: Optional[Dict[str, Any]] = None,
json: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
url = f'{self.base_url}{endpoint}'
response = self.session.request(
method=method,
url=url,
params=params,
json=json,
)
data = response.json()
if not response.ok:
error = data.get('error', {})
raise Exception(
f"API Error: {error.get('code')} - {error.get('message')}"
)
return data.get('data')
def get(self, endpoint: str, params: Optional[Dict] = None):
return self._request('GET', endpoint, params=params)
def post(self, endpoint: str, json: Dict):
return self._request('POST', endpoint, json=json)
def patch(self, endpoint: str, json: Dict):
return self._request('PATCH', endpoint, json=json)
def delete(self, endpoint: str):
return self._request('DELETE', endpoint)
api = SellerCockpitAPI(API_KEY)

List Contacts

def list_contacts(limit: int = 20, offset: int = 0):
try:
contacts = api.get('/contacts', params={
'limit': limit,
'offset': offset,
})
print(f'Found {len(contacts)} contacts')
return contacts
except Exception as e:
print(f'Error fetching contacts: {e}')
raise

Create Contact

def create_contact(
first_name: str,
last_name: str,
email: str,
job_title: Optional[str] = None,
organization_id: Optional[str] = None,
):
try:
contact = api.post('/contacts', json={
'first_name': first_name,
'last_name': last_name,
'job_title': job_title,
'organization_id': organization_id,
'emails': [
{
'email': email,
'type': 'work',
'is_primary': True,
}
],
})
print(f'Created contact: {contact["id"]}')
return contact
except Exception as e:
print(f'Error creating contact: {e}')
raise

Update Contact

def update_contact(contact_id: str, updates: Dict[str, Any]):
try:
contact = api.patch(f'/contacts/{contact_id}', json=updates)
print(f'Updated contact: {contact_id}')
return contact
except Exception as e:
print(f'Error updating contact: {e}')
raise

Integration Platform Examples

n8n Workflow

{
"nodes": [
{
"parameters": {
"url": "https://api.sellercockpit.com/v1/contacts",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"method": "POST",
"sendBody": true,
"bodyParameters": {
"parameters": [
{
"name": "first_name",
"value": "={{ $json.firstName }}"
},
{
"name": "last_name",
"value": "={{ $json.lastName }}"
},
{
"name": "emails",
"value": "={{ [{ email: $json.email, type: 'work', is_primary: true }] }}"
}
]
}
},
"type": "n8n-nodes-base.httpRequest",
"name": "Create Contact in SellerCockpit"
}
]
}

Setup Steps:

  1. Add HTTP Request node
  2. Set method to POST
  3. URL: https://api.sellercockpit.com/v1/contacts
  4. Authentication: Header Auth
    • Name: Authorization
    • Value: Bearer YOUR_API_KEY
  5. Headers:
    • Content-Type: application/json
  6. Body: JSON with contact data

Make (Integromat)

HTTP Module Configuration:

  • URL: https://api.sellercockpit.com/v1/contacts
  • Method: POST
  • Headers:
    • Authorization: Bearer YOUR_API_KEY
    • Content-Type: application/json
  • Body Type: Raw
  • Request Content: JSON
{
"first_name": "{{firstName}}",
"last_name": "{{lastName}}",
"emails": [
{
"email": "{{email}}",
"type": "work",
"is_primary": true
}
]
}

Zapier Webhook

Setup:

  1. Choose “Webhooks by Zapier” app
  2. Select “POST” action
  3. Configure:
    • URL: https://api.sellercockpit.com/v1/contacts
    • Headers:
      Authorization: Bearer YOUR_API_KEY
      Content-Type: application/json
    • Data: Pass-through or Structured
  4. Map fields from trigger to API request

Complete Workflow Example

This example demonstrates a complete workflow: Create organization → Add contact → Create deal.

JavaScript/TypeScript

async function completeWorkflow() {
try {
// Step 1: Create Organization
console.log('Creating organization...');
const organization = await api.post('/organizations', {
name: 'Acme Corp',
organization_type: 'prospect',
websites: [
{
url: 'https://acme.example.com',
type: 'main',
is_primary: true,
},
],
addresses: [
{
street: '123 Main St',
city: 'San Francisco',
state: 'CA',
postal_code: '94105',
country: 'US',
type: 'billing',
is_primary: true,
},
],
});
console.log('Created organization:', organization.id);
// Step 2: Create Contact at Organization
console.log('Creating contact...');
const contact = await api.post('/contacts', {
first_name: 'Jane',
last_name: 'Smith',
job_title: 'CEO',
organization_id: organization.id,
emails: [
{
email: 'jane@acme.example.com',
type: 'work',
is_primary: true,
},
],
phones: [
{
number: '+14155551234',
type: 'work',
is_primary: true,
},
],
});
console.log('Created contact:', contact.id);
// Step 3: Create Deal
console.log('Creating deal...');
const deal = await api.post('/deals', {
title: 'Q1 2024 - Acme Corp',
organization_id: organization.id,
primary_contact_id: contact.id,
stage: 'qualified',
value: 50000,
currency: 'USD',
expected_close_date: '2024-03-31',
probability: 75,
notes: 'Initial outreach went well. CEO interested in demo.',
});
console.log('Created deal:', deal.id);
// Step 4: Create Follow-up Task
console.log('Creating task...');
const task = await api.post('/tasks', {
title: 'Schedule product demo with Jane',
description: 'Follow up on initial call to schedule demo',
due_date: '2024-01-15T14:00:00Z',
priority: 'high',
contact_id: contact.id,
deal_id: deal.id,
});
console.log('Created task:', task.id);
console.log('Workflow complete!');
return { organization, contact, deal, task };
} catch (error) {
console.error('Workflow failed:', error);
throw error;
}
}
// Run the workflow
completeWorkflow()
.then(() => console.log('Success!'))
.catch((err) => console.error('Failed:', err));

Python

def complete_workflow():
"""Create organization, contact, deal, and task"""
try:
# Step 1: Create Organization
print('Creating organization...')
organization = api.post('/organizations', json={
'name': 'Acme Corp',
'organization_type': 'prospect',
'websites': [
{
'url': 'https://acme.example.com',
'type': 'main',
'is_primary': True,
}
],
'addresses': [
{
'street': '123 Main St',
'city': 'San Francisco',
'state': 'CA',
'postal_code': '94105',
'country': 'US',
'type': 'billing',
'is_primary': True,
}
],
})
print(f'Created organization: {organization["id"]}')
# Step 2: Create Contact
print('Creating contact...')
contact = api.post('/contacts', json={
'first_name': 'Jane',
'last_name': 'Smith',
'job_title': 'CEO',
'organization_id': organization['id'],
'emails': [
{
'email': 'jane@acme.example.com',
'type': 'work',
'is_primary': True,
}
],
'phones': [
{
'number': '+14155551234',
'type': 'work',
'is_primary': True,
}
],
})
print(f'Created contact: {contact["id"]}')
# Step 3: Create Deal
print('Creating deal...')
deal = api.post('/deals', json={
'title': 'Q1 2024 - Acme Corp',
'organization_id': organization['id'],
'primary_contact_id': contact['id'],
'stage': 'qualified',
'value': 50000,
'currency': 'USD',
'expected_close_date': '2024-03-31',
'probability': 75,
'notes': 'Initial outreach went well. CEO interested in demo.',
})
print(f'Created deal: {deal["id"]}')
# Step 4: Create Task
print('Creating task...')
task = api.post('/tasks', json={
'title': 'Schedule product demo with Jane',
'description': 'Follow up on initial call to schedule demo',
'due_date': '2024-01-15T14:00:00Z',
'priority': 'high',
'contact_id': contact['id'],
'deal_id': deal['id'],
})
print(f'Created task: {task["id"]}')
print('Workflow complete!')
return {
'organization': organization,
'contact': contact,
'deal': deal,
'task': task,
}
except Exception as e:
print(f'Workflow failed: {e}')
raise
if __name__ == '__main__':
result = complete_workflow()
print('Success!')

Bulk Operations Example

Bulk Create Contacts

async function bulkCreateContacts(contacts: Array<any>) {
try {
const result = await api.post('/bulk/contacts', {
operations: contacts.map(contact => ({
operation: 'create',
data: contact,
})),
});
console.log('Bulk operation result:', result);
console.log(`Success: ${result.results.filter(r => r.success).length}`);
console.log(`Failed: ${result.results.filter(r => !r.success).length}`);
return result;
} catch (error) {
console.error('Bulk operation failed:', error);
throw error;
}
}
// Usage
const contactsToCreate = [
{
first_name: 'Alice',
last_name: 'Johnson',
emails: [{ email: 'alice@example.com', type: 'work', is_primary: true }],
},
{
first_name: 'Bob',
last_name: 'Williams',
emails: [{ email: 'bob@example.com', type: 'work', is_primary: true }],
},
];
await bulkCreateContacts(contactsToCreate);

Error Handling Example

async function robustApiCall<T>(
apiCall: () => Promise<T>,
maxRetries: number = 3
): Promise<T> {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await apiCall();
} catch (error: any) {
const errorData = error.response?.data?.error;
// Don't retry client errors
if (error.response?.status < 500) {
throw error;
}
// Rate limit - wait and retry
if (error.response?.status === 429) {
const retryAfter = parseInt(
error.response.headers['retry-after'] || '60'
);
console.log(`Rate limited. Waiting ${retryAfter}s...`);
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
continue;
}
// Server error - exponential backoff
if (attempt < maxRetries) {
const delay = Math.pow(2, attempt) * 1000;
console.log(`Retry ${attempt + 1}/${maxRetries} after ${delay}ms`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw error;
}
}
throw new Error('Max retries exceeded');
}
// Usage
const contact = await robustApiCall(() =>
api.post('/contacts', contactData)
);

Need More Examples?

For questions or custom integration help: