klaviyo / klaviyo-node-sdk

Node SDK for developers to use Klaviyo's Public API
https://developers.klaviyo.com/
14 stars 2 forks source link

Klaviyo Node SDK (Legacy) - Retired

Deprecation Notice

This SDK and its associated NPM Package is deprecated and set to be retired on June 30th, 2024 and will not receive further updates. Use our latest Klaviyo Node SDK to take advantage of our new APIs and to continue to receive SDK updates. You can find out latest Klaviyo Node SDK linked here.

If you need help migrating, please follow the instructions below and read our Migrating from V1/V2 to the new Klaviyo APIs and Comparison between v1/v2 and new APIs.

Migration Instructions

NOTE: this change is not backwards compatible; migrating to the new SDK requires completing the following steps:

Install New SDK

npm install klaviyo-api

Update Client Instantiation

The new library contains code for require and ES modules see how to import the new package according to your project in the readme

Updating API Operations

The new SDK has many name changes to both namespace and parameters (types+format). Please reference this section for a comprehensive list of examples.

Version

Helpful Resources

Design & Approach

This SDK is a thin wrapper around our API. See our API Reference for full documentation on API behavior.

This SDK exactly mirrors the organization and naming convention of the above language-agnostic resources, with a few namespace changes to make it Pythonic (details in Appendix).

Organization

This SDK is organized into the following resources:

Installation

NPM

You can install this library using npm.

npm install klaviyo-sdk

source code

Alternatively, you can also run this using this repo as source code, by running one of the following shell commands within the cloned repo:

npm install

and then running JavaScript from the cloned repo.

Usage Example

To instantiate the client

import {ApiClient} from 'klaviyo-sdk'

// Klaviyo sdk setup
const defaultClient = ApiClient.instance;
// Configure API key authorization: ApiKeyAuth
const ApiKeyAuth = defaultClient.authentications['ApiKeyAuth'];
ApiKeyAuth.apiKey = "KLAVIYO PRIVATE KEY GOES HERE";

Or if ES6 isn't your thing

var client = require('klaviyo-sdk');

// Klaviyo sdk setup
var defaultClient = client.ApiClient.instance;
// Configure API key authorization: ApiKeyAuth
var ApiKeyAuth = defaultClient.authentications['ApiKeyAuth'];
ApiKeyAuth.apiKey = "KLAVIYO PRIVATE KEY GOES HERE";

NOTE:

To call the metric-export operation:

import {Metrics} from 'klaviyo-sdk';

const metricId = "METRIC_ID";
const opts = {count: 100};

Metrics.metricExport(metricId, opts)
    .then(data => 'Do Something Here')
    .catch(error => 'An error was thrown check the HTTP code with error.status');

or if you want to use async await

import {Metrics} from 'klaviyo-sdk';

const metricId = "METRIC_ID";
const opts = {count: 100};

// Just make sure you are calling with the async tag ie. async () => {}
try {
    data = await Metrics.metricExport(metricId, opts);
    console.log(data);
} catch (e) {
    console.log(error);
}

once again if you're not using ES6

var client = require('klaviyo-sdk');

var metricId = "METRIC_ID";
var opts = {count: 100};

client.Metrics.metricExport(metricId, opts)
    .then(data => 'Do Something Here')
    .catch(error => 'An error was thrown check the HTTP code with error.status');

Comprehensive list of Operations & Parameters

NOTE:

CampaignsApi

Cancel a Campaign

Campaigns.cancelCampaign(campaignId)

Clone a Campaign

Campaigns.cloneCampaign(campaignId, opts)

Create New Campaign

Campaigns.createCampaign(opts)

Get Campaign Info

Campaigns.getCampaignInfo(campaignId)

Get Campaign Recipients

Campaigns.getCampaignRecipients(campaignId, opts)

Get Campaigns

Campaigns.getCampaigns(opts)

Schedule a Campaign

Campaigns.scheduleCampaign(campaignId, opts)

Send a Campaign Immediately

Campaigns.sendCampaign(campaignId)

Update Campaign

Campaigns.updateCampaign(campaignId, opts)

DataPrivacyApi

Request a Deletion

DataPrivacy.requestDeletion(opts)

ListsSegmentsApi

Add Members to a List

ListsSegments.addMembers(listId, opts)

Create List

ListsSegments.createList(opts)

Delete List

ListsSegments.deleteList(listId)

Exclude Profile From All Email

ListsSegments.excludeGlobally(opts)

Get Global Exclusions & Unsubscribes

ListsSegments.getGlobalExclusions(opts)

Get All Exclusions for a List

ListsSegments.getListExclusions(listId, opts)

Get List Info

