amazon-sp-api

repository·main·Indexed 42 days ago

https://github.com/jrl84/amazon-sp-api

A JavaScript/TypeScript client for the Amazon Selling Partner API (SP-API) version 1.2.1. It simplifies API interactions by handling access token requests, rate limiting, report downloading via downloadReport(), and feed uploading. The library provides the SellingPartner class to execute requests through callAPI(), supporting custom typings, grantless operations, and flexible credential configuration via environment variables, files, or constructor objects.

Tokens
19K
Snippets
58
Records
84
Agent score
49%

What's inside amazon-sp-api

  1. How to handle different API versions

    main

    The client defaults to the oldest available version of an endpoint to prevent breaking changes. To use a newer version, you have two options:

    1. Per-call: Specify the version inside the options object of .callAPI().
    2. Class-level: Set endpoints_versions in the SellingPartner constructor to enable a specific version for all operations of that endpoint.

    If version_fallback is set to true (default), the client will automatically attempt to find an operation in an earlier version if it is missing from the version you specified.

    // Option 1: Per-call versioning
    let res = await spClient.callAPI({
      operation: 'getCatalogItem',
      endpoint: 'catalogItems',
      path: { asin: 'B084DWG2VQ' },
      options: { version: '2020-12-01' }
    });
    
    // Option 2: Class-level versioning
    const spClient = new SellingPartner({
      region: 'eu',
      refresh_token: '<REFRESH_TOKEN>',
      endpoints_versions: {
        catalogItems: '2020-12-01'
      }
    });
  2. Configure credentials via constructor config object

    main
    If environment variables or a credentials file are not available, you can pass credentials directly into the configuration object when instantiating the client. The specific structure of this object is detailed in the Config params section of the documentation.
  3. How to use Grantless operations

    main

    Grantless operations do not require a seller's authorization and use a different type of access token.

    To use them:

    1. Initialize the client with only_grantless_operations: true (and optionally auto_request_tokens: false if managing tokens manually).
    2. Request a grantless token using refreshAccessToken(scope) where the scope is either sellingpartnerapi::notifications or sellingpartnerapi::client_credential:rotation.

    If auto_request_tokens is set to true, the client handles token acquisition automatically.

    // 1. Setup client for grantless only
    const spClient = new SellingPartner({
      region: 'eu',
      options: {
        auto_request_tokens: false,
        only_grantless_operations: true
      }
    });
    
    // 2. Request the specific scope
    await spClient.refreshAccessToken('sellingpartnerapi::notifications');
    
    // 3. Call the operation
    let res = await spClient.callAPI({
      operation: 'getDestinations',
      endpoint: 'notifications'
    });
  4. Import the SellingPartner client

    main

    You can import the SellingPartner class using either CommonJS require or ESM import syntax.

    // commonjs
    const SellingPartner = require('amazon-sp-api');
    
    // esm
    import {SellingPartner} from 'amazon-sp-api';
  5. Add custom typings to `callAPI`

    main

    To extend the callAPI method with custom TypeScript types for specific Amazon Selling Partner API operations, follow these steps:

    1. Define the Operation: Add the new operation name to the type Operation = ... definition in index.d.ts.
    2. Create an Operation File: Create a new file in the typings/operations directory. Use the operation category as the filename (e.g., use orders.ts for operations related to orders like getOrders).
    3. Define Interfaces: In the new file, export interfaces for the parameters and the response using a specific naming convention:
      • Parameters: Combine the OperationName with the ParameterType (e.g., GetOrdersQuery, GetOrdersBody, or GetOrdersPath).
      • Response: Export an interface named OperationNameResponse (e.g., GetOrdersResponse).
    4. Register Types: Update index.d.ts by adding the new interfaces to the corresponding conditional type definitions: type QueryType.., type PathType.., or type BodyType.. based on how the operation receives parameters.
  6. Enable Sandbox mode

    main

    You can test operations in Amazon's sandbox environment by setting use_sandbox: true in the constructor configuration options.

    When using the sandbox, ensure you use the specific request parameters required for that operation. These can be found in the Amazon SP API documentation by searching for the x-amzn-api-sandbox key in the corresponding JSON model definitions.

    // Example: Testing getPricing in sandbox mode
    let res = await spClient.callAPI({
      operation: 'getPricing',
      endpoint: 'productPricing',
      query: {
        MarketplaceId: 'TEST_CASE_400'
      }
    });
  7. Upload feeds using .upload()

    main

    To upload a feed, you must first obtain upload details via the createFeedDocument operation. The .upload() method then takes these details along with your feed content and its content type.

    Feed Object Configuration

    NameTypeRequiredDescription
    contentstringOptionalThe content to upload as a string. Required if file is not provided.
    filestringOptionalThe absolute file path to the feed content document. Required if content is not provided.
    contentTypestringRequiredThe content type (e.g., text/xml; charset=utf-8 or text/tab-separated-values; charset=utf-8).

    Workflow Steps

    1. Create Feed Document: Call createFeedDocument to get the feedDocumentId and upload details.
    2. Upload Content: Use spClient.upload(feed_upload_details, feed) to send the data.
    3. Trigger Processing: Call the createFeed operation with marketplaceIds, feedType, and the inputFeedDocumentId retrieved in step 1.
    // 1. Define the feed content
    let feed = {
      content: `<?xml version="1.0" encoding="utf-8"?>...`, // Your XML/TSV content
      contentType: 'text/xml; charset=utf-8'
    };
    
    // 2. Get upload details
    let feed_upload_details = await spClient.callAPI({
      operation: 'createFeedDocument',
      endpoint: 'feeds',
      body: {
        contentType: feed.contentType
      }
    });
    
    // 3. Upload the content
    let res = await spClient.upload(feed_upload_details, feed);
    
    // 4. Trigger processing
    let feed_creation_infos = await spClient.callAPI({
      operation: 'createFeed',
      endpoint: 'feeds',
      body: {
        marketplaceIds: ['A1PA6795UKMFR9'],
        feedType: 'POST_INVENTORY_AVAILABILITY_DATA',
        inputFeedDocumentId: feed_upload_details.feedDocumentId
      }
    });
  8. Call unsupported endpoints using api_path

    main

    If an endpoint, version, or operation is not yet supported by the client, you can bypass the operation/endpoint logic by providing the api_path and the HTTP method directly.

    Note: If your api_path contains special characters (like UTF-8 SKUs), you must manually encode them before passing the string to .callAPI().

    let res = await spClient.callAPI({
      api_path: '/catalog/2020-12-01/items/B084DWG2VQ',
      method: 'GET',
      query: {
        marketplaceIds: ['A1PA6795UKMFR9'],
        includedData: ['identifiers', 'images']
      }
    });
  9. Manually download report data using download()

    main

    If you prefer to manage the report lifecycle manually, you can use the .download() function. This function takes the download details retrieved from a getReportDocument operation, downloads the content, unzips it (if compressed), and decrypts it.

    Step 1: Get Report Document

    Retrieve the reportDocumentId from a getReport operation (once processingStatus is DONE) and call getReportDocument:

    let report_document = await spClient.callAPI({
      operation: 'getReportDocument',
      endpoint: 'reports',
      path: {
        reportDocumentId: '<REPORT_DOCUMENT_ID>'
      }
    });

    The report_document object contains:

    • reportDocumentId: The ID of the document.
    • compressionAlgorithm: (Optional) e.g., 'GZIP'.
    • url: The download URL (expires after 5 minutes).

    Step 2: Download Content

    Pass the report_document to .download(). You can provide an optional second argument (the same download object used in downloadReport()) to enable JSON transformation or file saving.

    Default download (unzip/decrypt, no reformatting):

    let report = await spClient.download(report_document);

    Download with JSON transformation and file saving:

    let report = await spClient.download(report_document, {
      json: true,
      file: '<ABSOLUTE_FILE_PATH>/report.json'
    });

    Download with specific charset (e.g., for cp1252 encoded reports):

    let report = await spClient.download(report_document, {
      charset: 'cp1252'
    });
    let report_document = await spClient.callAPI({
      operation: 'getReportDocument',
      endpoint: 'reports',
      path: {
        reportDocumentId: '<REPORT_DOCUMENT_ID>'
      }
    });
    
    let report = await spClient.download(report_document, {
      json: true,
      file: '<ABSOLUTE_FILE_PATH>/report.json'
    });
  10. Check the result of a processed feed

    main

    Successful upload and creation of a feed does not guarantee successful processing by Amazon. To verify the result:

    1. Use the feedId from the createFeed response to call the getFeed operation.
    2. Check if the response includes a resultFeedDocumentId (this indicates processing is complete).
    3. If present, use the getFeedDocument operation with that ID to retrieve the download details.
    4. Use the .download() function to download the processing result.