CompactSaaS External API - Getting Started Guide

Welcome to the CompactSaaS External API! This guide will help you get up and running in minutes.

Overview

The CompactSaaS External API allows you to integrate analytics tracking and other services into your applications. All API calls are billed on a pay-as-you-go basis via Stripe.

Base URLs:

  • Production: https://api.compactsaas.com/v1
  • Staging: https://api.compactsaasstaging.click/v1

Interactive Documentation

Try out the API directly in your browser using our Interactive API Documentation (Swagger UI).

The interactive docs allow you to:

  • Browse all available endpoints
  • View request/response schemas and examples
  • Execute API calls with your API key using "Try it out"
  • See real responses from the API

Step 1: Getting Your API Key

Create an API Key

  1. Log in to your CompactSaaS Dashboard
  2. Navigate to Team SettingsAPI Keys
  3. Click Create API Key
  4. Enter a descriptive name (e.g., "Production App" or "Development")
  5. Click Create

Save Your Key Securely

Important: Your API key is shown only once. Copy and save it immediately in a secure location (e.g., environment variables, secrets manager).

API keys follow this format:

  • Production: pk_live_<32 random characters>
  • Staging/Test: pk_test_<32 random characters>

Example: pk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6

Key Management Tips

  • You can create up to 2 API keys per team (for key rotation)
  • To rotate keys: Create a new key → Update your apps → Revoke the old key
  • Revoked keys are immediately disabled

Step 2: Making Your First API Call

Let's track a simple page view event:

cURL

curl -X POST https://api.compactsaas.com/v1/track \
  -H "x-api-key: pk_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "event": "page_view",
    "properties": {
      "page": "/home",
      "referrer": "https://google.com"
    }
  }'

Expected Response

{
  "success": true
}

The API returns 202 Accepted to indicate the event was received and queued for processing.


Step 3: SDK Examples

JavaScript / Node.js

// Using fetch (Node.js 18+ or browser)
async function trackEvent(apiKey, event, properties = {}) {
  const response = await fetch('https://api.compactsaas.com/v1/track', {
    method: 'POST',
    headers: {
      'x-api-key': apiKey,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ event, properties }),
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`API error ${response.status}: ${error.message}`);
  }

  return response.json();
}

// Usage
const API_KEY = process.env.COMPACTSAAS_API_KEY;

await trackEvent(API_KEY, 'page_view', { page: '/pricing' });
await trackEvent(API_KEY, 'button_click', { button: 'signup_cta' });
await trackEvent(API_KEY, 'purchase_completed', {
  product_id: 'prod_123',
  amount: 99.99,
  currency: 'USD'
});

JavaScript / Node.js (with axios)

const axios = require('axios');

const compactSaasClient = axios.create({
  baseURL: 'https://api.compactsaas.com/v1',
  headers: {
    'x-api-key': process.env.COMPACTSAAS_API_KEY,
    'Content-Type': 'application/json',
  },
});

async function trackEvent(event, properties = {}) {
  try {
    const response = await compactSaasClient.post('/track', {
      event,
      properties,
    });
    return response.data;
  } catch (error) {
    if (error.response) {
      console.error(`API error: ${error.response.status} - ${error.response.data.message}`);
    }
    throw error;
  }
}

// Usage
await trackEvent('page_view', { page: '/home' });

Python

import os
import requests
from typing import Optional

API_KEY = os.environ.get('COMPACTSAAS_API_KEY')
BASE_URL = 'https://api.compactsaas.com/v1'

def track_event(event: str, properties: Optional[dict] = None, timestamp: Optional[str] = None):
    """
    Track an analytics event.

    Args:
        event: Name of the event (e.g., 'page_view', 'button_click')
        properties: Optional dict of event properties
        timestamp: Optional ISO 8601 timestamp (defaults to server time)

    Returns:
        dict: API response

    Raises:
        requests.HTTPError: If the API returns an error
    """
    payload = {
        'event': event,
        'properties': properties or {},
    }

    if timestamp:
        payload['timestamp'] = timestamp

    response = requests.post(
        f'{BASE_URL}/track',
        headers={
            'x-api-key': API_KEY,
            'Content-Type': 'application/json',
        },
        json=payload,
    )

    response.raise_for_status()
    return response.json()

# Usage examples
if __name__ == '__main__':
    # Track a page view
    track_event('page_view', {'page': '/pricing', 'referrer': 'https://google.com'})

    # Track a button click
    track_event('button_click', {'button_id': 'signup_cta', 'button_text': 'Get Started'})

    # Track with a specific timestamp
    track_event('purchase_completed',
                {'product_id': 'prod_123', 'amount': 99.99},
                timestamp='2024-01-15T10:30:00Z')

Python (with error handling)

import requests
from requests.exceptions import HTTPError

