# API-based Segmentation Quickstart Guide

## What is Segmentation?

Segmentation lets you target specific campaigns to specific users. With our APIs, you can add users to campaigns, check their status, and remove them when needed - all programmatically.

### Prerequisites

Before you start:

* ✅ Get your API key from the CustomerGlu Dashboard
* ✅ Note your Campaign IDs from the Campaigns section
* ✅ Have your User IDs ready (same as Registration API)

### API Endpoints

#### 1. Add a User to a Campaign

**Request:**

```http
POST https://api-us.customerglu.com/segment/:campaignId/user/add
Content-Type: application/json
X-API-KEY: your-api-key

{
    "userId": "user-123"
}
```

**Response:**

```http
HTTP/1.1 200 OK
Content-Type: application/json

{
    "success": true,
    "message": "User added to campaign successfully"
}
```

**Effect:** User immediately starts seeing the campaign and can earn associated rewards.

#### 2. Check User's Campaign Status

**Request:**

```http
POST https://api-us.customerglu.com/segment/:campaignId/user/status
Content-Type: application/json
X-API-KEY: your-api-key

{
    "userId": "user-123"
}
```

**Response:**

```http
HTTP/1.1 200 OK
Content-Type: application/json

{
    "success": true,
    "data": {
        "isPresent": true  // or false if not in segment
    }
}
```

#### 3. Remove a User from a Campaign

**Request:**

```http
DELETE https://api-us.customerglu.com/segment/:campaignId/user/delete
Content-Type: application/json
X-API-KEY: your-api-key

{
    "userId": "user-123"
}
```

**Response:**

```http
httpCopyHTTP/1.1 200 OK
Content-Type: application/json

{
    "success": true,
    "message": "User removed from campaign successfully"
}
```

**Effect:** Campaign stops appearing for this user; they stop earning campaign rewards.

## Implementation Examples

#### Personalized Onboarding

```javascript
javascriptCopy// When a new user signs up
function onUserSignup(userId) {
  // Add to onboarding campaign
  fetch('https://api-us.customerglu.com/segment/onboarding-campaign-id/user/add', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-KEY': 'your-api-key'
    },
    body: JSON.stringify({ userId })
  });
  
  // After completion, move to next campaign
  function moveToNextStage() {
    // Remove from onboarding
    fetch('https://api-us.customerglu.com/segment/onboarding-campaign-id/user/delete', {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'X-API-KEY': 'your-api-key'
      },
      body: JSON.stringify({ userId })
    });
    
    // Add to core features campaign
    fetch('https://api-us.customerglu.com/segment/core-features-id/user/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-KEY': 'your-api-key'
      },
      body: JSON.stringify({ userId })
    });
  }
}
```

#### A/B Testing

```javascript
javascriptCopy// Split users between variant campaigns
function assignVariant(userId) {
  const variant = Math.random() > 0.5 ? 'a' : 'b';
  const campaignId = `variant-${variant}-campaign-id`;
  
  fetch(`https://api-us.customerglu.com/segment/${campaignId}/user/add`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-KEY': 'your-api-key'
    },
    body: JSON.stringify({ userId })
  });
  
  return variant; // Track which variant was assigned
}
```

### Regional Endpoints

Select the appropriate base URL for your region:

* 🇺🇸 US: `https://api-us.customerglu.com`
* :flag\_ae: UAE: `https://api-me.customerglu.com`
* :flag\_in: IN: `https://api-in.customerglu.com`

### Error Handling

The API returns standard HTTP status codes. Here are common errors and solutions:

```http
HTTP/1.1 401 Unauthorized
Content-Type: application/json

{
    "success": false,
    "error": "Invalid API key"
}
```

Solution: Verify your API key is correct and active.

```http
HTTP/1.1 404 Not Found
Content-Type: application/json

{
    "success": false,
    "error": "Campaign not found"
}
```

Solution: Double-check the campaign ID exists and is active.

### Best Practices

1. **Check Before Modifying**: Use the status endpoint to avoid redundant operations
2. **Error Handling**: Implement proper error handling with retries for production systems
3. **Webhooks Integration**: Connect user events to segmentation API calls for real-time targeting
4. **Caching**: Cache segment membership locally for frequently checked users
5. **Logging**: Track API calls and responses for debugging and audit purposes

### Need Help?

Run into issues? Check these common troubleshooting steps:

1. Verify API key permissions in your CustomerGlu Dashboard
2. Ensure campaign IDs are correct and campaigns are active
3. Check that user IDs match those in your CustomerGlu account
4. Confirm you're using the correct regional endpoint

For more assistance, contact our developer support team via Slack


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.customerglu.com/integration-doc/api-based-segmentation-quickstart-guide.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
