HomeDocumentationCode SamplesAnnouncementsModelsRelease NotesFAQGitHubVideos
Developer HubAPI StatusSupport
Documentation
Developer HubAPI StatusSupport

Tutorial: Automate your SP-API Calls Using a JavaScript SDK for Node.js

Automate your SP-API calls with Login with Amazon (LWA) token exchange and authentication.

This tutorial provides you with all the required details to generate a JavaScript SDK for Node.js with Login with Amazon (LWA) token exchange and authentication to build your application seamlessly. You learn the prerequisites required to build the JavaScript SDK for Node.js and also view an example using the Selling Partner API for Sellers and Swagger Code Generator.

The SP-API JavaScript SDK for Node.js is designed for server-side integration with Amazon's Selling Partner API. This tutorial covers integrating and making SP-API calls with a focus on practical application, so you can execute API calls and integrate Amazon’s marketplace capabilities directly into your server-side processes.

Tutorial

The following tutorial will help you set up your own JavaScript SDK for Node.js for automating SP-API calls.

Prerequisites

To complete this tutorial, you need the following prerequisites:

  • A hybrid or SP-API app in draft or published state
  • Integrated development environment (IDE) software
  • Java version 7 or higher
  • swagger-codegen-cli-2.4.29
  • Node.js v18 or higher

❗️

Warning

You must use swagger-codegen-cli-2.4.29. If you use swagger-codegen-cli versions other than 2.4.29, generating the SDK will fail. Using the wrong version could cause larger issues in the integration process.

Before your application can connect to the Selling Partner API, you must register it, and it must be authorized by a selling partner. If you do not have a hybrid or SP-API app, follow the steps to register as a developer, register your application, and Authorizing Selling Partner API applications. Then, return to this tutorial.

Next, set up your workspace for the tutorial.

Step 1. Set up your workspace

  1. On your local drive, create a directory for this project, name it SPAPI_JavaScript_SDK, and navigate to the new directory.

    mkdir SPAPI_JavaScript_SDK
    cd SPAPI_JavaScript_SDK
    
  2. Download the following tools.

  3. Run the following command to download the Swagger Code Generator:

    wget https://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.4.29/swagger-codegen-cli-2.4.29.jar
    
  4. Use the following command to get the file and change permissions to make it executable.

    chmod 744 swagger-codegen-cli-2.4.29.jar
    
  5. Copy swagger-codegen-cli.jar into your local directory C:\\SPAPI_JavaScript_SDK.

  6. In GitHub, go to https://github.com/amzn/selling-partner-api-models/tree/main/models and use the following command to clone the selling-partner-api-models repository to your local directory C:\\SPAPI_JavaScript_SDK.

    git clone https://github.com/amzn/selling-partner-api-models
    

    Now that you have completed the required setup, the next step is to generate the JavaScript SDK for Node.js with the authentication and authorization classes provided in the sellingpartner-api-javascript folder.

Step 2. Generate a JavaScript SDK for Node.js with LWA token exchange and authentication

Navigate to the SellingPartnerAPISdkJavaScriptNode/src directory. In the src directory find the generate-js-sdk.sh shell script file. Run the following script in the command line:

cd SellingPartnerAPISdkJavaScriptNode/src
./generate-js-sdk.sh -j ../../swagger-codegen-cli-2.4.29.jar

You can now view the models and sdk directories, which contain the API models and the JavaScript SDK respectively, in your package root.

This folder provides helper classes to generate an access token for Amazon Selling Partner APIs. It is intended for use with the Selling Partner API Client Libraries generated by Swagger Codegen using the RestSharp library. It can also be integrated into custom projects.

Step 3. Create a local npm package

Package your SDK to use across multiple local projects without publishing the SDK to the public npm registry.

  1. Open your package.json file and add the following to ensure that the package.json is properly set up to include the necessary directories.:

    "files": [
      "src/helper/",
      "sdk/"
    ]
    

    This step ensures that only the specified directories and their contents (for example, src/helper/ and sdk/) are included in the package, and others are ignored.

  2. Navigate to the SellingPartnerAPISdkJavaScriptNode directory in your terminal or command prompt.

  3. Run the following command to create the package:

    npm pack
    

    This command creates a tarball (TGZ file) in your project directory, named amzn-testsellingpartnerjavascriptapilwalib-1.0.0.tgz or similar, based on your package's name and version. It includes all the necessary files from your project, effectively creating a local package that can be installed just like any published npm package.

