> For the complete documentation index, see [llms.txt](https://docs.growsurf.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.growsurf.com/developer-tools/rest-api/tutorials.md).

# Tutorials

{% hint style="success" %}

#### Customer Example: How Bolt.new Powered Their Viral Referral Program with GrowSurf’s API

See our in-depth technical [blog post](https://growsurf.com/blog/how-boltnew-powered-their-viral-referral-program-with-growsurfs-api) on how a GrowSurf customer implemented the API, webhooks, and reward metadata to scale their referral program to millions of users.
{% endhint %}

## Table of contents

The following examples use **Node.js**.

| Scenario                                                                                                                                                                                 |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Example 1: Trigger a referral on qualifying action (e.g, on conversion, purchase or upgrade)](#example-1-trigger-a-referral-on-qualifying-action-e.g-on-conversion-purchase-or-upgrade) |
| [Example 2: Trigger a referral on signup event](#example-2-trigger-a-referral-on-signup-event)                                                                                           |
| [Example 3: Get a participant's details](#example-3-get-a-participants-details)                                                                                                          |
| [Example 4: Delete a list of participants](#example-4-delete-a-list-of-participants)                                                                                                     |

## Example 1: Trigger a referral on qualifying action (e.g, on conversion, purchase or upgrade)

{% hint style="info" %}
**Airbnb as an example**

> ***"**&#x53;end a friend $40 in Airbnb credit. You’ll get $20 when they travel and $75 when they host."*

Follow this tutorial if your program's [referral trigger](https://support.growsurf.com/article/188-what-triggers-a-referral) is *Qualifying Action,* where a referrer only receives credit when the person they referred signs up AND performs a certain qualifying action.
{% endhint %}

This requires two API calls to GrowSurf.

### [Step 1: Make sure you have authentication set up](/developer-tools/rest-api.md#getting-started)

### Step 2: Add the participant

{% hint style="warning" %}
**Important Note:** If your program is configured to add participants automatically through a form on your website ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LgbRcVrYaKYUhQVctKK%2F-LgbS62PrNqHiJm-qwdI%2FScreen%20Shot%202019-06-05%20at%207.42.50%20PM.png?alt=media\&token=85e064ce-4bac-4617-9481-f80215478d51)), skip this ste&#x70;**.**
{% endhint %}

First, in the code where you capture the new user's email, add them to your GrowSurf program as a participant with the [**`POST`** `Add participant`](/developer-tools/rest-api/api-reference.md#post-campaign-id-participant) method. Alternatively, you can use the JavaScript method [`growsurf.addParticipant()`](https://docs.growsurf.com/developer-tools/javascript-sdk/api-reference#add-participant) instead to add participants.

The example below is what that code could look like when using the REST API.

**Code Example**

{% code title="signup.js" %}

```javascript
const request = require("request");

let options = {
  method: 'POST',
  url: 'https://api.growsurf.com/v2/campaign/4pdlhb/participant',
  headers: {
    Authorization: 'Bearer <YOUR_API_KEY>'
  },
  json: true
};

const signUp = user => {
    // Set the body of the GrowSurf API request
    options.body = user;

    // Send the API request to add the user as a new participant in your GrowSurf program
    request(options, (error, response, body) => {
      if (error) {
        throw new Error(error);
      }
      const growsurfId = body.id;
      // Save the new user to your database (optional)
      saveUser(user, growsurfId);
    });
};
```

{% endcode %}

**At line 21,** we set the GrowSurf participant ID as a variable called `growsurfId`.

**At line 23**, `saveUser(user, growsurfId)` is an example function you would use to save the GrowSurf participant ID to the new user in your database. We will use this `growsurfId` value later for triggering a referral.

{% hint style="info" %}
**Don't want to save the `growsurfId` to your database?**

The participant's`email` can be used instead of the `growsurfId` to trigger a referral later. If you have access to the participant's email then there is no need to persist the `growsurfId` into your database.
{% endhint %}

**At line 11**, the `user` argument passed into `signUp(user)` is an Object that looks like this:

```javascript
{
  email: 'sally_mayweathers9448@gmail.com',
  firstName: 'Sally', // Optional, but recommended for anti-fraud purposes
  lastName: 'Mayweathers', // Optional, but recommended for anti-fraud purposes
  ipAddress: 1.2.1.827, // Optional, but recommended for anti-fraud purposes
  fingerprint: 'dwah12iu3hi1u2h', // Optional, but recommended for anti-fraud purposes
  referredBy: '1cca8d', // The referrer's unique GrowSurf ID. Can also be the referrer's unique email address
  metadata: {
    phoneNumber: '+1 415-123-4567',
    country: 'USA',
    zipCode: '94303'
  }
}
```

* **At lines 2 and 3,** we pass in `firstName` and `lastName`. These will be used for anti-fraud purposes, as well as in referred friend motivator elements, if enabled.
* **At line 4**, we pass in the user's IP address, which will be used for anti-fraud purposes.
* **At line 5**, we pass in the user's browser fingerprint, which will be used for anti-fraud purposes. You can use a library like [fingerprintjs](https://github.com/fingerprintjs/fingerprintjs) to get this value.
* **At line 6**, we use `referredBy` to associate this new user with a referrer. This value can be the referrer's email address or unique GrowSurf ID (you may want to use [`growsurf.getReferrerId()`](https://docs.growsurf.com/developer-tools/javascript-sdk/api-reference#get-referrer-id) to retrieve the referrer ID).
* **At line 7**, we save a shallow `metadata` Object to the GrowSurf Participant. This is optional, but is useful for viewing specific participant information in your GrowSurf dashboard ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LfiWyhm5z0L0AN3V1o_%2F-Lficu90C8YEPgrdhKyA%2FScreen%20Shot%20on%202019-05-25%20at%2018%3A56%3A33.png?alt=media\&token=1d3a352f-652e-4d13-83bd-aab4aa7ae369)).

### **Step 3: Trigger the referral**

{% hint style="warning" %}
**Important Note:** Make sure your program's referral trigger is set to *Sign Up + Qualifying Action* ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LnvqQyyEju4bLT4R5PC%2F-LnvsusHI0xFY2PJcJzB%2FScreen%20Shot%202019-09-04%20at%206.42.06%20PM.png?alt=media\&token=21db3d41-f20b-4887-833c-8109205cbc89)). If the referral trigger is set to *Sign Up*, triggering referrals will not work since referral credit has already been provided.
{% endhint %}

Now at any future date [within the referral credit window](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LfTU5fPPuEimujYPBlL%2F-LfTUYdelF4Itf1vXW9T%2FScreen%20Shot%20on%202019-05-22%20at%2015%3A42%3A38.png?alt=media\&token=b1bd5196-2825-4229-b280-0c1240b0b30e), if this new participant performs the goal event, then referral credit will be awarded to their referrer. To trigger the referral, use the [**`POST`** `Trigger referral by participant ID`](/developer-tools/rest-api/api-reference.md#post-campaign-id-participant-participantidoremail-ref) method.

The example below is what that code could look like.

**Code Example**

{% code title="purchase.js" %}

```javascript
const request = require("request");

let options = {
  method: 'POST',
  headers: {
    Authorization: 'Bearer <YOUR_API_KEY>'
  },
  json: true
};

const purchase = growsurfId => {
    // ...code that makes the purchase...

    // Set the GrowSurf API request URL with the participant's ID
    options.url = `https://api.growsurf.com/v2/campaign/4pdlhb/participant/${growsurfId}/ref`;

    // Send the API request to trigger the referral
    request(options, (error, response, body) => {
      if (error) {
        throw new Error(error);
      }
      // Check to see if the referral was triggered successfully
      const { success, message } = body.success;
      if(success) {
        console.log('Referral trigger success!');
      } else {
        console.log('Referral trigger failed :( ', message);
      }
    });
};
```

{% endcode %}

**At line 11**, we passed a `growsurfId` argument, which is the GrowSurf participant's unique ID and is required in the API call. If you do not have access to the `growsurfId` of the participant, the participant `email` can be used instead.

{% hint style="info" %}

### **Want to honor a refund or cancellation window?**

You can hold the referral credit for a set number of days before it is awarded by including an optional `delayInDays` value (an integer between `1` and `90`) in the request body of the [`POST` `Trigger referral`](/developer-tools/rest-api/api-reference.md#post-campaign-id-participant-participantidoremail-ref) call. If the purchase is refunded during that window, cancel the pending trigger with the [`DELETE` `Cancel delayed referral trigger`](/developer-tools/rest-api/api-reference.md#delete-campaign-id-participant-participantidoremail-ref) method before the credit is awarded.
{% endhint %}

{% hint style="info" %}
**Remember to set up reward fulfillment automation**

Make sure you have [Webhooks](/developer-tools/webhooks.md) or [Zapier](/integrations/zapier.md) set up so that rewards automatically get fulfilled to the participant once they reach a reward goal.
{% endhint %}

## Example 2: Trigger a referral on signup event

{% hint style="info" %}
**Dropbox as an example**

> ***"**&#x46;or every friend you refer, you’ll both receive an extra 250MB in cloud storage."*

Follow this tutorial if your program's [referral trigger](https://support.growsurf.com/article/188-what-triggers-a-referral) is *Signup Event*, where a referrer receives credit when the person they referred signs up with their email address.
{% endhint %}

This requires just one API call to GrowSurf.

### [Step 1: Make sure you have authentication set up](/developer-tools/rest-api.md#getting-started)

### Step 2: Add the participant (and trigger the referral at the same time)

{% hint style="warning" %}
**Important Notes:**

* If your program is configured to add participants automatically through a form on your website ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LgbRcVrYaKYUhQVctKK%2F-LgbS62PrNqHiJm-qwdI%2FScreen%20Shot%202019-06-05%20at%207.42.50%20PM.png?alt=media\&token=85e064ce-4bac-4617-9481-f80215478d51)), skip this ste&#x70;**.**
* Make sure your program's referral trigger is set to *Signup Event* ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-Lnvt7uOcb1oD4xpY-jJ%2F-Lnvtjtp4i_3zpP2Yag7%2FScreen%20Shot%202019-09-04%20at%206.40.09%20PM.png?alt=media\&token=58dea9be-eb47-42c0-b1af-cb392c246e6b)).
  {% endhint %}

In the code where you capture the new user's email, add them to your GrowSurf program as a participant with the [**`POST`** `Add participant`](/developer-tools/rest-api/api-reference.md#post-campaign-id-participant) method.

The example below is what that code could look like.

**Code Example**

{% code title="signup.js" %}

```javascript
const request = require("request");

let options = {
  method: 'POST',
  url: 'https://api.growsurf.com/v2/campaign/4pdlhb/participant',
  headers: {
    Authorization: 'Bearer <YOUR_API_KEY>'
  },
  json: true
};

const signUp = user => {
    // Set the body of the GrowSurf API request
    options.body = user;

    // Send the API request to add the user as a new participant in your GrowSurf program
    request(options, (error, response, body) => {
      if (error) {
        throw new Error(error);
      }

      // Save the new user to your database (Optional)
      saveUser();
    });
};
```

{% endcode %}

**At line 12**, the `user` argument passed into `signUp(user)` is an Object that looks like this:

```javascript
{
  email: 'sally_mayweathers9448@gmail.com',
  firstName: 'Sally', // Optional, but recommended for anti-fraud purposes
  lastName: 'Mayweathers', // Optional, but recommended for anti-fraud purposes
  ipAddress: 1.2.1.827, // Optional, but recommended for anti-fraud purposes
  fingerprint: 'dwah12iu3hi1u2h', // Optional, but recommended for anti-fraud purposes
  referredBy: '1cca8d', // The referrer's unique GrowSurf ID. Can also be the referrer's unique email address
  referralStatus: 'CREDIT_AWARDED',
  metadata: {
    phoneNumber: '+1 415-123-4567',
    country: 'USA',
    zipCode: '94303'
  }
}
```

* **At lines 2 and 3,** we pass in `firstName` and `lastName`. These will be used for anti-fraud purposes, as well as in referred friend motivator elements, if enabled.
* **At line 4**, we pass in the user's IP address, which will be used for anti-fraud purposes.
* **At line 5**, we pass in the user's browser fingerprint, which will be used for anti-fraud purposes. You can use a library like [fingerprintjs](https://github.com/fingerprintjs/fingerprintjs) to get this value.
* **At line 6**, we use `referredBy` to associate this new user with a referrer. This value can be the referrer's email address or unique GrowSurf ID (you may want to use [`growsurf.getReferrerId()`](https://docs.growsurf.com/developer-tools/javascript-sdk/api-reference#get-referrer-id) to retrieve the referrer ID)
* **At line 7**, we set `referralStatus` to be `CREDIT_AWARDED`. This triggers the referral credit at the same time that this new participant is added (and it overrides the program referral trigger ([what's a referral trigger?](https://support.growsurf.com/article/188-what-triggers-a-referral)) that was set from the *Installation* step of the *Program Editor* ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LfU6JzlO17UzeyVOQcZ%2F-LfU6SW-uc8zI2uuzeah%2FScreen%20Shot%20on%202019-05-22%20at%2018%3A36%3A23.png?alt=media\&token=6204ba21-12b5-4630-90e3-f6117230d7f9)).
  * **Note:** `referralStatus` must be used with `referredBy`, or else it will be ignored.
* **At line 8**, we save a shallow `metadata` Object to the GrowSurf Participant. This is optional, but is useful for viewing specific participant information in your GrowSurf dashboard ([see image](https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/assets%2F-LeklWo0yn03AhWro2Ux%2F-LfiWyhm5z0L0AN3V1o_%2F-Lficu90C8YEPgrdhKyA%2FScreen%20Shot%20on%202019-05-25%20at%2018%3A56%3A33.png?alt=media\&token=1d3a352f-652e-4d13-83bd-aab4aa7ae369)).

{% hint style="info" %}
**Remember to set up reward fulfillment automation**

Make sure you have [Webhooks](/developer-tools/webhooks.md) or [Zapier](/integrations/zapier.md) set up so that rewards automatically get fulfilled to the participant once they reach a reward goal.
{% endhint %}

## Example 3: Get a participant's details

Let's say you want to display a participant's referral progress/stats/rewards in your website or mobile app. With the REST API, you can fetch [`Participant`](/developer-tools/rest-api/api-objects.md#participant)s and [`ParticipantReward`](/developer-tools/rest-api/api-objects.md#reward)s by using either of the following API methods:

* [**`GET`** `Get participant by email`](/developer-tools/rest-api/api-reference.md#get-campaign-id-participant-participantidoremail)
* [**`GET`** `Get participant by ID`](/developer-tools/rest-api/api-reference.md#get-campaign-id-participant-participantidoremail)

### [Step 1: Make sure you have authentication set up](/developer-tools/rest-api.md#getting-started)

### Step 2: Retrieve a participant by email

Let's say your server calls your database to retrieve user details and in that same call you want to send their participant information by using their unique email.

The example below is what that code could look like.

**Code Example**

```javascript
const request = require("request");

let options = {
	method: 'GET',
	headers: {
  		Authorization: 'Bearer <YOUR_API_KEY>'
  	}
};

const getUserDetails = userEmail => {
	// ...Call your database to get user details...
	// ...code here...

	// Get the GrowSurf participant's details
	request(options, (error, response, body) => {
		options.url = `https://api.growsurf.com/v2/campaign/4pdlhb/participant/${userEmail}`;
	 	if (error) {
			throw new Error(error);
		}
		console.log(body);
	});
};
```

**At line 10**, we passed `userEmail` so we could set it in the GrowSurf API URL at line 16.

**At line 20**, `console.log` would print something like this:

```javascript
{
    "id": "f8g9nl",
    "firstName": "Gavin",
    "lastName": "Belson",
    "referralCount": 2,
    "shareUrl": "https://piedpiper.com?grsf=f8g9nl",
    "email": "gavin@hoolie.com",
    "createdAt": 1552404738928,
    "fraudRiskLevel": "LOW",
    "fraudReasonCode": "UNIQUE_IDENTIY",
    "isWinner": true,
    "shareCount": {
        "email": 10,
        "facebook": 1,
        "pinterest": 1,
        "twitter": 11
    },
    "impressionCount": 2,
    "referrals": [
        "i9g2bh",
        "xua4sq"
    ],
    "referralSource": "PARTICIPANT",
    "referralStatus": "CREDIT_AWARDED",
    "referrer": {
        "id": "h8kp6l",
        "firstName": "Richard",
        "lastName": "Hendricks",
        "referralCount": 5,
        "shareUrl": "https://piedpiper.com?grsf=h8kp6l",
        "email": "richard@piedpiper.com",
        "createdAt": 1552402661449,
        "referralSource": "DIRECT",
        "fraudRiskLevel": "LOW",
        "fraudReasonCode": "UNIQUE_IDENTIY",
        "isWinner": true,
        "shareCount": {
            "email": 20,
            "facebook": 11,
            "linkedin": 0,
            "pinterest": 3,
            "twitter": 12
        },
        "impressionCount": 14,
        "referrals": [
            "0dveu7",
            "f8g9nl",
            "j0hbym",
            "m5xm9l",
            "w01fil"
        ]
    }
}
```

## Example 4: Delete a list of participants

To remove many participants at once, send them to the [**`POST`** `Bulk delete participants`](https://docs.growsurf.com/developer-tools/rest-api/api-reference#post-campaign-id-participants-bulk-delete) endpoint. One request deletes up to `200` participants, and each entry can be a participant ID or an email address. The response returns a per-row `status` for every entry, so you can see exactly which ones were removed.

{% hint style="warning" %}
Deleting a participant is permanent. It also removes that participant's referrals, rewards, commissions, and payout records.
{% endhint %}

**Code Example (Node.js)**

This example reads emails from a CSV, splits them into batches of `200`, and deletes each batch. Follow the steps below:

1. Replace `API_KEY` and `CAMPAIGN_ID` at lines 1 and 2 in the `script.js` file.
2. Replace the email addresses in the `emails.csv` file with your own list of participants to delete (keep the column header labeled `Email`).
3. Run `npm install csv-parser` to install the one dependency. The script uses the built-in `fetch`, so you need Node.js 18 or newer.
4. Run `node script.js` to run the script.

{% tabs %}
{% tab title="script.js" %}
{% code title="script.js" lineNumbers="true" %}

```javascript
const API_KEY = "ABC123FS9GM2FBJFZ68T7JNAMRCZ" // Replace with your own API key
const CAMPAIGN_ID = "2x3b5c";                  // Replace with your campaign ID

const csv = require("csv-parser");
const fs = require("fs");

const BATCH_SIZE = 200; // Max entries the bulk-delete endpoint accepts per request

// Reads emails.csv and returns the list of email addresses.
async function readEmails() {
  const emails = [];
  const reader = fs.createReadStream("emails.csv").pipe(csv());
  for await (const row of reader) {
    if (row["Email"]) {
      emails.push(row["Email"].trim());
    }
  }
  return emails;
}

// Deletes one batch of up to 200 participants and returns the API's report.
async function deleteBatch(participants) {
  const url = `https://api.growsurf.com/v2/campaign/${CAMPAIGN_ID}/participants/bulk-delete`;
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ participants })
  });
  const body = await response.json();
  if (!response.ok) {
    throw new Error(`Request failed (${response.status}): ${body.message || "unknown error"}`);
  }
  return body;
}