def track_event_safe(event: str, properties: dict = None):
    """Track event with comprehensive error handling."""
    try:
        response = requests.post(
            'https://api.compactsaas.com/v1/track',
            headers={
                'x-api-key': API_KEY,
                'Content-Type': 'application/json',
            },
            json={'event': event, 'properties': properties or {}},
            timeout=10,
        )
        response.raise_for_status()
        return {'success': True, 'data': response.json()}

    except HTTPError as e:
        status = e.response.status_code
        error_data = e.response.json() if e.response.content else {}

        if status == 401:
            return {'success': False, 'error': 'Invalid or revoked API key'}
        elif status == 403:
            return {'success': False, 'error': 'Account disabled - contact support'}
        elif status == 429:
            retry_after = e.response.headers.get('Retry-After', 60)
            return {'success': False, 'error': f'Rate limited - retry after {retry_after}s'}
        elif status == 400:
            return {'success': False, 'error': f'Invalid request: {error_data.get("message")}'}
        else:
            return {'success': False, 'error': f'API error: {status}'}

    except requests.Timeout:
        return {'success': False, 'error': 'Request timed out'}
    except requests.RequestException as e:
        return {'success': False, 'error': f'Network error: {str(e)}'}

cURL Examples

Track a page view:

curl -X POST https://api.compactsaas.com/v1/track \
  -H "x-api-key: $COMPACTSAAS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"event": "page_view", "properties": {"page": "/home"}}'

Track a custom event with timestamp:

curl -X POST https://api.compactsaas.com/v1/track \
  -H "x-api-key: $COMPACTSAAS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "event": "purchase_completed",
    "properties": {
      "product_id": "prod_123",
      "amount": 99.99,
      "currency": "USD"
    },
    "timestamp": "2024-01-15T10:30:00Z"
  }'

Check API health (no authentication required):

curl https://api.compactsaas.com/v1/health

Step 4: Error Handling

The API uses standard HTTP status codes. Here's how to handle common errors:

Status CodeErrorDescriptionAction
400Bad RequestInvalid request body (missing event name, invalid JSON, etc.)Check your request payload
401UnauthorizedInvalid, missing, or revoked API keyVerify your API key is correct and active
403ForbiddenAccount is disabled or suspendedContact support or check billing status
429Too Many RequestsRate limit exceeded (100 req/s)Wait and retry (check Retry-After header)
500Internal ErrorServer errorRetry with exponential backoff

Error Response Format

{
  "error": "Validation error",
  "message": "Event name is required",
  "code": "VALIDATION_ERROR"
}

Handling Rate Limits

When you receive a 429 response, the Retry-After header indicates how many seconds to wait:

async function trackWithRetry(event, properties, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    const response = await fetch('https://api.compactsaas.com/v1/track', {
      method: 'POST',
      headers: {
        'x-api-key': API_KEY,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ event, properties }),
    });

    if (response.status === 429) {
      const retryAfter = parseInt(response.headers.get('Retry-After') || '60', 10);
      console.log(`Rate limited. Retrying in ${retryAfter} seconds...`);
      await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
      continue;
    }

    if (!response.ok) {
      throw new Error(`API error: ${response.status}`);
    }

    return response.json();
  }
  throw new Error('Max retries exceeded');
}

Step 5: Billing

Pay-As-You-Go Pricing

CompactSaaS uses a simple pay-as-you-go billing model:

  • No monthly quotas - Use as much as you need
  • No tiers - Same rate for all customers
  • Transparent pricing - See current rates in your dashboard

Viewing Your Usage

  1. Log in to your CompactSaaS Dashboard
  2. Navigate to BillingUsage
  3. View your current billing period usage and estimated cost

How Billing Works

  1. Each API call is counted and tracked in real-time
  2. Usage is aggregated hourly and reported to Stripe
  3. All API calls appear on your monthly Stripe invoice
  4. View detailed usage breakdown in your dashboard

Rate Limits (DDoS Protection)

Rate limits are for infrastructure protection, not billing:

  • 100 requests per second (burst up to 200)
  • No monthly request limits
  • All requests within rate limits are billable

Next Steps

Need Help?

  • Dashboard: View usage, manage keys, and access support
  • Email: support@compactsaas.com
  • Status Page: Check API status and incidents

Quick Reference

Authentication Header

x-api-key: pk_live_your_key_here

Track Event Endpoint

POST /v1/track
Content-Type: application/json

{
  "event": "event_name",
  "properties": { ... },
  "timestamp": "2024-01-15T10:30:00Z"  // optional
}

Health Check Endpoint

GET /v1/health

No authentication required. Returns:

{
  "status": "ok",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "version": "v1"
}
Need the interactive API? Open the API Explorer.
Web analytics, short links, QR codes, bio pages, and wallet passes. Built in Sydney, Australia.
© Copyright 2026 CompactSaaS. All Rights Reserved.