Step 4. Create a new project using the local npm package

Now you can create a new project that uses the local npm package. With this approach, you can test the SDK in an environment similar to what end developers will encounter.

  1. Enter the following command to create a new directory for the new project. This example assumes your current directory is SellingPartnerAPISdkJavaScriptNode/src:

    cd ../../
    mkdir MyNewSPAPIProject
    cd MyNewSPAPIProject
    
  2. Set up a new Node.js project to ensure a clean environment.

    npm init -y
    
  3. Follow the prompts to initialize your new project. Accept the default options if they match your preferences.

  4. Install the local npm package you created in Step 3. Create a local npm package into this new project. For the following command, replace the placeholder ../SellingPartnerAPISdkJavaScriptNode/amzn-testsellingpartnerjavascriptapilwalib-1.0.0.tgz with the actual path to your TGZ file. This step is crucial because it simulates how other developers will integrate your SDK into their projects.

    npm install ../SellingPartnerAPISdkJavaScriptNode/amzn-testsellingpartnerjavascriptapilwalib-1.0.0.tgz
    

    📘

    Note

    The path to your .tgz file can be absolute or relative, based on your current working directory. For example, if your .tgz file is in the SellingPartnerAPISdkJavaScriptNode directory, your command is npm install ../SellingPartnerAPISdkJavaScriptNode/amzn-testsellingpartnerjavascriptapilwalib-1.0.0.tgz.

    After completing these steps, your package will be listed as a dependency in your new project's package.json, and you can import functionalities as you normally would.

Step 5. Connect to the Selling Partner API using the generated JavaScript SDK for Node.js

With authentication set up, you're now ready to interact with the SP-API endpoints.

  1. Store your LWA credentials in an app.config.mjs file within the project root.

    touch app.config.mjs
    
  2. Define your credentials inside app.config.mjs as follows:

    export const AppConfig = {
        lwaClientId: "< LWA client ID >",
        lwaClientSecret: "< LWA client secret >",
        lwaRefreshToken: "< LWA refresh token >",
    }
    

    🚧

    Caution

    Never commit this file to your version control system as it contains sensitive information. Please ensure these LWA credentials are stored securely in an encrypted format.

  3. Create a new file named index.js in your project root directory and insert the following script, which initiates a call to a specific SP-API endpoint and logs the response to the console.

    touch index.js
    
  4. Copy and paste the following into index.js:

    import { AppConfig } from './app.config.mjs';
    import { LwaAuthClient } from '@amzn/testsellingpartnerjavascriptapilwalib/src/helper/LwaAuthClient.mjs';
    
    import {
      SellersApi,
      ApiClient as SellersApiClient,
    } from '@amzn/testsellingpartnerjavascriptapilwalib/sdk/src/sellers/index.js';
    
    (async () => {
      const lwaClient = new LwaAuthClient(
        AppConfig.lwaClientId,
        AppConfig.lwaClientSecret,
        AppConfig.lwaRefreshToken
      );
      const sellerApiClient = new SellersApiClient(
        'https://sellingpartnerapi-fe.amazon.com'
      );
    
      const sellerApi = new SellersApi(sellerApiClient);
      sellerApiClient.applyXAmzAccessTokenToRequest(
        await lwaClient.getAccessToken()
      );
      const participations = await sellerApi.getMarketplaceParticipations();
      console.log(
        JSON.stringify(participations, null, '  ') +
          '\n**********************************'
      );
    })();
    
  5. Run the script: Run the following command in your terminal or command prompt to initiate a GET request to the Sellers API endpoint:

    node index.js
    

    This command runs your script, initiates the API call, and displays the results in your console.

    Expected Output:

    {
      "payload": [
        {
          "marketplace": {
            "id": "xxxxx",
            "countryCode": "JP",
            "name": "Amazon.co.jp",
            "defaultCurrencyCode": "JPY",
            "defaultLanguageCode": "ja_JP",
            "domainName": "www.amazon.jp“
          },
          "participation": {
            "isParticipating": true,
            "hasSuspendedListings": false
          }
        }
      ]
    }