ListsSegments.getListInfo(listId)

Check if Profiles Are in a List

ListsSegments.getListMembers(listId, opts)

Check if Profiles Are in a List and not Suppressed

ListsSegments.getListSubscriptions(listId, opts)

Get Lists

ListsSegments.getLists()

Get List and Segment Members

ListsSegments.getMembers(listOrSegmentId, opts)

Check if Profiles Are in a Segment

ListsSegments.getSegmentMembers(segmentId, opts)

Remove Profiles From List

ListsSegments.removeMembers(listId, opts)

Subscribe Profiles to List

ListsSegments.subscribe(listId, opts)

Unsubscribe Profiles From List

ListsSegments.unsubscribe(listId, opts)

Update List Name

ListsSegments.updateListName(listId, opts)

MetricsApi

Get Metrics Info

Metrics.getMetrics(opts)

Query Event Data

Metrics.metricExport(metricId, opts)

Get Events for a Specific Metric

Metrics.metricTimeline(metricId, opts)

Get Events for All Metrics

Metrics.metricsTimeline(opts)

ProfilesApi

Exchange ID for Profile ID

Profiles.exchange(opts)

Get Profile

Profiles.getProfile(personId)

Get Profile's Events for a Specific Metric

Profiles.profileMetricTimeline(personId, metricId, opts)

Get Profile's Events for all Metrics

Profiles.profileMetricsTimeline(personId, opts)

Update Profile

Profiles.updateProfile(personId, opts)

TemplatesApi

Clone Template

Templates.cloneTemplate(templateId, opts)

Create New Template

Templates.createTemplate(opts)

Delete Template

Templates.deleteTemplate(templateId)

Get All Templates

Templates.getTemplates()

Render Template

Templates.renderTemplate(templateId, opts)

Render and Send Template

Templates.sendTemplate(templateId, opts)

Update Template

Templates.updateTemplate(templateId, opts)

TrackIdentifyApi

These are a little unique because the actual payload outlined in our docs below are supposed to be send as a string. Secondly, the two get endpoint need to have their data base64 encoded this might look slightly different depending on what environement you are using the SDK in

Identify Profile

This endpoint requires base 64 encoding of the paramater

const identifyPayload = {
    token: "WRITE_TOKEN",
    properties: {
      $email: "USER_EMAUL",
      property:"PROPERTY_INFO_HERE"
    }
}
const encodedPayload = Buffer.from(JSON.stringify(identifyPayload), 'utf8').toString('base64')
TrackIdentify.identifyGet(encodedPayload)

Identify Profile

This requires the data payload to be sent as a string, luckly this is easy by converting your js object to a string with JSON.stringify

const identifyPayload = {
    token: "WRITE_TOKEN",
    properties: {
      $email: "USER_EMAUL",
      property:"PROPERTY_INFO_HERE"
    }
}
TrackIdentify.identifyPost({data: JSON.stringify(identifyPayload)})

Track Profile Activity

This endpoint requires base 64 encoding of the paramater

const trackPayload = {
  token: WRITE_TOKEN,
  event: "TestEvent",
  customer_properties: {
    $email: USER_EMAIL
  },
  properties: {
    EXAMPLE_PROPERTY, PROPERTY_VALUE,
  }
}
encodedPayload = Buffer.from(JSON.stringify(trackPayload), 'utf8').toString('base64')
TrackIdentify.trackGet(encodedPayload)

Track Profile Activity

This requires the data payload to be sent as a string, luckly this is easy by converting your js object to a string with JSON.stringify

const trackPayload = {
  token: WRITE_TOKEN,
  event: "TestEvent",
  customer_properties: {
    $email: USER_EMAIL
  },
  properties: {
    EXAMPLE_PROPERTY, PROPERTY_VALUE,
  }
}
TrackIdentify.trackPost({data: JSON.stringify(trackPayload)})

Appendix

Limitations

Refresher on catching exceptions:


try {
    await YOUR_CALL
} catch e {
    print(e.status, e.reason, e.body, e.headers)
}

Namespace

In the interest of making the SDK follow conventions, we made the following namespace changes relative to the language agnostic resources up top.

  1. dashes - are removed in favor of camelCase
  2. all other non-alphanumeric symbols, including spaces, are removed.

For example:

Parameters & Arguments

The parameters follow the same naming conventions as the resource groups and operations.

We stick to the following convention for parameters/arguments

  1. All parameters are passed as function args.
  2. All optional params, as well as all Body and Form Data params (including required ones), are passed in a single object param.
  3. All query and path params that are tagged as required in the docs are passed as positional args.
  4. There is no need to pass in your private api_key for any operations, as it is defined upon client instantiation; public key is still required where its used.