> ## Documentation Index
> Fetch the complete documentation index at: https://docs.userboo.st/llms.txt
> Use this file to discover all available pages before exploring further.

# REST API Examples

> Direct HTTP API integration examples using cURL for any language or framework

## Overview

The UserBoost REST API allows you to track events from any language or framework that can make HTTP requests. Use these cURL examples as a reference for implementing in your preferred language.

## Authentication

All API requests require authentication using your server-side API key:

```bash theme={null}
Authorization: Bearer ub_live_your_api_key_here
```

## Basic Event Tracking

### Single Event (Primary Endpoint)

Track events using the **`/v1/event`** endpoint - the recommended approach for most applications:

#### Minimal Payload (Required Fields Only)

```bash theme={null}
curl -X POST https://api.userboo.st/v1/event \
  -H "Authorization: Bearer ub_live_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "event": "user_signed_up",
    "user": {
      "id": "user_123"
    }
  }'
```

#### 📋 Full Payload (With Optional Fields)

```bash theme={null}
curl -X POST https://api.userboo.st/v1/event \
  -H "Authorization: Bearer ub_live_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "event": "user_signed_up",
    "user": {
      "id": "user_123",
      "email": "john@example.com",
      "traits": {
        "plan": "free"
      }
    },
    "timestamp": "2025-01-15T10:00:00Z",
    "properties": {
      "source": "website"
    }
  }'
```

#### 📋 Field Requirements

| Field          | Required     | Type     | Description                           |
| -------------- | ------------ | -------- | ------------------------------------- |
| ✅ `event`      | **REQUIRED** | `string` | Event name (e.g., "user\_signed\_up") |
| ✅ `user`       | **REQUIRED** | `object` | User object with required id field    |
| ❌ `timestamp`  | *Optional*   | `string` | ISO 8601 timestamp (defaults to now)  |
| ❌ `properties` | *Optional*   | `object` | Event-specific data                   |

### 🎨 User Object Format

The `user` field requires an **object with an id field**:

<Note>
  **Important:** User data must be provided as an object. String format like
  `"user": "user_123"` is no longer supported and will result in validation
  errors.
</Note>

<Tabs>
  <Tab title="Minimal User Object">
    ```bash theme={null}
    curl -X POST https://api.userboo.st/v1/event \
      -H "Authorization: Bearer ub_live_your_api_key_here" \
      -H "Content-Type: application/json" \
      -d '{
        "event": "button_clicked",
        "user": {
          "id": "user_123"
        },
        "properties": {
          "button": "signup_cta",
          "page": "homepage"
        }
      }'
    ```

    ✅ **Best for**: Quick event tracking with existing user IDs
  </Tab>

  <Tab title="📋 User Object with Traits (Rich Data)">
    ```bash theme={null}
    curl -X POST https://api.userboo.st/v1/event \
      -H "Authorization: Bearer ub_live_your_api_key_here" \
      -H "Content-Type: application/json" \
      -d '{
        "event": "purchase_completed",
        "user": {
          "id": "user_123",
          "email": "john@example.com",
          "traits": {
            "plan": "premium",
            "company": "Acme Corp"
          }
        },
        "properties": {
          "amount": 99.00,
          "product": "pro_plan"
        }
      }'
    ```

    ✅ **Best for**: Enriching user profiles with demographic data
  </Tab>
</Tabs>

#### 📋 User Object Structure

| Field      | Required     | Type     | Description                           |
| ---------- | ------------ | -------- | ------------------------------------- |
| ✅ `id`     | **REQUIRED** | `string` | Unique user identifier                |
| ❌ `email`  | *Optional*   | `string` | User email address                    |
| ❌ `traits` | *Optional*   | `object` | User attributes (plan, company, etc.) |

***

### 📦 Batch Events (Advanced Use Case)

For **high-volume applications only** - send multiple events using `/v1/events`:

```bash theme={null}
curl -X POST https://api.userboo.st/v1/events \
  -H "Authorization: Bearer ub_live_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "sent_at": "2025-01-15T10:00:00Z",
    "events": [
      {
        "type": "event",
        "name": "user_registered",
        "user": {
          "id": "user_123",
          "email": "john@example.com"
        },
        "timestamp": "2025-01-15T10:00:00Z"
      },
      {
        "type": "event",
        "name": "profile_completed",
        "user": {
          "id": "user_123"
        },
        "timestamp": "2025-01-15T10:05:00Z",
        "properties": {
          "completion_rate": 100
        }
      }
    ]
  }'
```

#### 📋 Batch Fields Requirements

