Code Examples

Practical examples and code snippets to help you integrate Postally API into your applications.

Bulk Post Scheduling

Schedule multiple posts at once with different timing and platforms.

JavaScript/Node.js

const posts = [
  {
    content: "Monday motivation! 💪 #MondayMotivation",
    platforms: ["twitter", "instagram"],
    schedule_time: "2024-01-01T09:00:00Z"
  },
  {
    content: "Midweek check-in! How's everyone doing?",
    platforms: ["twitter", "linkedin"],
    schedule_time: "2024-01-03T14:00:00Z"
  },
  {
    content: "Friday vibes! 🎉 #TGIF",
    platforms: ["instagram", "facebook"],
    schedule_time: "2024-01-05T17:00:00Z"
  }
];

const scheduleBulkPosts = async () => {
  const results = await Promise.all(
    posts.map(async (post) => {
      const response = await fetch('https://app.postally.io/api/v1/posts', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(post)
      });
      return response.json();
    })
  );
  
  console.log('Scheduled posts:', results);
};

scheduleBulkPosts();

AI Content Generation Workflow

Generate content with AI and automatically schedule it across platforms.

Python

import requests
import json
from datetime import datetime, timedelta

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://app.postally.io/api/v1"

def generate_and_schedule_content():
    # Generate AI content
    ai_request = {
        "prompt": "Create an engaging post about productivity tips",
        "platform": "linkedin",
        "tone": "professional",
        "include_hashtags": True,
        "max_length": 300
    }
    
    ai_response = requests.post(
        f"{BASE_URL}/ai/generate",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json=ai_request
    )
    
    generated_content = ai_response.json()
    
    # Schedule the generated content
    schedule_time = datetime.now() + timedelta(hours=2)
    
    post_request = {
        "content": generated_content["content"],
        "platforms": ["linkedin", "twitter"],
        "schedule_time": schedule_time.isoformat() + "Z",
        "hashtags": generated_content.get("hashtags", [])
    }
    
    schedule_response = requests.post(
        f"{BASE_URL}/posts",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json=post_request
    )
    
    return schedule_response.json()

result = generate_and_schedule_content()
print(f"Scheduled post: {result['id']}")

Analytics Dashboard Integration

Fetch analytics data and create custom dashboards.

React Component

import React, { useState, useEffect } from 'react';

const AnalyticsDashboard = () => {
  const [analytics, setAnalytics] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchAnalytics = async () => {
      try {
        const response = await fetch('/api/postally-analytics', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${process.env.POSTALLY_API_KEY}`,
            'Content-Type': 'application/json'
          }
        });
        
        const data = await response.json();
        setAnalytics(data);
      } catch (error) {
        console.error('Failed to fetch analytics:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchAnalytics();
  }, []);

  if (loading) return <div>Loading analytics...</div>;

  return (
    <div className="analytics-dashboard">
      <h2>Social Media Performance</h2>
      <div className="metrics-grid">
        <div className="metric-card">
          <h3>Total Posts</h3>
          <p>{analytics.total_posts}</p>
        </div>
        <div className="metric-card">
          <h3>Engagement Rate</h3>
          <p>{analytics.engagement_rate}%</p>
        </div>
        <div className="metric-card">
          <h3>Best Performing Platform</h3>
          <p>{analytics.best_platform}</p>
        </div>
      </div>
    </div>
  );
};

export default AnalyticsDashboard;

Webhook Integration

Handle real-time notifications when posts are published or failed.

Express.js Webhook Handler

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

app.use(express.json());

// Webhook endpoint for Postally events
app.post('/webhooks/postally', (req, res) => {
  const signature = req.headers['x-postally-signature'];
  const payload = JSON.stringify(req.body);
  
  // Verify webhook signature (recommended for security)
  const expectedSignature = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET)
    .update(payload)
    .digest('hex');
  
  if (signature !== `sha256=${expectedSignature}`) {
    return res.status(401).send('Invalid signature');
  }
  
  const { event_type, data } = req.body;
  
  switch (event_type) {
    case 'post.published':
      console.log(`Post ${data.post_id} published successfully`);
      // Update your database, send notifications, etc.
      break;
      
    case 'post.failed':
      console.log(`Post ${data.post_id} failed: ${data.error}`);
      // Handle failed posts, retry logic, etc.
      break;
      
    case 'account.disconnected':
      console.log(`Account ${data.account_id} disconnected`);
      // Handle account disconnections
      break;
      
    default:
      console.log(`Unknown event type: ${event_type}`);
  }
  
  res.status(200).send('OK');
});

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

Official SDKs

We provide official SDKs to make integration even easier:

JavaScript/TypeScript

npm install @postally/sdk

Python

pip install postally-python

PHP

composer require postally/sdk