Skip to content
This repository has been archived by the owner on Aug 18, 2023. It is now read-only.

klaviyo/klaviyo-node-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

  • SDK version: 1.0.1

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:

  • Campaigns
  • DataPrivacy
  • ListsSegments
  • Metrics
  • Profiles
  • Templates
  • TrackIdentify

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:

  • The SDK retries on resolvable errors, namely: rate limits (common) and server errors on klaviyo (rare).

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:

  • Organization: Resource groups and operation_ids are listed in alphabetical order, first by Resource name, then by OpenAPI Summary. Operation summaries are those listed in the right side bar of the API Reference.
  • For example values / data types, as well as whether parameters are required/optional, please reference the corresponding API Reference link.
  • Some keyword args are required for the API call to succeed, the API docs above are the source of truth regarding which keyword params are required.

CampaignsApi

Campaigns.cancelCampaign(campaignId)
Campaigns.cloneCampaign(campaignId, opts)
Campaigns.createCampaign(opts)
Campaigns.getCampaignInfo(campaignId)
Campaigns.getCampaignRecipients(campaignId, opts)
Campaigns.getCampaigns(opts)
Campaigns.scheduleCampaign(campaignId, opts)
Campaigns.sendCampaign(campaignId)
Campaigns.updateCampaign(campaignId, opts)

DataPrivacyApi

DataPrivacy.requestDeletion(opts)

ListsSegmentsApi

ListsSegments.addMembers(listId, opts)
ListsSegments.createList(opts)
ListsSegments.deleteList(listId)
ListsSegments.excludeGlobally(opts)
ListsSegments.getGlobalExclusions(opts)
ListsSegments.getListExclusions(listId, opts)
ListsSegments.getListInfo(listId)
ListsSegments.getListMembers(listId, opts)
ListsSegments.getListSubscriptions(listId, opts)
ListsSegments.getLists()
ListsSegments.getMembers(listOrSegmentId, opts)
ListsSegments.getSegmentMembers(segmentId, opts)
ListsSegments.removeMembers(listId, opts)
ListsSegments.subscribe(listId, opts)
ListsSegments.unsubscribe(listId, opts)
ListsSegments.updateListName(listId, opts)

MetricsApi

Metrics.getMetrics(opts)
Metrics.metricExport(metricId, opts)
Metrics.metricTimeline(metricId, opts)
Metrics.metricsTimeline(opts)

ProfilesApi

Profiles.exchange(opts)
Profiles.getProfile(personId)
Profiles.profileMetricTimeline(personId, metricId, opts)
Profiles.profileMetricsTimeline(personId, opts)
Profiles.updateProfile(personId, opts)

TemplatesApi

Templates.cloneTemplate(templateId, opts)
Templates.createTemplate(opts)
Templates.deleteTemplate(templateId)
Templates.getTemplates()
Templates.renderTemplate(templateId, opts)
Templates.sendTemplate(templateId, opts)
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

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)

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)})

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)

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

  • The api_key is set at the global level: this means that if you manage multiple stores, you will need to run the code for each store in a different environment

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:

  • get-campaigns becomes getCampaigns
  • Track & Identify becomes TrackIdentify

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.