| Field                   | Required     | Type     | Description                        |
| ----------------------- | ------------ | -------- | ---------------------------------- |
| ✅ `sent_at`             | **REQUIRED** | `string` | Batch timestamp (ISO 8601)         |
| ✅ `events`              | **REQUIRED** | `array`  | Array of event objects             |
| ✅ `events[].type`       | **REQUIRED** | `string` | Must be "event"                    |
| ✅ `events[].name`       | **REQUIRED** | `string` | Event name                         |
| ✅ `events[].user`       | **REQUIRED** | `object` | User object with required id field |
| ❌ `events[].timestamp`  | *Optional*   | `string` | Event timestamp                    |
| ❌ `events[].properties` | *Optional*   | `object` | Event data                         |

<Warning>
  **👉 Use `/v1/event` for most applications** - batch endpoint is only needed
  for 100+ events per minute
</Warning>

## User Identification

Update user profile information:

```bash theme={null}
curl -X POST https://api.userboo.st/v1/events \
  -H "Authorization: Bearer ub_live_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "sent_at": "2025-01-15T10:00:00Z",
    "events": [{
      "type": "identify",
      "user": {
        "id": "user_123",
        "email": "john@example.com",
        "traits": {
          "name": "John Doe",
          "plan": "premium",
          "created_at": "2025-01-01T00:00:00Z"
        }
      },
      "timestamp": "2025-01-15T10:00:00Z"
    }]
  }'
```

## Language Examples

### Python (requests)

Simplified single event tracking:

```python theme={null}
import requests
import json
from datetime import datetime

def track_event(event_name, user, properties=None):
    payload = {
        "name": event_name,
        "user": user,
        "timestamp": datetime.utcnow().isoformat() + "Z",
        "properties": properties or {}
    }

    response = requests.post(
        "https://api.userboo.st/v1/event",
        headers={
            "Authorization": "Bearer ub_live_your_api_key_here",
            "Content-Type": "application/json"
        },
        json=payload
    )

    return response.json()

# Usage with simple user ID
track_event("user_signed_up", "user_123", {
    "email": "john@example.com",
    "plan": "free"
})

# Usage with user object and traits
track_event("purchase_completed", {
    "id": "user_123",
    "email": "john@example.com",
    "traits": {
        "plan": "premium",
        "company": "Acme Corp"
    }
}, {
    "amount": 99.00,
    "product": "pro_plan"
})
```

### Go

Simplified single event tracking:

```go theme={null}
package main

import (
    "bytes"
    "encoding/json"
    "net/http"
    "time"
)

// User can be a string or an object
type User struct {
    ID     string                 `json:"id"`
    Email  string                 `json:"email,omitempty"`
    Traits map[string]interface{} `json:"traits,omitempty"`
}

type EventRequest struct {
    Name       string      `json:"name"`
    User       interface{} `json:"user"` // Can be string or User object
    Timestamp  string      `json:"timestamp"`
    Properties map[string]interface{} `json:"properties,omitempty"`
}

// Simple user ID version
func trackEvent(eventName, userID string, properties map[string]interface{}) error {
    payload := EventRequest{
        Name:       eventName,
        User:       userID, // Simple string
        Timestamp:  time.Now().UTC().Format(time.RFC3339),
        Properties: properties,
    }

    return sendEvent(payload)
}

// Rich user data version
func trackEventWithUser(eventName string, user User, properties map[string]interface{}) error {
    payload := EventRequest{
        Name:       eventName,
        User:       user, // User object with traits
        Timestamp:  time.Now().UTC().Format(time.RFC3339),
        Properties: properties,
    }

    return sendEvent(payload)
}

func sendEvent(payload EventRequest) error {
    jsonData, _ := json.Marshal(payload)

    req, _ := http.NewRequest("POST", "https://api.userboo.st/v1/event", bytes.NewBuffer(jsonData))
    req.Header.Set("Authorization", "Bearer ub_live_your_api_key_here")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    return nil
}

// Usage examples
func main() {
    // Simple user ID
    trackEvent("user_signed_up", "user_123", map[string]interface{}{
        "email": "john@example.com",
        "plan":  "free",
    })

    // Rich user data with traits
    trackEventWithUser("purchase_completed", User{
        ID:    "user_123",
        Email: "john@example.com",
        Traits: map[string]interface{}{
            "plan":    "premium",
            "company": "Acme Corp",
        },
    }, map[string]interface{}{
        "amount":  99.00,
        "product": "pro_plan",
    })
}
```

### PHP

Simplified single event tracking:

```php theme={null}
<?php

function trackEvent($eventName, $user, $properties = []) {
    $payload = [
        'name' => $eventName,
        'user' => $user,
        'timestamp' => date('c'),
        'properties' => $properties
    ];

    $options = [
        'http' => [
            'header' => [
                'Authorization: Bearer ub_live_your_api_key_here',
                'Content-Type: application/json'
            ],
            'method' => 'POST',
            'content' => json_encode($payload)
        ]
    ];

    $context = stream_context_create($options);
    $result = file_get_contents('https://api.userboo.st/v1/event', false, $context);

    return json_decode($result, true);
}

// Usage with simple user ID
trackEvent('user_signed_up', 'user_123', [
    'email' => 'john@example.com',
    'plan' => 'free'
]);

// Usage with user object and traits
trackEvent('purchase_completed', [
    'id' => 'user_123',
    'email' => 'john@example.com',
    'traits' => [
        'plan' => 'premium',
        'company' => 'Acme Corp'
    ]
], [
    'amount' => 99.00,
    'product' => 'pro_plan'
]);
?>
```

## 📈 Payload Reference

### Single Event Payload (`/v1/event` - Primary)

**Minimal required payload:**

```json theme={null}
{
  "name": "event_name",
  "user": "user_123"
}
```

<Tabs>
  <Tab title="Minimal Payload">
    ```json theme={null}
    {
      "name": "button_clicked",
      "user": "user_123"
    }
    ```

    **✅ Required fields only** - timestamp auto-generated
  </Tab>

  <Tab title="📋 Standard Payload">
    ```json theme={null}
    {
      "name": "purchase_completed",
      "user": "user_123",
      "properties": {
        "amount": 99.00,
        "product": "pro_plan"
      }
    }
    ```

    **✅ With event data** - most common usage
  </Tab>

  <Tab title="📋 Full Payload">
    ```json theme={null}
    {
      "name": "profile_updated",
      "user": {
        "id": "user_123",
        "email": "john@example.com",
        "traits": {
          "plan": "premium",
          "company": "Acme Corp"
        }
      },
      "timestamp": "2025-01-15T10:00:00Z",
      "properties": {
        "fields_updated": ["email", "company"]
      }
    }
    ```

    **✅ With user enrichment** - updates user profile
  </Tab>
</Tabs>

***

### 📦 Batch Events Payload (`/v1/events` - Advanced)

**For high-volume applications only:**

```json theme={null}
{
  "sent_at": "2025-01-15T10:00:00Z",
  "events": [
    {
      "type": "event",
      "name": "event_name",
      "user": "user_123",
      "properties": {
        "custom_property": "value"
      }
    }
  ]
}
```

### 🎨 Properties vs Traits

<Tabs>
  <Tab title="📊 Properties (Event Data)">
    ```json theme={null}
    {
      "name": "purchase_completed",
      "user": "user_123",
      "properties": {
        "amount": 99.00,
        "product": "pro_plan",
        "payment_method": "stripe",
        "discount_code": "SAVE20"
      }
    }
    ```

    **👉 Use for:** Event context, transaction details, session info, action metadata
  </Tab>

  <Tab title="👤 Traits (User Attributes)">
    ```json theme={null}
    {
      "name": "profile_updated",
      "user": {
        "id": "user_123",
        "traits": {
          "email": "john@example.com",
          "plan": "premium",
          "company_size": "50-100",
          "industry": "saas"
        }
      }
    }
    ```

    **👉 Use for:** User demographics, account info, preferences, persistent attributes
  </Tab>
</Tabs>

<Info>
  **Quick Rule:** - **Properties** = What happened in this event 📊 - **Traits**
  \= Who the user is 👤
</Info>

## Response Format

### Success Response

```json theme={null}
{
  "success": true,
  "events_processed": 1
}
```

### Error Response

```json theme={null}
{
  "error": "Invalid API key",
  "code": 401
}
```

## 🎯 Best Practices

1. **Use `/v1/event` endpoint** for most applications (simpler, faster)
2. **📊 Send minimal required fields** - `name` and `user` are often enough
3. **📋 Use meaningful event names** that describe user actions
4. **👤 Include user traits** when you have rich user data
5. **🔒 Use environment variables** for API keys
6. **⚡ Only batch events** if you have 100+ events per minute

## 🚦 Rate Limits

| Limit Type             | `/v1/event` | `/v1/events` (batch) |
| ---------------------- | ----------- | -------------------- |
| **Events/sec**         | 1000        | 1000 total events    |
| **Payload size**       | 1 MB        | 10 MB                |
| **Events per request** | 1           | Up to 100            |
| **👉 Best for**        | Most apps   | High-volume only     |

## Support

For REST API questions, contact [support@userboo.st](mailto:support@userboo.st)
