API Integrations

Connect PromptCompose to your applications with API keys and SDK integration

API Integrations

PromptCompose integrations allow you to connect the platform with your applications, services, and workflows. This guide covers API key management, SDK setup, webhook configuration, and third-party integrations.

Getting Started with Integrations

Why Integrate?

Integrating PromptCompose into your applications enables:

  • Dynamic Content: Serve personalized prompts based on user context
  • A/B Testing: Run experiments and measure performance automatically
  • Version Control: Deploy prompt updates without code changes
  • Analytics: Track prompt performance and user interactions
  • Team Collaboration: Manage prompts through a collaborative interface

Integration Options

Direct API: Make HTTP requests to PromptCompose API endpoints SDK Integration: Use our JavaScript/TypeScript SDK for easier integration Webhook Events: Receive real-time notifications about changes Third-Party Tools: Connect with analytics, communication, and development tools

API Key Management

Creating API Keys

  1. Navigate to Integrations

    • Click “Integrations” in the sidebar
    • Click “Create API Key”
  2. Configure Your Key

    • Name: Descriptive name (e.g., “Production Website”)
    • Description: What this key will be used for
    • Environment: Development, Staging, or Production
    • Permissions: Read-only or Full access
  3. Security Settings

    • IP Restrictions: Limit usage to specific IP addresses
    • Domain Restrictions: Restrict to specific domains
    • Rate Limits: Set custom rate limits for this key
    • Expiration: Optional automatic expiration date
  4. Copy Your Key ⚠️ Important: Copy the API key immediately - you won’t see it again!

API Key Types

Production Keys

For live applications serving real users:

  • Full access to prompts and analytics
  • Higher rate limits
  • Production-grade SLA
  • Enhanced monitoring and alerting

Development Keys

For testing and development:

  • Access to development/staging prompts
  • Standard rate limits
  • Testing-friendly features
  • Debugging and logging capabilities

Read-Only Keys

For analytics and monitoring:

  • View prompts and performance data
  • Cannot modify prompts or settings
  • Suitable for reporting dashboards
  • Enhanced security for display applications

Key Security Best Practices

Storage and Handling

  • Store keys in environment variables, not in code
  • Use different keys for different environments
  • Rotate keys regularly (every 90 days recommended)
  • Never commit keys to version control

Access Control

  • Use IP restrictions when possible
  • Set domain restrictions for web applications
  • Configure appropriate rate limits
  • Set expiration dates for temporary integrations

Monitoring

  • Monitor key usage patterns
  • Set up alerts for unusual activity
  • Track error rates and response times
  • Review access logs regularly

SDK Integration

JavaScript/TypeScript SDK

Installation

npm install @promptcompose/sdk

Quick Setup

import { PromptCompose } from '@promptcompose/sdk';

const promptCompose = new PromptCompose(
  'your-api-key',
  'your-project-id',
  { debug: process.env.NODE_ENV === 'development' }
);

// Initialize connection
await promptCompose.init();

Basic Usage

// Resolve a prompt with variables
const result = await promptCompose.resolvePrompt('welcome-email', {
  config: {
    abTesting: { sessionId: `user-${userId}` }
  }
}, {
  customerName: 'John Doe',
  companyName: 'Acme Corp'
});

console.log(result.content); // Rendered prompt

Framework Integration Examples

React Application

// hooks/usePrompts.js
import { useState, useEffect } from 'react';
import { PromptCompose } from '@promptcompose/sdk';

export function usePromptCompose() {
  const [sdk, setSdk] = useState(null);
  const [isReady, setIsReady] = useState(false);

  useEffect(() => {
    const initSDK = async () => {
      const promptCompose = new PromptCompose(
        process.env.REACT_APP_PROMPT_COMPOSE_API_KEY,
        process.env.REACT_APP_PROMPT_COMPOSE_PROJECT_ID
      );
      
      await promptCompose.init();
      setSdk(promptCompose);
      setIsReady(true);
    };

    initSDK();
  }, []);

  return { sdk, isReady };
}

// Component usage
function WelcomeMessage({ userId, userName }) {
  const { sdk, isReady } = usePromptCompose();
  const [message, setMessage] = useState('');

  useEffect(() => {
    if (isReady && sdk) {
      const fetchMessage = async () => {
        const result = await sdk.resolvePrompt('welcome-prompt', {
          config: { abTesting: { sessionId: userId } }
        }, { userName });
        
        setMessage(result.content);
      };

      fetchMessage();
    }
  }, [isReady, sdk, userId, userName]);

  return <div>{message}</div>;
}

Node.js/Express API

// server.js
const express = require('express');
const { PromptCompose } = require('@promptcompose/sdk');

