Public APIAPI Code Examples

API Code Examples

Ready-to-use code examples for the SocialRails Public API in curl, JavaScript, and Python.

Ready-to-use examples for common operations with the SocialRails Public API.

Replace YOUR_API_KEY with your actual API key in all examples.


curl

List scheduled posts

curl -X GET "https://socialrails.com/api/v1/posts?status=scheduled&limit=10" \
  -H "Authorization: Bearer YOUR_API_KEY"

Create a scheduled post

curl -X POST "https://socialrails.com/api/v1/posts" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "Excited to share our latest product update!",
    "platform": "twitter",
    "scheduled_for": "2026-03-10T14:00:00Z"
  }'

Generate AI content

curl -X POST "https://socialrails.com/api/v1/ai/generate" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Write a LinkedIn post about the importance of consistent branding",
    "platform": "linkedin",
    "tone": "professional"
  }'

Get analytics for the last 30 days

curl -X GET "https://socialrails.com/api/v1/analytics?period=30d" \
  -H "Authorization: Bearer YOUR_API_KEY"

JavaScript (fetch)

List posts

const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://socialrails.com/api/v1';
 
async function listPosts(status = 'scheduled', limit = 50) {
  const response = await fetch(
    `${BASE_URL}/posts?status=${status}&limit=${limit}`,
    {
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
      },
    }
  );
 
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error.message);
  }
 
  return response.json();
}
 
// Usage
const { data, pagination } = await listPosts('scheduled', 10);
console.log(`Found ${pagination.total} scheduled posts`);

Schedule a post

async function schedulePost(content, platform, scheduledFor) {
  const response = await fetch(`${BASE_URL}/posts`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      content,
      platform,
      scheduled_for: scheduledFor,
    }),
  });
 
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error.message);
  }
 
  return response.json();
}
 
// Usage
const result = await schedulePost(
  'Check out our new feature!',
  'twitter',
  '2026-03-10T14:00:00Z'
);
console.log('Post created:', result.data.id);

Generate AI content

async function generateContent(prompt, platform, tone) {
  const response = await fetch(`${BASE_URL}/ai/generate`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ prompt, platform, tone }),
  });
 
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error.message);
  }
 
  return response.json();
}
 
// Usage
const { data } = await generateContent(
  'Write a tweet about our summer sale with 25% off',
  'twitter',
  'humorous'
);
console.log('Generated:', data.content);

Python (requests)

List posts

import requests
 
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://socialrails.com/api/v1"
 
def list_posts(status="scheduled", limit=50):
    response = requests.get(
        f"{BASE_URL}/posts",
        params={"status": status, "limit": limit},
        headers={"Authorization": f"Bearer {API_KEY}"},
    )
    response.raise_for_status()
    return response.json()
 
# Usage
result = list_posts("scheduled", 10)
print(f"Found {result['pagination']['total']} scheduled posts")
for post in result["data"]:
    print(f"  - [{post['platform']}] {post['content'][:60]}...")

Schedule a post

def schedule_post(content, platform, scheduled_for):
    response = requests.post(
        f"{BASE_URL}/posts",
        json={
            "content": content,
            "platform": platform,
            "scheduled_for": scheduled_for,
        },
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
    )
    response.raise_for_status()
    return response.json()
 
# Usage
result = schedule_post(
    "Excited to share our Q1 results!",
    "linkedin",
    "2026-03-10T09:00:00Z",
)
print(f"Post created: {result['data']['id']}")

Generate AI content

def generate_content(prompt, platform=None, tone="professional"):
    response = requests.post(
        f"{BASE_URL}/ai/generate",
        json={"prompt": prompt, "platform": platform, "tone": tone},
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
    )
    response.raise_for_status()
    return response.json()
 
# Usage
result = generate_content(
    "Write an Instagram caption for a photo of our team at a conference",
    platform="instagram",
    tone="casual",
)
print(f"Generated: {result['data']['content']}")

Full workflow: Generate and schedule

# Generate content, then schedule it
ai_result = generate_content(
    "Write a Monday motivation post for our tech startup",
    platform="twitter",
    tone="inspirational",
)
 
