=============== LIBRARY RULES =============== From library maintainers: - Publora REST API base URL is https://api.publora.com/api/v1 - Authentication uses x-publora-key header with API key - MCP server is at mcp.publora.com with type http not url - Platform IDs format: {platform}-{id} e.g. twitter-123 - scheduledTime must be ISO 8601 UTC format - Media uploads use pre-signed S3 URLs via get-upload-url - Threads nested multi-part posts temporarily unavailable ### Basic TypeScript MCP Client Example Source: https://github.com/publora/publora-api-docs/blob/main/docs/mcp/client-setup.md Demonstrates how to connect to the MCP server, list tools, and call a tool using the Publora SDK in TypeScript. Ensure you have the necessary SDK installed. ```typescript import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; async function main() { const transport = new StreamableHTTPClientTransport( new URL("https://mcp.publora.com"), { headers: { Authorization: "Bearer sk_YOUR_API_KEY", }, } ); const client = new Client({ name: "publora-client", version: "1.0.0", }); await client.connect(transport); // List tools const tools = await client.listTools(); console.log(`Available tools: ${tools.tools.length}`); // Get connections const result = await client.callTool({ name: "list_connections", arguments: {}, }); console.log(result.content[0]); await client.close(); } main(); ``` -------------------------------- ### Get Platform Connections Example Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/rate-limits.md Shows how to retrieve a list of connected platforms, including their IDs, usernames, and token statuses. ```http GET https://api.publora.com/api/v1/platform-connections x-publora-key: sk_your_api_key ``` -------------------------------- ### Complete Publora API Example Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/python/quick-start.md A comprehensive example demonstrating the workflow from connecting accounts to creating and checking post status. ```python import requests from datetime import datetime, timedelta PUBLORA_API_KEY = 'YOUR_API_KEY' BASE_URL = 'https://api.publora.com/api/v1' def main(): headers = { 'Content-Type': 'application/json', 'x-publora-key': PUBLORA_API_KEY } # 1. Get connected accounts connections_response = requests.get( f'{BASE_URL}/platform-connections', headers={'x-publora-key': PUBLORA_API_KEY} ) connections = connections_response.json()['connections'] if not connections: print('No accounts connected. Visit app.publora.com to connect.') return # 2. Get platform IDs platform_ids = [c['platformId'] for c in connections] print('Posting to:', platform_ids) # 3. Create a post post_response = requests.post( f'{BASE_URL}/create-post', headers=headers, json={ 'content': 'Testing the Publora API - works great!', 'platforms': platform_ids } ) result = post_response.json() print('Created post:', result['postGroupId']) # 4. Check status import time time.sleep(5) status_response = requests.get( f'{BASE_URL}/get-post/{result["postGroupId"]}', headers={'x-publora-key': PUBLORA_API_KEY} ) status = status_response.json() for post in status['posts']: print(f"{post['platform']}: {post['status']}") if __name__ == '__main__': main() ``` -------------------------------- ### Create and Check Post Status with Node.js (axios) Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/cross-platform.md This Node.js example demonstrates creating a post with long content across multiple platforms and then checking the status of each platform's post. Ensure you have axios installed (`npm install axios`). ```javascript const axios = require('axios'); const api = axios.create({ baseURL: 'https://api.publora.com/api/v1', headers: { 'Content-Type': 'application/json', 'x-publora-key': 'YOUR_API_KEY' } }); const longContent = `We are thrilled to announce that our platform now supports 10 social media channels! Here is what's new: - Twitter/X threading for long posts - LinkedIn articles with rich formatting - Instagram Reels for video content - TikTok with automatic settings - YouTube with public visibility defaults - Facebook pages - Threads support - Telegram channels - Bluesky integration - Mastodon support This has been months in the making, and we cannot wait for you to try it out. Visit our website to learn more and connect your accounts today.`; const { data: post } = await api.post('/create-post', { content: longContent, platforms: [ 'twitter-123456', 'linkedin-ABCDEF', 'threads-111213', 'telegram-141516', 'bluesky-171819' ], scheduledTime: '2026-03-15T10:00:00.000Z' }); console.log('Post created:', post.postGroupId); // Check platform-level results after publishing const { data: status } = await api.get(`/get-post/${post.postGroupId}`); if (status.posts) { for (const platformPost of status.posts) { console.log(` ${platformPost.platform}: ${platformPost.status}`); } } ``` -------------------------------- ### Install Next.js Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/frameworks/nextjs.md Install Next.js using npm. No additional dependencies are required as the Publora API uses native fetch. ```bash npm install next ``` -------------------------------- ### Example: Get Bookmarks with Videos, Sorted by Likes Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/x-bookmarks.md Demonstrates searching for bookmarks that contain video media, sorted by the number of likes. Useful for finding popular video content. ```javascript // Example 3: Get bookmarks with videos, sorted by likes async function getPopularVideos() { try { const result = await searchBookmarks({ has_media: 'true', media_type: 'video', sort: 'likes', limit: 20 }); console.log(`Found ${result.pagination.totalItems} video bookmarks`); return result; } catch (error) { console.error('Failed:', error.message); throw error; } } ``` -------------------------------- ### Publora API Quick Reference: Python Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/cursor-ai.md Reference for making Publora API calls using Python. Includes setup for authentication headers and examples for listing connections, creating posts, checking status, and deleting posts. ```python # Cursor: Use this as reference for Publora API calls import requests BASE_URL = 'https://api.publora.com/api/v1' headers = { 'Content-Type': 'application/json', 'x-publora-key': os.environ['PUBLORA_API_KEY'] } # List connections connections = requests.get(f'{BASE_URL}/platform-connections', headers=headers).json() # Create post post = requests.post(f'{BASE_URL}/create-post', headers=headers, json={ 'content': 'Your post content', 'platforms': ['twitter-123456789'], 'scheduledTime': '2026-03-01T14:00:00.000Z', # Optional }).json() # Get post status status = requests.get(f'{BASE_URL}/get-post/{post_group_id}', headers=headers).json() # Delete post requests.delete(f'{BASE_URL}/delete-post/{post_group_id}', headers=headers) ``` -------------------------------- ### Install Dependencies Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/rate-limits.md Install the necessary libraries for making API requests. Use npm for JavaScript/Node.js and pip for Python. ```bash # JavaScript/Node.js npm install axios # Python pip install requests ``` -------------------------------- ### Create Draft Post and Get Upload URL with cURL Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/media-uploads.md This cURL example shows how to initiate a draft post and then request a pre-signed URL for uploading a video. It's the first step in the media upload process. ```bash API_KEY="YOUR_API_KEY" # Step 1: Create a draft post (no scheduledTime) POST_RESPONSE=$(curl -s -X POST https://api.publora.com/api/v1/create-post \ -H "Content-Type: application/json" \ -H "x-publora-key: $API_KEY" \ -d '{ "content": "Watch our latest promo video!", "platforms": ["twitter-123", "tiktok-789", "youtube-012"] }') POST_GROUP_ID=$(echo "$POST_RESPONSE" | jq -r '.postGroupId') ``` -------------------------------- ### Correct MCP Configuration Example Source: https://github.com/publora/publora-api-docs/blob/main/docs/mcp/troubleshooting.md Provides a valid example of an MCP client configuration, including the correct 'type', 'url', and 'Authorization' header format with the 'Bearer' prefix. ```json { "mcpServers": { "publora": { "type": "http", "url": "https://mcp.publora.com", "headers": { "Authorization": "Bearer sk_abc123..." } } } } ``` -------------------------------- ### Autonomous Agent Example with Publora MCP Source: https://github.com/publora/publora-api-docs/blob/main/docs/mcp/openclaw.md A complete Python implementation demonstrating autonomous social media management. It shows how to connect, get connected platforms, schedule posts, and list scheduled posts using the Publora MCP client. ```python import asyncio from datetime import datetime, timedelta from contextlib import asynccontextmanager from mcp import ClientSession from mcp.client.streamable_http import streamablehttp_client @asynccontextmanager def publora_session(api_key: str): """Context manager for Publora MCP connection.""" headers = {"Authorization": f"Bearer {api_key}"} async with streamablehttp_client("https://mcp.publora.com", headers=headers) as (read, write, _): async with ClientSession(read, write) as session: await session.initialize() yield session async def get_connections(session): """Get all connected platforms.""" result = await session.call_tool("list_connections", {}) return result.content[0].text async def schedule_post(session, content: str, platforms: list, scheduled_time: str): """Schedule a post to specified platforms.""" result = await session.call_tool("create_post", { "content": content, "platforms": platforms, "scheduledTime": scheduled_time }) return result.content[0].text async def get_scheduled_posts(session): """List all scheduled posts.""" result = await session.call_tool("list_posts", { "status": "scheduled" }) return result.content[0].text async def main(): async with publora_session("sk_YOUR_API_KEY") as session: # Get connected platforms connections = await get_connections(session) print("Connected platforms:", connections) # Schedule a post for next Monday at 2pm UTC next_monday = datetime.now() + timedelta(days=(7 - datetime.now().weekday()) % 7) scheduled_time = next_monday.replace( hour=14, minute=0, second=0, microsecond=0 ).isoformat() + "Z" result = await schedule_post( session, content="Automated post from OpenClaw agent!", platforms=["linkedin-YOUR_PLATFORM_ID"], scheduled_time=scheduled_time ) print("Scheduled:", result) # Check scheduled posts posts = await get_scheduled_posts(session) print("Upcoming posts:", posts) asyncio.run(main()) ``` -------------------------------- ### Upload Media and Post to Twitter/LinkedIn Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/go/quick-start.md This example demonstrates uploading media to Publora and associating it with a post. It first creates a post to get a post group ID, then retrieves an upload URL, uploads the file, and confirms the media attachment. ```go package main import ( "bytes" "fmt" "io" "log" "net/http" "os" "path/filepath" "your-project/publora" ) func getMimeType(filename string) string { ext := filepath.Ext(filename) mimeTypes := map[string]string{ ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".gif": "image/gif", ".mp4": "video/mp4", ".webp": "image/webp", } if mime, ok := mimeTypes[ext]; ok { return mime } return "application/octet-stream" } func main() { client := publora.NewClient(os.Getenv("PUBLORA_API_KEY")) filePath := "./screenshot.png" // Step 1: Create post first to get postGroupId postResp, err := client.CreatePost(&publora.CreatePostRequest{ Content: "Check out this screenshot!", Platforms: []string{"twitter-123456789", "linkedin-ABC123DEF"}, }) if err != nil { log.Fatalf("Failed to create post: %v", err) } postGroupID := postResp.PostGroupID fmt.Printf("Post created: %s\n", postGroupID) // Step 2: Get upload URL (media auto-attaches via postGroupId) fileName := filepath.Base(filePath) contentType := getMimeType(fileName) uploadResp, err := client.GetUploadURL(fileName, contentType, postGroupID) if err != nil { log.Fatalf("Failed to get upload URL: %v", err) } // Step 3: Upload file to S3 fileData, err := os.ReadFile(filePath) if err != nil { log.Fatalf("Failed to read file: %v", err) } req, _ := http.NewRequest("PUT", uploadResp.UploadURL, bytes.NewReader(fileData)) req.Header.Set("Content-Type", contentType) httpClient := &http.Client{} resp, err := httpClient.Do(req) if err != nil { log.Fatalf("Failed to upload file: %v", err) } defer resp.Body.Close() if resp.StatusCode >= 400 { body, _ := io.ReadAll(resp.Body) log.Fatalf("Upload failed: %s", body) } fmt.Printf("Media uploaded: %s\n", uploadResp.MediaID) fmt.Printf("File URL: %s\n", uploadResp.FileURL) fmt.Printf("Post with media created: %s\n", postGroupID) } ``` -------------------------------- ### Upload Video using Node.js (axios) Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/media-uploads.md This Node.js example demonstrates uploading a video using the axios library. It covers creating a draft post, getting an upload URL, uploading the video file, and scheduling the post. ```javascript const axios = require('axios'); const fs = require('fs'); const api = axios.create({ baseURL: 'https://api.publora.com/api/v1', headers: { 'Content-Type': 'application/json', 'x-publora-key': 'YOUR_API_KEY' } }); // Step 1: Create a draft post (no scheduledTime) const { data: postData } = await api.post('/create-post', { content: 'Watch our latest promo video!', platforms: ['twitter-123', 'tiktok-789', 'youtube-012'] // No scheduledTime = draft }); // Step 2: Get upload URL const { data: uploadData } = await api.post('/get-upload-url', { fileName: 'promo-video.mp4', contentType: 'video/mp4', type: 'video', postGroupId: postData.postGroupId }); // Step 3: Upload video const videoBuffer = fs.readFileSync('./promo-video.mp4'); await axios.put(uploadData.uploadUrl, videoBuffer, { headers: { 'Content-Type': 'video/mp4' }, maxContentLength: 512 * 1024 * 1024, // 512 MB maxBodyLength: 512 * 1024 * 1024 }); console.log('Video uploaded:', postData.postGroupId); // Step 4: Schedule the post await api.put(`/update-post/${postData.postGroupId}`, { status: 'scheduled', scheduledTime: '2026-03-15T16:00:00.000Z' }); console.log('Post scheduled!'); ``` -------------------------------- ### Install Python Requests Library Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/python/quick-start.md Install the necessary library for making HTTP requests. ```bash pip install requests ``` -------------------------------- ### Install Django and Requests Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/frameworks/django.md Install the necessary Python packages for Django development and making HTTP requests. ```bash pip install requests django ``` -------------------------------- ### Upload Video and Schedule Post with JavaScript (fetch) Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/media-uploads.md This example shows how to upload a video and schedule a post using the native fetch API in JavaScript. It follows the same pattern: create draft, get upload URL, upload video, schedule post. ```javascript const fs = require('fs'); const API_KEY = 'YOUR_API_KEY'; const BASE_URL = 'https://api.publora.com/api/v1'; // Step 1: Create a draft post (no scheduledTime) const postResponse = await fetch(`${BASE_URL}/create-post`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-publora-key': API_KEY }, body: JSON.stringify({ content: 'Watch our latest promo video!', platforms: ['twitter-123', 'tiktok-789', 'youtube-012'] // No scheduledTime = draft }) }); const { postGroupId } = await postResponse.json(); // Step 2: Get a pre-signed upload URL for the video const uploadUrlResponse = await fetch(`${BASE_URL}/get-upload-url`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-publora-key': API_KEY }, body: JSON.stringify({ fileName: 'promo-video.mp4', contentType: 'video/mp4', type: 'video', postGroupId: postGroupId }) }); const { uploadUrl } = await uploadUrlResponse.json(); // Step 3: Upload the video to S3 const videoBuffer = await fs.promises.readFile('./promo-video.mp4'); await fetch(uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'video/mp4' }, body: videoBuffer }); console.log('Video uploaded:', postGroupId); // Step 4: Schedule the post await fetch(`${BASE_URL}/update-post/${postGroupId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'x-publora-key': API_KEY }, body: JSON.stringify({ status: 'scheduled', scheduledTime: '2026-03-15T16:00:00.000Z' }) }); console.log('Post scheduled!'); ``` -------------------------------- ### REST API Authentication Example (Python) Source: https://github.com/publora/publora-api-docs/blob/main/docs/authentication.md Provides a Python example using the requests library to authenticate an API call by setting the 'x-publora-key' header. ```python response = requests.get( 'https://api.publora.com/api/v1/platform-connections', headers={'x-publora-key': os.environ['PUBLORA_API_KEY']} ) ``` -------------------------------- ### Get Post Comments cURL Example Source: https://github.com/publora/publora-api-docs/blob/main/docs/endpoints/linkedin-feed-retrieval.md Example using cURL to fetch comments for a specific LinkedIn post. Ensure to provide the correct `postedId` and `platformId`. ```bash curl -X POST "https://api.publora.com/api/v1/linkedin-post-comments" \ -H "x-publora-key: sk_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "postedId": "urn:li:share:7123456789", "platformId": "linkedin-ABC123", "count": 50 }' ``` -------------------------------- ### Get LinkedIn Posts cURL Example Source: https://github.com/publora/publora-api-docs/blob/main/docs/endpoints/linkedin-feed-retrieval.md Example using cURL to fetch LinkedIn posts. Ensure to include your API key and specify request parameters in the JSON body. ```bash curl -X POST "https://api.publora.com/api/v1/linkedin-posts" \ -H "x-publora-key: sk_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "platformId": "linkedin-ABC123", "count": 20, "sortBy": "LAST_MODIFIED" }' ``` -------------------------------- ### Post Text Message with Node.js (axios) Source: https://github.com/publora/publora-api-docs/blob/main/docs/platforms/telegram.md This Node.js example uses the `axios` library to post a text message to Telegram. Ensure `axios` is installed (`npm install axios`). ```javascript const axios = require('axios'); const content = `*Product Update v2.5* We have shipped the following improvements: - _Faster API response times_ (avg 45ms) - New batch endpoint for bulk operations - Improved error messages with error_code field > This update is backward compatible. No migration needed. Full changelog: [docs.example.com/changelog](https://docs.example.com/changelog)`; const response = await axios.post('https://api.publora.com/api/v1/create-post', { content, platforms: ['telegram-1001234567890'] }, { headers: { 'Content-Type': 'application/json', 'x-publora-key': 'YOUR_API_KEY' } }); console.log(response.data); // Response: { "success": true, "postGroupId": "abc123..." } ``` -------------------------------- ### Initialize PubloraClient Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/php/quick-start.md Demonstrates how to instantiate the PubloraClient with your API key. Ensure the API key is securely stored and accessed, for example, via environment variables. ```php c.platformId); const postResponse = await fetch('https://api.publora.com/api/v1/create-post', { method: 'POST', headers: { ...headers, 'x-publora-user-id': user._id }, body: JSON.stringify({ content: `Welcome to ${displayName}'s social presence, powered by our platform!`,, platforms, scheduledTime: '2026-03-15T14:00:00.000Z' }) }); const post = await postResponse.json(); console.log(`4. Post scheduled for user ${user._id}: ${post.postGroupId}`); return user; } // Usage const client = await onboardClient('acme-corp', 'Acme Corp'); ``` -------------------------------- ### Get Single LinkedIn Metric Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/linkedin-analytics.md Example demonstrating how to retrieve a single specific metric, such as 'IMPRESSION', for a LinkedIn post. Returns the count for the requested metric. ```javascript async function getImpressions(postedId, platformId) { try { const analytics = await getLinkedInAnalytics(postedId, platformId, 'IMPRESSION'); return analytics.count; } catch (error) { console.error('Failed to get impressions:', error.message); throw error; } } ``` -------------------------------- ### Complete Publora API Workflow Example Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/javascript/quick-start.md Demonstrates a full workflow: listing connected accounts, creating a post, and then checking its status after a short delay. Handles cases where no accounts are connected. ```javascript // Full workflow: list accounts, create post, check status async function main() { // 1. Get connected accounts const connections = await getConnections(); if (connections.length === 0) { console.log('No accounts connected. Visit app.publora.com to connect.'); return; } // 2. Get platform IDs const platforms = connections.map(c => c.platformId); console.log('Posting to:', platforms); // 3. Create a post const result = await createPost( 'Testing the Publora API - works great!', platforms ); // 4. Check status after a moment setTimeout(async () => { await getPostStatus(result.postGroupId); }, 5000); } main().catch(console.error); ``` -------------------------------- ### Get All LinkedIn Metrics Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/linkedin-analytics.md Example of how to retrieve all available analytics metrics for a LinkedIn post. Logs impressions, reactions, comments, shares, and reach to the console. ```javascript async function getAllMetrics(postedId, platformId) { try { const analytics = await getLinkedInAnalytics(postedId, platformId, 'ALL'); console.log('Impressions:', analytics.metrics.IMPRESSION); console.log('Reactions:', analytics.metrics.REACTION); console.log('Comments:', analytics.metrics.COMMENT); console.log('Shares:', analytics.metrics.RESHARE); console.log('Reach:', analytics.metrics.MEMBERS_REACHED); return analytics; } catch (error) { console.error('Failed to get analytics:', error.message); throw error; } } ``` -------------------------------- ### Example: Full Sync Loop for All Bookmarks Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/x-bookmarks.md Implements a loop to fetch all available bookmarks by repeatedly calling `syncBookmarks` until `hasMore` is false. Includes a 60-second delay between syncs to respect rate limits. ```javascript // Example 5: Full sync loop (fetch all bookmarks) async function fullSync() { let totalNew = 0; let totalUpdated = 0; let hasMore = true; while (hasMore) { const result = await syncBookmarks(100); totalNew += result.synced.inserted; totalUpdated += result.synced.updated; hasMore = result.hasMore; if (hasMore) { // Respect rate limit: 1 sync per 60 seconds console.log(`Synced batch. Waiting 60s before next...`); await new Promise(r => setTimeout(r, 60000)); } } console.log(`Full sync complete: ${totalNew} new, ${totalUpdated} updated`); return { totalNew, totalUpdated }; } ``` -------------------------------- ### Get LinkedIn Account Statistics (JavaScript) Source: https://github.com/publora/publora-api-docs/blob/main/docs/endpoints/linkedin-statistics.md Fetches aggregated statistics for a LinkedIn account using the API. This example requests all metrics with total aggregation. ```javascript const response = await fetch('https://api.publora.com/api/v1/linkedin-account-statistics', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-publora-key': 'YOUR_API_KEY' }, body: JSON.stringify({ platformId: 'linkedin-Tz9W5i6ZYG', queryTypes: 'ALL', aggregation: 'TOTAL' }) }); const data = await response.json(); console.log(`Total impressions: ${data.metrics.IMPRESSION}`); console.log(`Total engagement: ${data.metrics.REACTION + data.metrics.COMMENT}`); ``` -------------------------------- ### Generate CSV Template Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/python/bulk-csv-import.md Creates a sample CSV file with predefined columns and example data. Use this as a starting point for preparing your CSV for bulk import. ```python def generate_csv_template(output_file='posts_template.csv'): """Generate a sample CSV template.""" sample_rows = [ { 'content': 'Monday motivation: Start your week strong!', 'platforms': 'twitter-123456;linkedin-ABC123', 'scheduled_time': '2026-03-01T09:00:00Z', 'media_url': '' }, { 'content': 'Check out our latest blog post!', 'platforms': 'twitter-123456', 'scheduled_time': '2026-03-01T14:00:00Z', 'media_url': 'https://example.com/blog-image.png' }, { 'content': 'Behind the scenes at our office', 'platforms': 'instagram-789012', 'scheduled_time': '2026-03-02T11:00:00Z', 'media_url': 'https://example.com/office-photo.jpg' } ] with open(output_file, 'w', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=['content', 'platforms', 'scheduled_time', 'media_url']) writer.writeheader() writer.writerows(sample_rows) print(f"Template created: {output_file}") # generate_csv_template() ``` -------------------------------- ### Get Specific LinkedIn Engagement Metrics Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/linkedin-analytics.md Example for fetching only engagement-related metrics (reactions, comments, shares) for a LinkedIn post. Returns a metrics object containing the requested data. ```javascript async function getEngagementMetrics(postedId, platformId) { try { const analytics = await getLinkedInAnalytics( postedId, platformId, ['REACTION', 'COMMENT', 'RESHARE'] ); return analytics.metrics; } catch (error) { console.error('Failed to get engagement:', error.message); throw error; } } ``` -------------------------------- ### Initialize Go Module Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/go/quick-start.md Initialize your Go project with a module for dependency management. ```bash go mod init your-project ``` -------------------------------- ### Get LinkedIn Posts Python Example Source: https://github.com/publora/publora-api-docs/blob/main/docs/endpoints/linkedin-feed-retrieval.md Python script using the requests library to retrieve LinkedIn posts. It demonstrates how to send the POST request and process the JSON response. ```python import requests response = requests.post( "https://api.publora.com/api/v1/linkedin-posts", headers={"x-publora-key": "sk_YOUR_API_KEY"}, json={ "platformId": "linkedin-ABC123", "count": 20, "sortBy": "LAST_MODIFIED" } ) data = response.json() for post in data["posts"]: print(f"Post: {post['commentary'][:50]}...") print(f"Published: {post['publishedAt']}") print("---") ``` -------------------------------- ### Basic MCP Python Client Example Source: https://github.com/publora/publora-api-docs/blob/main/docs/mcp/client-setup.md A basic Python script demonstrating how to connect to the Publora MCP server, initialize the client session, list available tools, and call a tool. Requires an active internet connection and valid API key. ```python import asyncio from mcp import ClientSession from mcp.client.streamable_http import streamablehttp_client async def main(): headers = {"Authorization": "Bearer sk_YOUR_API_KEY"} async with streamablehttp_client("https://mcp.publora.com", headers=headers) as (read, write, _): async with ClientSession(read, write) as session: await session.initialize() # List available tools tools = await session.list_tools() print(f"Available tools: {len(tools.tools)}") for tool in tools.tools: print(f" - {tool.name}: {tool.description}") # Get connections result = await session.call_tool("list_connections", {{}}) print(result.content[0].text) asyncio.run(main()) ``` -------------------------------- ### HTTParty Quick Start Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/ruby/quick-start.md Use this snippet to make direct API calls for creating posts and retrieving connections using the HTTParty gem. Ensure the 'httparty' gem is installed. ```ruby require 'httparty' class PubloraAPI include HTTParty base_uri 'https://api.publora.com/api/v1' def initialize(api_key) @api_key = api_key end def get_connections response = self.class.get('/platform-connections', headers: auth_headers) handle_response(response)['connections'] end def create_post(content:, platforms:, scheduled_time: nil) body = { content: content, platforms: platforms } body[:scheduledTime] = scheduled_time if scheduled_time response = self.class.post('/create-post', headers: auth_headers.merge('Content-Type' => 'application/json'), body: body.to_json ) handle_response(response) end private def auth_headers { 'x-publora-key' => @api_key } end def handle_response(response) raise "API Error (#{response.code}): #{response['error'] || response['message']}" unless response.success? response.parsed_response end end # Usage api = PubloraAPI.new(ENV['PUBLORA_API_KEY']) connections = api.get_connections puts "Connections: #{connections.length}" post = api.create_post( content: 'Hello from HTTParty!', platforms: ['twitter-123456789'] ) puts "Created: #{post['postGroupId']}" ``` -------------------------------- ### Create a Single Post Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/go/quick-start.md This example demonstrates how to create a single post to one or more platforms. You can specify content, target platforms, and a scheduled time. ```go package main import ( "fmt" "log" "os" "time" "your-project/publora" ) func main() { client := publora.NewClient(os.Getenv("PUBLORA_API_KEY")) // Schedule for 1 hour from now scheduledTime := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) resp, err := client.CreatePost(&publora.CreatePostRequest{ Content: "Hello from Go! Building with Publora API.", Platforms: []string{"twitter-123456789", "linkedin-ABC123DEF"}, ScheduledTime: scheduledTime, }) if err != nil { log.Fatalf("Failed to create post: %v", err) } fmt.Printf("Post created: %s\n", resp.PostGroupID) for _, post := range resp.Posts { fmt.Printf(" - %s: %s\n", post.Platform, post.Status) } } ``` -------------------------------- ### Initialize Publora API Client Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/ruby/quick-start.md Instantiate the PubloraClient with your API key. Ensure the PUBLORA_API_KEY environment variable is set. ```ruby require_relative 'publora_client' client = PubloraClient.new(ENV['PUBLORA_API_KEY']) ``` -------------------------------- ### Upload Video using cURL Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/media-uploads.md This example shows how to upload a video file using cURL commands. It involves getting an upload URL, uploading the video data, and then scheduling the post. ```bash UPLOAD_RESPONSE=$(curl -s -X POST https://api.publora.com/api/v1/get-upload-url \ -H "Content-Type: application/json" \ -H "x-publora-key: $API_KEY" \ -d "{ \"fileName\": \"promo-video.mp4\", \"contentType\": \"video/mp4\", \"type\": \"video\", \"postGroupId\": \"$POST_GROUP_ID\" }") UPLOAD_URL=$(echo "$UPLOAD_RESPONSE" | jq -r '.uploadUrl') # Step 3: Upload video to S3 curl -X PUT "$UPLOAD_URL" \ -H "Content-Type: video/mp4" \ --data-binary @./promo-video.mp4 # Step 4: Schedule the post curl -X PUT "https://api.publora.com/api/v1/update-post/$POST_GROUP_ID" \ -H "Content-Type: application/json" \ -H "x-publora-key: $API_KEY" \ -d '{ "status": "scheduled", "scheduledTime": "2026-03-15T16:00:00.000Z" }' ``` -------------------------------- ### Get Analytics for a Post Created via Publora Source: https://github.com/publora/publora-api-docs/blob/main/docs/guides/linkedin-analytics.md This example shows how to first retrieve the `postedId` for a post created through Publora, and then use it to fetch its LinkedIn analytics. It requires the `postGroupId` and `platformId`. ```javascript async function getAnalyticsForPost(postGroupId, platformId) { // Step 1: Get the postedId from the post const postResponse = await fetch(`${BASE_URL}/get-post/${postGroupId}`, { headers: { 'x-publora-key': PUBLORA_API_KEY } }); const postData = await postResponse.json(); const linkedInPost = postData.posts.find(p => p.platform === 'linkedin'); if (!linkedInPost || !linkedInPost.postedId) { throw new Error('LinkedIn post not found or not yet published'); } // Step 2: Get analytics return await getLinkedInAnalytics(linkedInPost.postedId, platformId, 'ALL'); } ``` -------------------------------- ### Faraday Gem Integration Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/ruby/quick-start.md This example shows how to use the Faraday gem to interact with the Publora API. It sets up a connection with JSON request and response middleware. Ensure the 'faraday' gem is installed. ```ruby # Gemfile # gem 'faraday' require 'faraday' require 'json' class PubloraClient BASE_URL = 'https://api.publora.com/api/v1' def initialize(api_key) @conn = Faraday.new(url: BASE_URL) do |f| f.request :json f.response :json f.adapter Faraday.default_adapter f.headers['x-publora-key'] = api_key end end def get_connections response = @conn.get('platform-connections') handle_response(response)['connections'] end def create_post(content:, platforms:, scheduled_time: nil) body = { content: content, platforms: platforms } body[:scheduledTime] = scheduled_time if scheduled_time response = @conn.post('create-post', body) handle_response(response) end def get_post(post_group_id) response = @conn.get("get-post/#{post_group_id}") handle_response(response) end private def handle_response(response) unless response.success? error = response.body['error'] || response.body['message'] || 'Unknown error' raise "API Error (#{response.status}): #{error}" end response.body end end # Usage client = PubloraClient.new(ENV['PUBLORA_API_KEY']) connections = client.get_connections puts "Found #{connections.length} connections" post = client.create_post( content: 'Hello from Faraday!', platforms: ['twitter-123456789', 'linkedin-ABC123DEF'] ) puts "Created post: #{post['postGroupId']}" ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/frameworks/nextjs.md Set up your Publora API key in the .env.local file for secure access. ```bash # .env.local PUBLORA_API_KEY=sk_your_api_key_here ``` -------------------------------- ### Rails Integration Example Source: https://github.com/publora/publora-api-docs/blob/main/docs/examples/ruby/quick-start.md This snippet demonstrates how to integrate the Publora API client into a Rails application. It shows setup in an initializer and usage within a controller and service object. Ensure the PubloraClient class is accessible. ```ruby # config/initializers/publora.rb require_relative '../../lib/publora_client' PUBLORA_CLIENT = PubloraClient.new(Rails.application.credentials.publora_api_key) # app/services/social_posting_service.rb class SocialPostingService def self.schedule_post(content:, platforms:, scheduled_time:) PUBLORA_CLIENT.create_post( content: content, platforms: platforms, scheduled_time: scheduled_time.iso8601 ) end def self.get_connections PUBLORA_CLIENT.get_connections end end # app/controllers/posts_controller.rb class PostsController < ApplicationController def create result = SocialPostingService.schedule_post( content: params[:content], platforms: params[:platforms], scheduled_time: Time.parse(params[:scheduled_time]) ) render json: { success: true, post_group_id: result['postGroupId'] } rescue PubloraError => e render json: { success: false, error: e.message }, status: :unprocessable_entity end end ```