const app = express();
const promptCompose = new PromptCompose(
  process.env.PROMPT_COMPOSE_API_KEY,
  process.env.PROMPT_COMPOSE_PROJECT_ID
);

// Initialize SDK on server start
promptCompose.init().then(() => {
  console.log('PromptCompose SDK initialized');
});

// API endpoint
app.post('/api/prompts/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { variables, config, sessionId } = req.body;
    
    const result = await promptCompose.resolvePrompt(id, {
      config: {
        abTesting: { sessionId }
      }
    }, variables);
    
    res.json({
      content: result.content,
      variant: result.variant?.name,
      test: result.abTest?.name
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000);

Next.js API Route

// pages/api/prompts/[id].js
import { PromptCompose } from '@promptcompose/sdk';

const promptCompose = new PromptCompose(
  process.env.PROMPT_COMPOSE_API_KEY,
  process.env.PROMPT_COMPOSE_PROJECT_ID
);

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { id } = req.query;
    const { variables, sessionId } = req.body;
    
    const result = await promptCompose.resolvePrompt(id, {
      config: { abTesting: { sessionId } }
    }, variables);
    
    res.status(200).json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}

Webhook Configuration

Setting Up Webhooks

  1. Create Webhook Endpoint Create an endpoint in your application to receive webhook events:

    app.post('/webhooks/promptcompose', express.raw({type: 'application/json'}), (req, res) => {
      const event = JSON.parse(req.body);
      
      // Verify webhook signature
      const signature = req.headers['x-promptcompose-signature'];
      const isValid = verifyWebhookSignature(req.body, signature);
      
      if (!isValid) {
        return res.status(400).send('Invalid signature');
      }
      
      // Process the event
      handleWebhookEvent(event);
      
      res.status(200).send('OK');
    });
    
  2. Configure in PromptCompose

    • Go to Integrations → Webhooks
    • Click “Add Webhook”
    • Enter your endpoint URL
    • Select events to receive
    • Add webhook secret for security

Available Webhook Events

Prompt Events

  • prompt.deployed: New prompt version deployed
  • prompt.updated: Prompt metadata changed
  • prompt.deleted: Prompt removed
  • prompt.version.created: New version created
  • prompt.version.rollback: Version rolled back

A/B Test Events

  • ab_test.started: Test begins running
  • ab_test.stopped: Test stopped or completed
  • ab_test.variant.winning: Clear winner detected
  • ab_test.result.reported: Conversion event reported

Team Events

  • team.member.added: New team member invited
  • team.member.removed: Team member removed
  • team.role.changed: Member role updated
  • team.permission.updated: Permission changes

Webhook Security

Signature Verification

const crypto = require('crypto');

function verifyWebhookSignature(payload, signature) {
  const webhookSecret = process.env.PROMPTCOMPOSE_WEBHOOK_SECRET;
  const expectedSignature = crypto
    .createHmac('sha256', webhookSecret)
    .update(payload)
    .digest('hex');
    
  return signature === `sha256=${expectedSignature}`;
}

Best Practices

  • Always verify webhook signatures
  • Use HTTPS endpoints only
  • Implement idempotency for event processing
  • Set up proper error handling and retries
  • Log webhook events for debugging

Third-Party Integrations

Analytics Platforms

Google Analytics

Track prompt usage and A/B test performance:

// Track prompt resolution
gtag('event', 'prompt_resolved', {
  'prompt_id': promptId,
  'variant': result.variant?.name,
  'test': result.abTest?.name,
  'user_id': userId
});

// Track conversions
gtag('event', 'conversion', {
  'test_id': testId,
  'variant_id': variantId,
  'value': conversionValue
});

Mixpanel Integration

// Track prompt events
mixpanel.track('Prompt Resolved', {
  prompt_id: promptId,
  variant_name: result.variant?.name,
  test_name: result.abTest?.name,
  user_id: userId,
  timestamp: new Date()
});

// Track A/B test conversions
mixpanel.track('A/B Test Conversion', {
  test_id: testId,
  variant_id: variantId,
  status: 'success',
  user_id: userId
});

Communication Tools

Slack Integration

Get notifications about prompt deployments and A/B test results:

  1. Create Slack App

    • Go to api.slack.com
    • Create new app for your workspace
    • Get webhook URL for your channel
  2. Configure Webhook

    • Add Slack webhook URL to PromptCompose
    • Select events to receive
    • Customize message format
  3. Example Notification

    🚀 Prompt Deployed: "Welcome Email v2.1"
    📊 A/B Test Complete: "Subject Line Test" - Variant B won with 23% higher open rate
    👥 New Team Member: Alice joined the Marketing project
    

Microsoft Teams Integration

Similar setup to Slack with Teams webhook URLs and custom card formatting.

Development Tools

GitHub Integration

Connect with your development workflow:

  • Trigger deployments from pull requests
  • Sync prompt versions with code releases
  • Create GitHub issues for A/B test results

CI/CD Integration

Include prompt management in your deployment pipeline:

# GitHub Actions example
- name: Deploy Prompts
  run: |
    curl -X POST "https://api.promptcompose.io/api/v1/prompts/deploy" \
      -H "Authorization: Bearer ${{ secrets.PROMPT_COMPOSE_API_KEY }}" \
      -H "Content-Type: application/json" \
      -d '{"version": "${{ github.sha }}", "environment": "production"}'

Monitoring and Analytics

API Usage Monitoring

Key Metrics to Track

  • Request Volume: Total API calls over time
  • Response Times: Average and 95th percentile latency
  • Error Rates: 4xx and 5xx error frequencies
  • Rate Limit Usage: How close you are to limits

Setting Up Monitoring

// Custom monitoring middleware
const monitoringMiddleware = (req, res, next) => {
  const start = Date.now();
  
  res.on('finish', () => {
    const duration = Date.now() - start;
    const statusCode = res.statusCode;
    
    // Send metrics to your monitoring system
    metrics.increment('promptcompose.api.requests', 1, {
      method: req.method,
      status: statusCode,
      endpoint: req.path
    });
    
    metrics.timing('promptcompose.api.duration', duration);
  });
  
  next();
};

Performance Optimization

Caching Strategies

const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 300 }); // 5 minute cache