post_result = schedule_post(
    content=ai_result["data"]["content"],
    platform="twitter",
    scheduled_for="2026-03-10T08:00:00Z",
)
 
print(f"Scheduled AI-generated post: {post_result['data']['id']}")

Complete Workflows

Batch post to multiple platforms

curl -X POST "https://socialrails.com/api/v1/posts/batch" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "We just launched our public API! Build integrations, automate posting, and more.",
    "platforms": ["twitter", "linkedin", "facebook"],
    "scheduled_for": "2026-03-10T14:00:00Z"
  }'

Upload an image and create a post

# Step 1: Upload the image
MEDIA=$(curl -s -X POST "https://socialrails.com/api/v1/media/upload" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@product-screenshot.png")
 
MEDIA_KEY=$(echo $MEDIA | jq -r '.data.key')
 
# Step 2: Create a post with the uploaded media
curl -X POST "https://socialrails.com/api/v1/posts" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"content\": \"Check out our new dashboard design!\",
    \"platform\": \"twitter\",
    \"media\": [\"$MEDIA_KEY\"],
    \"scheduled_for\": \"2026-03-10T14:00:00Z\"
  }"

Upload a video with thumbnail

# Step 1: Upload the video
VIDEO=$(curl -s -X POST "https://socialrails.com/api/v1/media/upload" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@product-demo.mp4")
 
VIDEO_KEY=$(echo $VIDEO | jq -r '.data.key')
 
# Step 2: Upload a thumbnail (cover image)
THUMB=$(curl -s -X POST "https://socialrails.com/api/v1/media/upload" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "file=@cover.jpg" \
  -F "type=thumbnail")
 
THUMB_KEY=$(echo $THUMB | jq -r '.data.key')
 
# Step 3: Schedule a video post across platforms
curl -X POST "https://socialrails.com/api/v1/posts/batch" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"content\": \"Watch our product demo!\",
    \"platforms\": [\"tiktok\", \"instagram\", \"youtube\"],
    \"media\": [\"$VIDEO_KEY\", \"$THUMB_KEY\"],
    \"scheduled_for\": \"2026-03-10T14:00:00Z\"
  }"

Update a scheduled post

curl -X PATCH "https://socialrails.com/api/v1/posts/POST_ID" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "Updated: We just launched our public API! Check the docs at socialrails.com/documentation",
    "scheduled_for": "2026-03-11T10:00:00Z"
  }'

Register a webhook (JavaScript)

async function registerWebhook(url, events) {
  const response = await fetch(`${BASE_URL}/webhooks`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ url, events }),
  });
 
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error.message);
  }
 
  const { data } = await response.json();
  console.log('Webhook registered:', data.id);
  console.log('Save this secret for verification:', data.secret);
  return data;
}
 
// Usage
await registerWebhook(
  'https://your-app.com/webhooks/socialrails',
  ['post.published', 'post.failed']
);

Content calendar automation (Python)

from datetime import datetime, timedelta
 
def schedule_week_of_content(posts):
    """Schedule a week of posts, one per day at 9am UTC."""
    results = []
    for i, post in enumerate(posts):
        scheduled_time = (
            datetime.utcnow().replace(hour=9, minute=0, second=0)
            + timedelta(days=i + 1)
        )
        result = schedule_post(
            content=post["content"],
            platform=post["platform"],
            scheduled_for=scheduled_time.isoformat() + "Z",
        )
        results.append(result)
        print(f"Day {i+1}: Scheduled '{post['content'][:40]}...' for {post['platform']}")
    return results
 
# Usage
week_posts = [
    {"content": "Monday motivation: Start strong!", "platform": "twitter"},
    {"content": "Tuesday tip: Batch your content creation.", "platform": "linkedin"},
    {"content": "Midweek check-in: How's your week going?", "platform": "twitter"},
    {"content": "Thursday thoughts on our product roadmap.", "platform": "linkedin"},
    {"content": "Friday wins: What did you accomplish this week?", "platform": "twitter"},
]
 
schedule_week_of_content(week_posts)