npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

amazon-ad-api-tools

v0.0.8

Published

Amazon Advertising API client

Downloads

12

Readme

amazon-ad-api (client for the Amazon Advertising API)

The client handles calls to the Amazon Advertising API. It wraps up all the necessary stuff such as auto-requesting access tokens and/or profiles, handling of BigInt issues with IDs and provides convenience methods, i.e. for requesting and downloading reports.

Contents

Prerequisites

Make sure that you followed the Amazon Ads API Onboarding Process, have successfully retrieved an authorization code and used it to generate a refresh token.

Installation

npm install amazon-ad-api

Getting Started

Before you can use the client you need to add your app client and aws user credentials.

Setting credentials from environment variables

Setting credentials from file

Instead of setting the credentials via environment variables you may load them from a credentials file. The default path to the file is ~/.amzadapi/credentials (path can be changed when creating a client) and you add the credentials one per line:

AMAZON_AD_CLIENT_ID=<YOUR_AD_CLIENT_ID>
AMAZON_AD_CLIENT_SECRET=<YOUR_AD_CLIENT_SECRET>

Setting credentials from constructor config object

Although the most convenient and recommended way of setting the credentials is via environment variables or config file it is also possible to pass the credentials inside the config object when creating an instance of the client (i.e. if you have no means of using env vars or a config file). The structure of the constructor config object will be explained below.

Usage

Require library:

const AdvertisingAPI = require('amazon-ad-api');

Create client and call API:

(async() => {
  try {
    let advertising = new AdvertisingAPI({
      region:'eu', // The region to use for the AD-API operations ("eu", "na" or "fe"),
      country:'de', // The country code of the marketplace to use for the AD-API operations
      refresh_token:'<REFRESH_TOKEN>' // The refresh token of your app user
    });
    let res = await advertising.callAPI({
      operation:'/v2/profiles',
      method:'GET'
    });
    console.log(res);
  } catch(e){
    console.log(e);
  }
})();

Config params

The class constructor takes a config object with the following structure as input:

{
  region:'<REGION>',
  refresh_token:'<REFRESH_TOKEN>',
  access_token:'<ACCESS_TOKEN>',
  credentials:{
    AMAZON_AD_CLIENT_ID:'<AD_CLIENT_ID>',
    AMAZON_AD_CLIENT_SECRET:'<AD_CLIENT_SECRET>'
  },
  options:{
    credentials_path:'~/.amzadapi/credentials',
    auto_request_token:true,
    auto_request_throttled:true,
    max_retries:20,
    use_sandbox:false
  }
}

Valid properties of the config object:

| Name | Type | Default | Description | |:--|:--:|:--:|:--| | regionrequired | string | - | The region to use for the AD-API operations.Must be one of: eu, na or fe | | countryrequired | string | - | The country code of the marketplace to use for the AD-API operations. | | refresh_tokenrequired | string | - | The refresh token of the app user. | | access_tokenoptional | string | - | The temporary access token requested with the refresh token of the app user. | | credentialsoptional | object | - | The app client id and secret. Must include the two credentials properties AMAZON_AD_CLIENT_ID and AMAZON_AD_CLIENT_SECRET with their corresponding values.NOTE: Should only be used if you have no means of using environment vars or credentials file! | | optionsoptional | object | - | Additional options, see table below for all possible options properties. |

Valid properties of the config options:

| Name | Type | Default | Description | |:--|:--:|:--:|--| | credentials_pathoptional | string | ~/.amzadapi/credentials | A custom absolute path to your credentials file location. | | auto_request_tokenoptional | boolean | true | Whether or not the client should retrieve a new access token if not given or expired. | | auto_request_throttledoptional | boolean | true | Whether or not the client should automatically retry a request when throttled. | | max_retriesoptional | integer | 20 | How many retries the client should process when waiting for a report to finish or when a request is throttled. Setting this value to 0 will force the client to wait infinitely. | | use_sandboxoptional | boolean | false | Whether or not to use the sandbox endpoint. |

Request access token

If you only provide the region, country and refresh_token parameters the client will automatically request access_token for you (with a TTL of 1 hour) and reuse the token for future api calls for the class instance.

Instead of having the client handle the access_token requests automatically, you may also refresh the token manually:

let advertising = new AdvertisingAPI({
  region:'eu',
  country:'de',
  refresh_token:'<REFRESH_TOKEN>',
  options:{
    auto_request_token:false
  }
});
await advertising.refreshAccessToken();

If you want to use the same access_token for multiple instances you can retrieve the token via getter and use it as input for a new instance:

let access_token = advertising.access_token;

let advertisingNewInstance = new AdvertisingAPI({
  region:'eu',
  country:'de',
  refresh_token:'<REFRESH_TOKEN>',
  access_token:access_token
});

Call the API

Calls to the AD-API will be triggered by using the .callAPI() function, which takes an object with the following structure as input:

{
  operation:'<OPERATION_TO_CALL>',
  method:'<METHOD_TO_USE>',
  query:{
    ...
  },
  body:{
    ...
  }
}

Valid properties of the object:

| Name | Type | Default | Description | |:--|:--:|:--:|:--| | operationrequired | string | - | The operation (api path) you want to request, see Amazon Advertising API Docs. | | methodrequired | string | - | The HTTP method to use. Must be one of: GET, POST, PUT,DELETE or PATCH. | | queryoptional | object | - | The input paramaters added to the query string of the operation. | | bodyoptional | object | - | The input paramaters added to the body of the operation. |

Examples

Call the API by passing in the operation (api path) and the HTTP method. See the following examples:

let res = await advertising.callAPI({
  operation:'/v2/profiles',
  method:'GET'
});
let res = await advertising.callAPI({
  operation:'/invoices',
  method:'GET',
  query:{
    count:10,
    invoiceStatuses:['ISSUED','PAID_IN_FULL']
  }
});
let res = await advertising.callAPI({
  operation:'/v2/sp/keywords',
  method:'POST',
  body:[{
    campaignId:'<CAMPAIGN_ID>',
    adGroupId:'<AD_GROUP_ID>',
    keywordText:'My exact keyword',
    state:'enabled',
    matchType:'exact',
    bid:1.10
  },{
    campaignId:'<CAMPAIGN_ID>',
    adGroupId:'<AD_GROUP_ID>',
    keywordText:'My even better phrase keyword',
    state:'enabled',
    matchType:'phrase',
    bid:0.80
  }]
});
let res = await advertising.callAPI({
	operation:'/sb/recommendations/bids',
	method:'POST',
	body:{
    campaignId:'<CAMPAIGN_ID>',
    keywords:[{
      keywordText:'headphones',
      matchType:'exact'
    },{
      keywordText:'bluetooth earphones',
      matchType:'exact'
    }],
    adFormat:'productCollection'
	}
});
let res = await advertising.callAPI({
  operation:'/sd/targets',
  method:'PUT',
  body:[{
    targetId:'<TARGET_ID>',
    bid:1.20
  },{
    targetId:'<TARGET_ID>',
    state:'paused'
  }]
});

Request, download and unzip reports

The .getReport() function will request a report, wait for the report to be finished and then download, unzip and return the report.

See the following example:

let report = await advertising.getReport({
  campaignType:'sponsoredProducts',
  recordType:'productAds',
  body:{
    reportDate:'20211201'
  }
});

Valid properties of the object:

| Name | Type | Default | Description | |:--|:--:|:--:|:--| | campaignTyperequired | string | - | The campaignType of the report you want to request, currently supports sponsoredProducts, sponsoredBrands, sponsoredDisplay and brandMetrics. | | recordTypeoptional | string | - | The recordType of the report. Depends on the campaignType, but must be one of: campaigns, adGroups, productAds,keywords ,targets, asins. Required for all campaignTypes except brandMetrics.| | metricsTypeoptional | string | - | Required if campaignType is set to sponsoredBrands. Must be either hsa or video. Also required if campaignType is set to sponsoredProducts and recordType is set to asins. Must be either keywords or targets. | | bodyoptional | object | - | The input paramaters added to the body of the operation. |

NOTE: If you don't provide a list of metrics inside the body, the client will automatically default to include ALL valid metrics for the specific report.

Seller Support

If you are selling on the european market we might be able to support you with everything else that can't be done with the API. Feel free to visit us at https://amz.tools.