async function main() {
  const emails = await readEmails();
  console.log(`Deleting ${emails.length} participant(s) in batches of ${BATCH_SIZE}...`);

  for (let i = 0; i < emails.length; i += BATCH_SIZE) {
    const batch = emails.slice(i, i + BATCH_SIZE);
    const { summary, results } = await deleteBatch(batch);

    for (const row of results) {
      if (row.status === "DELETED") {
        console.log(`✅ ${row.identifier} deleted`);
      } else {
        console.log(`⚠️  ${row.identifier} (${row.status}): ${row.message}`);
      }
    }
    console.log(
      `Batch done: ${summary.deletedCount} deleted, ${summary.notFoundCount} not found, ` +
      `${summary.duplicateCount} duplicate, ${summary.errorCount} error`
    );
  }
}

main();
```

{% endcode %}
{% endtab %}

{% tab title="emails.csv" %}
{% code title="emails.csv" lineNumbers="true" %}

```csv
Email
person1@company.com
person2@company.com
person3@company.com
```

{% endcode %}
{% endtab %}
{% endtabs %}

**Some other notes:**

* Each request replaces up to `200` individual delete calls, so you are far less likely to hit the [rate limit](https://docs.growsurf.com/developer-tools/rest-api/api-guidelines#rate-limits). For very large lists, add a short pause between batches.
* A `200` response does not mean every row was deleted. Check each row's `status`: `DELETED`, `NOT_FOUND` (no participant matched the ID or email), `DUPLICATE` (the entry resolves to the same participant as an earlier one in the batch), or `ERROR` (the lookup or deletion failed). The `summary` object totals each outcome.
* A single request can mix participant IDs and email addresses.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.growsurf.com/developer-tools/rest-api/tutorials.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