async function getCachedPrompt(promptId, variables) {
  const cacheKey = `${promptId}-${JSON.stringify(variables)}`;
  
  let result = cache.get(cacheKey);
  if (result) {
    return result;
  }
  
  result = await promptCompose.resolvePrompt(promptId, undefined, variables);
  cache.set(cacheKey, result);
  
  return result;
}

Connection Pooling

// Reuse SDK instance across requests
const globalPromptCompose = new PromptCompose(apiKey, projectId);
globalPromptCompose.init();

// Use the global instance in request handlers
app.post('/api/prompts', async (req, res) => {
  const result = await globalPromptCompose.resolvePrompt(/* ... */);
  res.json(result);
});

Troubleshooting Integrations

Common Issues

Authentication Errors

401 Unauthorized: Invalid API key
403 Forbidden: Insufficient permissions
  • Verify API key is correct and active
  • Check key permissions and restrictions
  • Ensure key hasn’t expired

Rate Limiting

429 Too Many Requests: Rate limit exceeded
  • Check your current rate limits
  • Implement exponential backoff retry logic
  • Consider upgrading your plan for higher limits

Network Issues

ECONNRESET: Connection reset by peer
ETIMEDOUT: Request timeout
  • Check network connectivity
  • Verify firewall and proxy settings
  • Implement proper timeout and retry logic

Variable Validation

400 Bad Request: Missing required variable 'customerName'
  • Review prompt variable requirements
  • Validate input data before API calls
  • Provide default values for optional variables

Debugging Tips

Enable Debug Logging

const promptCompose = new PromptCompose(apiKey, projectId, {
  debug: true // Enables detailed logging
});

Request/Response Logging

// Log all API interactions
promptCompose.on('request', (req) => {
  console.log('API Request:', req);
});

promptCompose.on('response', (res) => {
  console.log('API Response:', res);
});

Health Check Endpoint

app.get('/health/promptcompose', async (req, res) => {
  try {
    await promptCompose.init();
    res.status(200).json({ status: 'healthy' });
  } catch (error) {
    res.status(500).json({ 
      status: 'unhealthy', 
      error: error.message 
    });
  }
});

Best Practices

Security

  1. Environment Variables: Store API keys securely
  2. Key Rotation: Rotate keys regularly
  3. Least Privilege: Use read-only keys when possible
  4. Network Security: Use IP and domain restrictions
  5. HTTPS Only: Never send keys over unencrypted connections

Performance

  1. Caching: Cache responses when appropriate
  2. Connection Reuse: Share SDK instances
  3. Batch Operations: Combine multiple requests when possible
  4. Monitoring: Track performance metrics
  5. Error Handling: Implement proper retry logic

Development Workflow

  1. Environment Separation: Use different keys for dev/staging/prod
  2. Version Control: Never commit API keys
  3. Testing: Mock API responses in tests
  4. Documentation: Document your integration patterns
  5. Monitoring: Set up alerts for integration health

Getting Help

For integration support:

Next Steps

With integrations configured:

Proper integration setup enables powerful, scalable prompt management that grows with your application needs.