klaviyo-api-beta v3.0.1
Klaviyo JavaScript Beta SDK
SDK version: 3.0.1
Revision: 2023-01-25.pre (Deprecated)
This Beta SDK uses deprecated and/or retired functionality. This Beta SDK will be updated with new experimental functionality during our next Beta API release. To find all of our up-to-date stable API functionality, please check out our stable SDK.
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
Installation
NPM
You can install this library using npm
.
npm install klaviyo-api-beta
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 ConfigWrapper
import {ConfigWrapper} from 'klaviyo-api-beta'
ConfigWrapper("KLAVIYO PRIVATE KEY GOES HERE")
Or if ES6 isn't your thing
var KaviyoSdk = require('klaviyo-api-beta');
KaviyoSdk.ConfigWrapper("KLAVIYO PRIVATE KEY GOES HERE")
To edit the exponential backoff built into the ConfigWrapper you can pass optional parameters
import {ConfigWrapper} from 'klaviyo-api-beta'
ConfigWrapper("KLAVIYO PRIVATE KEY GOES HERE", {
numOfAttempts: 5, // max number of rety attempts. Default is 3
timeMultiple: 10, // how exponental the timing is. Default is 5
startingDelay: 1000, // How long before first retry. Default is 500
})
NOTE:
- The SDK retries on resolvable errors, namely: rate limits (common) and server errors on klaviyo (rare).
To call the getCampaign
operation:
import {Campaigns} from 'klaviyo-api-beta';
const campaignId = "CAMPAIGN_ID";
const opts = {};
Campaigns.getCampaign(campaignId, 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 {Campaigns} from 'klaviyo-api-beta';
const campaignId = "CAMPAIGN_ID";
const opts = {};
// Just make sure you are calling with the async tag ie. async () => {}
try {
response = await Campaigns.getCampaign(campaignId, opts)
console.log(response);
} catch (e) {
console.log(error);
}
once again if you're not using ES6
var KaviyoSdk = require('klaviyo-api-beta');
var campaignId = "CAMPAIGN_ID";
var opts = {};
KaviyoSdk.Campaigns.getCampaign(campaignId, opts)
.then(data => 'Do Something Here')
.catch(error => 'An error was thrown check the HTTP code with error.status');
What the response looks like
The response is an object with three parts: status, headers, and body
import {Campaigns} from 'klaviyo-api';
const opts = {};
// how to get your request information
try {
response = await Campaigns.getCampaigns(opts)
const response_body = response.body
// first index id
const id = response_body.data[0].id
// getting the next page cursor
const next_page_cursor = response_body.links.next
// rest of the response information
const status = response.status
const headers = response.headers
} catch (e) {
console.log(error);
}
Multiple stores
if you need to use multiple api keys, you can forgo the wrapped api classes and make you own
import {ConfigWrapper, CatalogsApi} from 'klaviyo-api-beta'
const catalogApi = new CatalogsApi(ConfigWrapper("KLAVIYO PRIVATE KEY GOES HERE"))
const r = await catalogApi.createCatalogCategory(body)
Optional Parameters
Different endpoint include specific optional parameters. Here is a few examples how to use these and what they look like
more often than not the info that can go into the opts
param are the optional headers.
These are formatted in js a bit different from the docs, headers names have variables that make bad names like
pagecursor are transformed to pageCursor
. (Remove the weird characters and append words with camelCase)
const opts = {
pageCursor: "page_cursor", // page[cursor]
fieldsList: ["list", "of", "wanted", "attributes"] // fields[list]
include: ["resource_to_include"] // include
}
Cursor based Pagination
Obtain the cursor value from the call you want to get the next page for, then pass it under the pageCursor
optional parameter
const nextPageCursor = 'WzE2NDA5OTUyMDAsICIzYzRjeXdGTndadyIsIHRydWVd'
await Campaigns.getCampaigns({pageCursor: nextPageCursor})
Filtering
Filter by passing the filter as a string as under the optional parameter filter
Read more about formatting your filter strings in our developer documentation
const filter = 'equals(archived,false)'
const response1 = await Campaigns.getCampaigns({filter}); // the same as {filter: filter}
Sparse Fields
The SDK expands the optional sparse fields into their own option, where you can pass a list of the desired items to include
const fieldsCampaign = ["name"]
const fieldsTag = ["name"]
await Campaigns.getCampaign(CAMPAIGN_ID, {
fieldsCampaign,
fieldsTag
});
Includes
Includes you can pass a similar way, just add the values you want to include as a list
const include = ["tags"]
await Campaigns.getCampaign(CAMPAIGN_ID, {
include,
});
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
Create Campaign
const Campaigns.createCampaign(body)
Create Campaign Clone
const Campaigns.createCampaignClone(body)
Create Campaign Message Assign Template
const Campaigns.createCampaignMessageAssignTemplate(body)
Create Campaign Send Job
const Campaigns.createCampaignSendJob(body)
Delete Campaign
const Campaigns.deleteCampaign(id)
Get Campaign
const Campaigns.getCampaign(id, opts)
Get Campaign Message
const Campaigns.getCampaignMessage(id, opts)
Get Campaign Relationships
const Campaigns.getCampaignRelationships(id, relatedResource)
Get Campaign Send Job
const Campaigns.getCampaignSendJob(id, opts)
Get Campaign Tags
const Campaigns.getCampaignTags(campaignId, opts)
Get Campaigns
const Campaigns.getCampaigns(opts)
Update Campaign
const Campaigns.updateCampaign(body, id)
Update Campaign Message
const Campaigns.updateCampaignMessage(body, id)
Update Campaign Send Job
const Campaigns.updateCampaignSendJob(body, id)
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.
- dashes
-
are removed in favor of camelCase - all other non-alphanumeric symbols, including spaces, are removed.
For example:
get-campaigns
becomesgetCampaigns
Track & Identify
becomesTrackIdentify
Parameters & Arguments
The parameters follow the same naming conventions as the resource groups and operations.
We stick to the following convention for parameters/arguments
- All parameters are passed as function args.
- All optional params, as well as all Body and Form Data params (including required ones), are passed in a single object param.
- All query and path params that are tagged as
required
in the docs are passed as positional args. - There is no need to pass in your private
api_key
for any operations, as it is defined upon ConfigWrapper instantiation; public key is still required where its used.