API Version: v1.2.0
View ChangelogDeveloper API DocumentationDocs
Node.js Examples
Complete Node.js examples for integrating with the Zyhap Developer API using modern JavaScript/TypeScript.
Installation & Setup
First, install the required dependencies:
npm install axios # or npm install node-fetch
Basic API Client
Create a reusable API client class for making requests:
const axios = require('axios');
class ZyhapAPI {
constructor(apiKey, workspaceId, baseURL = 'https://api.zyhap.com/api/v1/public/marketing') {
this.client = axios.create({
baseURL,
headers: {
'X-API-Key': apiKey,
'X-Workspace-ID': workspaceId,
'Content-Type': 'application/json'
}
});
// Add response interceptor for error handling
this.client.interceptors.response.use(
response => response,
error => {
console.error('API Error:', error.response?.data?.error || error.message);
throw error;
}
);
}
// Schedule a post
async schedulePost(postData) {
try {
const response = await this.client.post('/posts', postData);
return response.data.data;
} catch (error) {
throw new Error(`Failed to schedule post: ${error.response?.data?.error || error.message}`);
}
}
// Get posts with optional filtering
async getPosts(options = {}) {
try {
const response = await this.client.get('/posts', { params: options });
return response.data.data;
} catch (error) {
throw new Error(`Failed to get posts: ${error.response?.data?.error || error.message}`);
}
}
// Get connected accounts
async getAccounts() {
try {
const response = await this.client.get('/accounts');
return response.data.data.accounts;
} catch (error) {
throw new Error(`Failed to get accounts: ${error.response?.data?.error || error.message}`);
}
}
// Get connected pages/destinations
async getPages(platform = null) {
try {
const params = platform ? { platform } : {};
const response = await this.client.get('/pages', { params });
return response.data.data;
} catch (error) {
throw new Error(`Failed to get pages: ${error.response?.data?.error || error.message}`);
}
}
// Update a post
async updatePost(postId, updateData) {
try {
const response = await this.client.patch(`/posts/${postId}`, updateData);
return response.data.data;
} catch (error) {
throw new Error(`Failed to update post: ${error.response?.data?.error || error.message}`);
}
}
// Delete a post
async deletePost(postId) {
try {
const response = await this.client.delete(`/posts/${postId}`);
return response.data.data;
} catch (error) {
throw new Error(`Failed to delete post: ${error.response?.data?.error || error.message}`);
}
}
}
module.exports = ZyhapAPI;Basic Usage Example
const ZyhapAPI = require('./zyhap-api');
async function main() {
// Initialize the API client
const api = new ZyhapAPI(
process.env.ZYHAP_API_KEY,
process.env.ZYHAP_WORKSPACE_ID
);
try {
// Get connected pages/destinations
const pagesData = await api.getPages();
const pages = pagesData.pages;
console.log(`Available posting destinations: ${pages.length}`);
if (pages.length > 0) {
// Schedule a post to the first available destination
const destination = pages[0];
const postData = {
content: 'Hello from Node.js! š',
platforms: [{
platformId: destination.platform,
pageId: destination.id,
pageName: destination.name
}],
scheduledFor: new Date(Date.now() + 60 * 60 * 1000).toISOString() // 1 hour from now
};
const result = await api.schedulePost(postData);
console.log(`Post scheduled successfully: ${result.postId}`);
// Get scheduled posts
const posts = await api.getPosts({ status: 'scheduled', limit: 5 });
console.log(`You have ${posts.pagination.total} scheduled posts`);
}
} catch (error) {
console.error('Error:', error.message);
}
}
main();Bulk Post Scheduling
Schedule multiple posts across different platforms and times:
const ZyhapAPI = require('./zyhap-api');
class BulkScheduler {
constructor(apiKey, workspaceId) {
this.api = new ZyhapAPI(apiKey, workspaceId);
}
async scheduleBulkPosts(postsData) {
const results = [];
for (const postData of postsData) {
try {
const result = await this.api.schedulePost(postData);
results.push({ success: true, postId: result.postId, data: postData });
// Add delay to respect rate limits
await this.delay(1000); // 1 second delay
} catch (error) {
results.push({ success: false, error: error.message, data: postData });
}
}
return results;
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Generate scheduled times spread over hours/days
generateScheduledTimes(startTime, count, intervalHours = 2) {
const times = [];
const start = new Date(startTime);
for (let i = 0; i < count; i++) {
const scheduledTime = new Date(start.getTime() + (i * intervalHours * 60 * 60 * 1000));
times.push(scheduledTime.toISOString());
}
return times;
}
}
async function bulkScheduleExample() {
const scheduler = new BulkScheduler(
process.env.ZYHAP_API_KEY,
process.env.ZYHAP_WORKSPACE_ID
);
// Get available destinations
const pagesData = await scheduler.api.getPages();
const destinations = pagesData.pages;
if (destinations.length === 0) {
console.log('No connected accounts found');
return;
}
// Prepare bulk posts
const startTime = new Date(Date.now() + 60 * 60 * 1000); // Start in 1 hour
const scheduledTimes = scheduler.generateScheduledTimes(startTime, 5, 3); // 5 posts, 3 hours apart
const bulkPosts = scheduledTimes.map((scheduledFor, index) => ({
content: `Scheduled post #${index + 1} - Posted at ${new Date(scheduledFor).toLocaleString()}`,
platforms: [{
platformId: destinations[0].platform,
pageId: destinations[0].id,
pageName: destinations[0].name
}],
scheduledFor
}));
console.log(`Scheduling ${bulkPosts.length} posts...`);
const results = await scheduler.scheduleBulkPosts(bulkPosts);
// Report results
const successful = results.filter(r => r.success).length;
const failed = results.filter(r => !r.success).length;
console.log(`Successfully scheduled: ${successful} posts`);
console.log(`Failed: ${failed} posts`);
if (failed > 0) {
console.log('Failed posts:', results.filter(r => !r.success));
}
}
bulkScheduleExample();Chatbot Integration
Example of integrating with a Discord bot for scheduling posts:
const { Client, GatewayIntentBits } = require('discord.js');
const ZyhapAPI = require('./zyhap-api');
class SocialMediaBot {
constructor(discordToken, zyhapApiKey, zyhapWorkspaceId) {
this.client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]
});
this.zyhap = new ZyhapAPI(zyhapApiKey, zyhapWorkspaceId);
this.setupCommands();
this.client.login(discordToken);
}
setupCommands() {
this.client.on('ready', () => {
console.log(`Bot logged in as ${this.client.user.tag}`);
});
this.client.on('messageCreate', async (message) => {
if (message.author.bot) return;
// Command: !schedule <content> [time]
if (message.content.startsWith('!schedule ')) {
await this.handleScheduleCommand(message);
}
// Command: !posts
if (message.content === '!posts') {
await this.handleListPostsCommand(message);
}
// Command: !accounts
if (message.content === '!accounts') {
await this.handleListAccountsCommand(message);
}
});
}
async handleScheduleCommand(message) {
try {
const args = message.content.slice(10).trim(); // Remove '!schedule '
const parts = args.split(' | ');
const content = parts[0];
const timeString = parts[1] || '1 hour';
if (!content) {
return message.reply('Please provide content to post. Usage: `!schedule <content> | <time>`');
}
// Parse time (simple implementation)
const scheduledFor = this.parseTimeString(timeString);
// Get first available destination
const pagesData = await this.zyhap.getPages();
if (pagesData.pages.length === 0) {
return message.reply('ā No connected social media accounts found.');
}
const destination = pagesData.pages[0];
// Schedule the post
const result = await this.zyhap.schedulePost({
content,
platforms: [{
platformId: destination.platform,
pageId: destination.id,
pageName: destination.name
}],
scheduledFor: scheduledFor.toISOString()
});
message.reply(
`ā
Post scheduled successfully!\n` +
`š Content: ${content.substring(0, 100)}${content.length > 100 ? '...' : ''}\n` +
`š
Scheduled for: ${scheduledFor.toLocaleString()}\n` +
`š Post ID: ${result.postId}`
);
} catch (error) {
message.reply(`ā Error scheduling post: ${error.message}`);
}
}
async handleListPostsCommand(message) {
try {
const posts = await this.zyhap.getPosts({ status: 'scheduled', limit: 5 });
if (posts.posts.length === 0) {
return message.reply('š No scheduled posts found.');
}
let response = 'š
**Upcoming Scheduled Posts:**\n';
posts.posts.forEach((post, index) => {
const scheduledDate = new Date(post.scheduledFor).toLocaleString();
const preview = post.content.substring(0, 50) + (post.content.length > 50 ? '...' : '');
response += `${index + 1}. ${preview} - ${scheduledDate}\n`;
});
response += `\nš Total scheduled: ${posts.pagination.total}`;
message.reply(response);
} catch (error) {
message.reply(`ā Error fetching posts: ${error.message}`);
}
}
async handleListAccountsCommand(message) {
try {
const pagesData = await this.zyhap.getPages();
if (pagesData.pages.length === 0) {
return message.reply('š No connected social media accounts found.');
}
let response = 'š **Connected Social Accounts:**\n';
Object.entries(pagesData.byPlatform).forEach(([platform, platformPages]) => {
response += `**${platform.toUpperCase()}** (${platformPages.length} destinations)\n`;
platformPages.forEach(page => {
response += ` ⢠${page.name}\n`;
});
});
message.reply(response);
} catch (error) {
message.reply(`ā Error fetching accounts: ${error.message}`);
}
}
parseTimeString(timeString) {
const now = new Date();
const lowercaseTime = timeString.toLowerCase();
if (lowercaseTime.includes('hour')) {
const hours = parseInt(lowercaseTime) || 1;
return new Date(now.getTime() + hours * 60 * 60 * 1000);
} else if (lowercaseTime.includes('minute')) {
const minutes = parseInt(lowercaseTime) || 30;
return new Date(now.getTime() + minutes * 60 * 1000);
} else if (lowercaseTime.includes('day')) {
const days = parseInt(lowercaseTime) || 1;
return new Date(now.getTime() + days * 24 * 60 * 60 * 1000);
} else {
// Default to 1 hour
return new Date(now.getTime() + 60 * 60 * 1000);
}
}
}
// Initialize the bot
const bot = new SocialMediaBot(
process.env.DISCORD_TOKEN,
process.env.ZYHAP_API_KEY,
process.env.ZYHAP_WORKSPACE_ID
);Advanced Error Handling
const ZyhapAPI = require('./zyhap-api');
class RobustZyhapClient extends ZyhapAPI {
constructor(apiKey, workspaceId, options = {}) {
super(apiKey, workspaceId);
this.maxRetries = options.maxRetries || 3;
this.retryDelay = options.retryDelay || 1000;
}
async schedulePostWithRetry(postData, retries = 0) {
try {
return await this.schedulePost(postData);
} catch (error) {
if (retries < this.maxRetries && this.isRetryableError(error)) {
console.log(`Retrying request in ${this.retryDelay}ms (attempt ${retries + 1}/${this.maxRetries})`);
await this.delay(this.retryDelay * Math.pow(2, retries)); // Exponential backoff
return this.schedulePostWithRetry(postData, retries + 1);
}
throw error;
}
}
isRetryableError(error) {
const status = error.response?.status;
return status === 429 || status >= 500; // Rate limit or server errors
}
async delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Validate post data before sending
validatePostData(postData) {
const errors = [];
if (!postData.content || postData.content.trim().length === 0) {
errors.push('Content is required');
}
if (!postData.platforms || postData.platforms.length === 0) {
errors.push('At least one platform is required');
}
if (!postData.publishImmediately && !postData.scheduledFor) {
errors.push('scheduledFor is required when not publishing immediately');
}
if (postData.scheduledFor) {
const scheduledDate = new Date(postData.scheduledFor);
if (scheduledDate <= new Date()) {
errors.push('Scheduled time must be in the future');
}
}
if (errors.length > 0) {
throw new Error(`Validation errors: ${errors.join(', ')}`);
}
return true;
}
async safeSchedulePost(postData) {
try {
// Validate data first
this.validatePostData(postData);
// Schedule with retry logic
return await this.schedulePostWithRetry(postData);
} catch (error) {
console.error('Failed to schedule post:', {
error: error.message,
postData: {
content: postData.content?.substring(0, 100),
platforms: postData.platforms?.map(p => p.platformId),
scheduledFor: postData.scheduledFor
}
});
throw error;
}
}
}
// Usage example
async function robustSchedulingExample() {
const client = new RobustZyhapClient(
process.env.ZYHAP_API_KEY,
process.env.ZYHAP_WORKSPACE_ID,
{ maxRetries: 3, retryDelay: 1000 }
);
try {
const result = await client.safeSchedulePost({
content: 'This post will be scheduled with robust error handling!',
platforms: [{
platformId: 'facebook',
"uniqueId": "your_page_uniqueId",
pageName: 'Your Page Name'
}],
scheduledFor: new Date(Date.now() + 60 * 60 * 1000).toISOString()
});
console.log('Post scheduled successfully:', result.postId);
} catch (error) {
console.error('Final error after all retries:', error.message);
}
}
robustSchedulingExample();Environment Variables Setup
Create a .env file in your project root:
ZYHAP_API_KEY=your_developer_api_key_here ZYHAP_WORKSPACE_ID=your_workspace_id_here DISCORD_TOKEN=your_discord_bot_token_here
Don't forget to add .env to your .gitignore file!