### Install amazon-sp-api Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Install the library using npm. ```bash npm install amazon-sp-api ``` -------------------------------- ### Minimal SellingPartner Client Setup Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Create a SellingPartner client with minimal configuration, relying on environment variables for credentials. ```javascript // Minimal setup — credentials from env vars const spClient = new SellingPartner({ region: 'eu', // required: 'eu' | 'na' | 'fe' refresh_token: process.env.SP_REFRESH_TOKEN }); ``` -------------------------------- ### Complete End-to-End Example with amazon-sp-api Source: https://context7.com/jrl84/amazon-sp-api/llms.txt This example demonstrates a comprehensive workflow using the amazon-sp-api library. It covers authentication, fetching orders, confirming shipments, downloading inventory reports, and submitting feed updates. Ensure you have the necessary environment variables set for authentication. ```javascript const SellingPartner = require('amazon-sp-api'); (async () => { const spClient = new SellingPartner({ region: 'eu', refresh_token: process.env.SP_REFRESH_TOKEN, endpoints_versions: { catalogItems: '2022-04-01' }, options: { debug_log: true, timeouts: { deadline: 30000 } } }); try { // 1. Confirm API access const participations = await spClient.callAPI({ operation: 'sellers.getMarketplaceParticipations' }); console.log('Active marketplaces:', participations.map(p => p.marketplace.id)); // 2. Fetch recent unshipped orders const { Orders } = await spClient.callAPI({ operation: 'getOrders', endpoint: 'orders', query: { MarketplaceIds: ['A1PA6795UKMFR9'], CreatedAfter: new Date(Date.now() - 86400000).toISOString(), OrderStatuses: ['Unshipped'] } }); console.log(`Found ${Orders.length} unshipped orders`); if (Orders.length > 0) { const orderId = Orders[0].AmazonOrderId; // 3. Get order items const { OrderItems } = await spClient.callAPI({ operation: 'getOrderItems', endpoint: 'orders', path: { orderId } }); console.log('First order items:', OrderItems.map(i => i.ASIN)); // 4. Confirm shipment await spClient.callAPI({ operation: 'confirmShipment', endpoint: 'orders', path: { orderId }, body: { packageReferenceId: 'PKG-001', carrierCode: 'DHL', trackingId: '1234567890', shipDate: new Date().toISOString(), orderItems: OrderItems.map(i => ({ orderItemId: i.OrderItemId, quantity: i.QuantityOrdered })) } }); } // 5. Download inventory report as JSON const inventory = await spClient.downloadReport({ body: { reportType: 'GET_FLAT_FILE_OPEN_LISTINGS_DATA', marketplaceIds: ['A1PA6795UKMFR9'] }, interval: 10000, download: { json: true, file: '/tmp/inventory.json' } }); console.log(`Downloaded ${inventory.length} inventory rows`); // 6. Update stock quantity via feed const feedDoc = await spClient.callAPI({ operation: 'createFeedDocument', endpoint: 'feeds', body: { contentType: 'text/xml; charset=utf-8' } }); await spClient.upload(feedDoc, { content: `
1.02MERCHANT_ID
Inventory 1MY-SKU-001100
`, contentType: 'text/xml; charset=utf-8' }); await spClient.callAPI({ operation: 'createFeed', endpoint: 'feeds', body: { marketplaceIds: ['A1PA6795UKMFR9'], feedType: 'POST_INVENTORY_AVAILABILITY_DATA', inputFeedDocumentId: feedDoc.feedDocumentId } }); console.log('Inventory feed submitted'); } catch (err) { console.error(`[${err.code}] ${err.message}`); process.exit(1); } })(); ``` -------------------------------- ### Call API Operation with Path, Query, and Options Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md This example shows how to call an API operation using path parameters, query parameters, and specific options like API version. ```javascript let res = await spClient.callAPI({ operation: 'catalogItems.getCatalogItem', path: { asin: 'B084J4QQFT' }, query: { marketplaceIds: ['A1PA6795UKMFR9'] }, options: { version: '2022-04-01' } }); ``` -------------------------------- ### Download Report with Options Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md This example demonstrates how to use the `downloadReport` function to request a report, specify report type and marketplace, set a re-request interval, and configure download options like JSON transformation and saving to a file. ```APIDOC ## downloadReport ### Description Requests a report and provides options for re-requesting, downloading, transforming to JSON, and saving to a file. ### Method `sellingPartner.downloadReport(options)` ### Parameters #### Body Parameters - **reportType** (string) - Required - The type of report to request. - **marketplaceIds** (string[]) - Required - An array of marketplace IDs for the report. #### Version Parameter - **version** (string) - Required - The API version to use (e.g., '2021-06-30'). #### Interval Parameter - **interval** (number) - Optional - The interval in milliseconds to re-request the report if it's not ready. #### Download Options Object - **json** (boolean) - Optional - Whether to transform the content to JSON. Defaults to false. - **unzip** (boolean) - Optional - Whether to unzip the content. Defaults to true. - **file** (string) - Optional - The absolute file path to save the report to. - **charset** (string) - Optional - The charset to use for decoding. Defaults to 'utf8'. - **timeouts** (object) - Optional - Allows setting timeouts for download requests (response, idle, deadline). ### Request Example ```javascript let res = await sellingPartner.downloadReport({ body: { reportType: 'GET_FLAT_FILE_OPEN_LISTINGS_DATA', marketplaceIds: ['A1PA6795UKMFR9'] }, version: '2021-06-30', interval: 8000, download: { json: true, file: '/report.json' } }); ``` ``` -------------------------------- ### Call API Operation with Query and Raw Result Option Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md This example demonstrates calling an API operation with query parameters and requesting the raw result, useful for specific data retrieval needs. ```javascript let res = await spClient.callAPI({ operation: 'finances.listFinancialEvents', query: { PostedAfter: '2020-03-01T00:00:00-07:00', PostedBefore: '2020-03-02T00:00:00-07:00' }, options: { raw_result: true } }); ``` -------------------------------- ### Create Feed Content Object Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Construct a feed object with `content` (as a string or file path) and `contentType`. This example shows an XML feed for updating inventory quantity. ```javascript let feed = { content: `
1.02 YOUR_MERCHANT_IDENTIFIER
Inventory 1 YOUR_SKU 10
`, contentType: 'text/xml; charset=utf-8' }; ``` -------------------------------- ### Enable Sandbox Mode for getPricing Operation Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Set `use_sandbox` to `true` in the constructor config to enable sandbox mode. This example demonstrates testing the `getPricing` operation in sandbox mode with a specific `MarketplaceId`. ```javascript let res = await spClient.callAPI({ operation: 'getPricing', endpoint: 'productPricing', query: { MarketplaceId: 'TEST_CASE_400' } }); ``` -------------------------------- ### Configure Proxy Agent for SP-API Client Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Use this snippet to configure a proxy agent when behind a firewall. Ensure 'hpagent' is installed. ```javascript const {HttpsProxyAgent} = require('hpagent'); const agent = new HttpsProxyAgent({proxy: 'http://x.x.x.x:zzzz'}); const spClient = new SellingPartner({ region: 'eu', refresh_token: '', options: { https_proxy_agent: agent } }); ``` -------------------------------- ### Retrieve Feed Upload Details Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Call the `createFeedDocument` operation to get the necessary details for uploading a feed. Ensure the `contentType` matches the feed's content type. ```javascript let feed_upload_details = await spClient.callAPI({ operation: 'createFeedDocument', endpoint: 'feeds', body: { contentType: feed.contentType } }); ``` -------------------------------- ### Call Grantless API Operation Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Execute a grantless API operation after obtaining the necessary access token. This example calls the `getDestinations` operation on the `notifications` endpoint. ```javascript let res = await spClient.callAPI({ operation: 'getDestinations', endpoint: 'notifications' }); ``` -------------------------------- ### Get Report Document and Download Report Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md This section explains how to manually retrieve report download details using `getReportDocument` and then use the `download` function to fetch and process the report content. It covers retrieving the report document, its structure, and how to use the `download` function with optional parameters. ```APIDOC ## getReportDocument and download ### Description This approach involves first retrieving the report document details using `getReportDocument` and then using the `download` function to fetch the report content. The `download` function can handle unzipping, decryption, and optional JSON transformation or saving to a file. ### Operation: getReportDocument #### Method `spClient.callAPI(options)` #### Parameters - **operation** (string) - Required - The API operation to call, set to 'getReportDocument'. - **endpoint** (string) - Required - The API endpoint, set to 'reports'. - **path** (object) - Required - Path parameters for the operation. - **reportDocumentId** (string) - Required - The ID of the report document to retrieve. ### Report Document Structure ```javascript { reportDocumentId:'', compressionAlgorithm:'GZIP', // Only included if report is compressed url: '' // Expires after 5 minutes! } ``` ### Operation: download #### Method `spClient.download(reportDocument, options)` #### Parameters - **reportDocument** (object) - Required - The report document object obtained from `getReportDocument`. - **options** (object) - Optional - Download configuration options, same as for the `download` object in `downloadReport`. - **json** (boolean) - Optional - Whether to transform the content to JSON. Defaults to false. - **unzip** (boolean) - Optional - Whether to unzip the content. Defaults to true. - **file** (string) - Optional - The absolute file path to save the report to. - **charset** (string) - Optional - The charset to use for decoding. Defaults to 'utf8'. - **timeouts** (object) - Optional - Allows setting timeouts for download requests (response, idle, deadline). ### Request Example (getReportDocument) ```javascript let report_document = await spClient.callAPI({ operation: 'getReportDocument', endpoint: 'reports', path: { reportDocumentId: '' } }); ``` ### Request Example (download) ```javascript // Download, decrypt, and unzip content let report = await spClient.download(report_document); // Download, transform to JSON, and save to disk let report = await spClient.download(report_document, { json: true, file: '/report.json' }); ``` ``` -------------------------------- ### Handle SP-API Errors with CustomError Source: https://context7.com/jrl84/amazon-sp-api/llms.txt All errors thrown by the library are instances of `CustomError` with `code`, `message`, and optional `details` properties. This example demonstrates a try-catch block to log these properties. ```javascript try { await spClient.callAPI({ operation: 'getOrder', endpoint: 'orders', path: { orderId: 'INVALID-ORDER-ID' } }); } catch (err) { // SP-API errors console.error(err.code); // e.g. 'InvalidInput', 'Unauthorized', 'QuotaExceeded' console.error(err.message); // human-readable description console.error(err.details); // additional context if available // Library-level error codes: // 'NO_VALID_REGION_PROVIDED' – bad region string // 'NO_REFRESH_TOKEN_PROVIDED' – missing refresh token // 'NO_ACCESS_TOKEN_PRESENT' – token not set and auto_request_tokens is false // 'CREDENTIALS_MISSING' – app client ID/secret not found // 'ENDPOINT_NOT_FOUND' – unknown endpoint name // 'INVALID_OPERATION_FOR_ENDPOINT'– operation not registered for endpoint // 'OPERATION_NOT_FOUND_FOR_VERSION'– version has no such operation and no fallback // 'API_RESPONSE_TIMEOUT' – response timeout exceeded // 'API_IDLE_TIMEOUT' – idle timeout exceeded // 'API_DEADLINE_TIMEOUT' – deadline timeout exceeded // 'JSON_PARSE_ERROR' – unexpected non-JSON response body // 'REPORT_PROCESSING_CANCELLED' – report cancelled after max retries } ``` -------------------------------- ### Call unsupported endpoint using api_path Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Use the `api_path` and `method` parameters to call endpoints or operations that are not yet directly supported by the client. This example calls the `getCatalogItem` operation using its direct API path. ```javascript let res = await spClient.callAPI({ api_path: '/catalog/2020-12-01/items/B084DWG2VQ', method: 'GET', query: { marketplaceIds: ['A1PA6795UKMFR9'], includedData: ['identifiers', 'images', 'productTypes', 'salesRanks', 'summaries', 'variations'] } }); ``` -------------------------------- ### Configure default endpoint versions in constructor Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Define default endpoint versions in the constructor configuration to avoid specifying the version for each API call. This example sets the `catalogItems` endpoint to use the `2020-12-01` version by default. ```javascript const spClient = new SellingPartner({ region: 'eu', refresh_token: '', endpoints_versions: { catalogItems: '2020-12-01' } }); ``` -------------------------------- ### SellingPartner Client with Credentials from File Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Create a SellingPartner client specifying a custom path for the credentials file. ```javascript // Credentials from file (default path ~/.amzspapi/credentials): // SELLING_PARTNER_APP_CLIENT_ID= // SELLING_PARTNER_APP_CLIENT_SECRET= const spClientFile = new SellingPartner({ region: 'fe', refresh_token: '', options: { credentials_path: '/etc/myapp/sp-credentials' } }); ``` -------------------------------- ### Manually Refresh Access Token Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Call this when auto_request_tokens is disabled to get a new access token. A scope can be provided for grantless tokens. ```javascript const spClient = new SellingPartner({ region: 'na', refresh_token: '', options: { auto_request_tokens: false } }); // Regular (seller-scoped) token await spClient.refreshAccessToken(); console.log(spClient.access_token); // 'Atza|...' // Grantless token for notifications await spClient.refreshAccessToken('sellingpartnerapi::notifications'); // Grantless token for application credential rotation await spClient.refreshAccessToken('sellingpartnerapi::client_credential:rotation'); ``` -------------------------------- ### Create Client and Call API Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Instantiate the SellingPartner client with your region and refresh token, then make an API call. Ensure you replace '' with your actual token. ```javascript (async () => { try { const spClient = new SellingPartner({ region: 'eu', // The region to use for the SP-API endpoints ("eu", "na" or "fe") refresh_token: '' // The refresh token of your app user }); let res = await spClient.callAPI({ operation: 'getMarketplaceParticipations', endpoint: 'sellers' }); console.log(res); } catch (e) { console.log(e); } })(); ``` -------------------------------- ### Instantiate SellingPartner Client (CommonJS) Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Import and create a SellingPartner client instance using CommonJS module syntax. ```javascript const SellingPartner = require('amazon-sp-api'); ``` -------------------------------- ### Instantiate Client and Call API Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md This snippet shows how to create an instance of the SellingPartner client with specified region and refresh token, and then how to call an API operation like 'getMarketplaceParticipations'. ```APIDOC ## Instantiate Client and Call API ### Description This example demonstrates how to initialize the `SellingPartner` client and make a call to the `getMarketplaceParticipations` operation. ### Method `spClient.callAPI(options)` ### Parameters #### Client Initialization Options - **region** (string) - Required - The region for the SP-API endpoints (e.g., "eu", "na", "fe"). - **refresh_token** (string) - Required - The refresh token of your app user. #### `callAPI` Options - **operation** (string) - Required - The name of the API operation to call (e.g., 'getMarketplaceParticipations'). - **endpoint** (string) - Required - The specific endpoint for the operation (e.g., 'sellers'). ### Request Example ```javascript // commonjs const SellingPartner = require('amazon-sp-api'); // esm import {SellingPartner} from 'amazon-sp-api'; (async () => { try { const spClient = new SellingPartner({ region: 'eu', refresh_token: '' }); let res = await spClient.callAPI({ operation: 'getMarketplaceParticipations', endpoint: 'sellers' }); console.log(res); } catch (e) { console.log(e); } })(); ``` ### Response #### Success Response The response will contain the data returned by the `getMarketplaceParticipations` operation. The exact structure depends on the API response. #### Response Example ```json { "example": "[Response data from getMarketplaceParticipations]" } ``` ``` -------------------------------- ### Set credentials via environment variables Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Configure your application's client ID and client secret using environment variables. Ensure these variables are set before initializing the client. ```bash SELLING_PARTNER_APP_CLIENT_ID= SELLING_PARTNER_APP_CLIENT_SECRET= ``` -------------------------------- ### Grantless Operations Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Perform operations that do not require a seller refresh token by setting `only_grantless_operations: true` and using a grantless token. Examples include managing notification destinations and subscriptions. ```APIDOC ## Grantless Operations — Notifications & Application Management Some operations require a grantless token (no seller `refresh_token` needed). Set `only_grantless_operations: true` and call `refreshAccessToken` with the appropriate scope. ```javascript const grantlessClient = new SellingPartner({ region: 'eu', options: { auto_request_tokens: false, only_grantless_operations: true } }); // Request grantless token for notifications scope await grantlessClient.refreshAccessToken('sellingpartnerapi::notifications'); // List notification destinations const destinations = await grantlessClient.callAPI({ operation: 'getDestinations', endpoint: 'notifications' }); // [ { destinationId: 'dest-123', name: 'MyQueue', resource: { sqs: { arn: 'arn:aws:...' } } } ] // Create an SQS notification destination const newDest = await grantlessClient.callAPI({ operation: 'createDestination', endpoint: 'notifications', body: { name: 'OrderChangeQueue', resourceSpecification: { sqs: { arn: 'arn:aws:sqs:eu-west-1:123456789012:my-sp-api-queue' } } } }); // Subscribe to ORDER_CHANGE notifications const subscription = await spClient.callAPI({ operation: 'createSubscription', endpoint: 'notifications', path: { notificationType: 'ORDER_CHANGE' }, body: { payloadVersion: '1.0', destinationId: newDest.destinationId } }); ``` ``` -------------------------------- ### Instantiate SellingPartner Client (ESM) Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Import and create a SellingPartner client instance using ECMAScript Modules (ESM) syntax. ```javascript import { SellingPartner } from 'amazon-sp-api'; ``` -------------------------------- ### API Call with Path and Query Parameters Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Demonstrates an API call that requires both path parameters (like ASIN) and query parameters (like marketplace ID). ```APIDOC ## API Call with Path and Query Parameters ### Description This example shows how to call an API operation that requires parameters in the path (e.g., ASIN) and also accepts query parameters like `marketplaceIds`. It also includes an `options` object to specify the API version. ### Method `spClient.callAPI` ### Parameters - **operation** (string) - Required - The name of the API operation, potentially using shorthand notation. - **path** (object) - Optional - An object containing key-value pairs for path parameters. - **asin** (string) - Required - The ASIN of the item. - **query** (object) - Optional - An object containing key-value pairs for query parameters. - **marketplaceIds** (array) - Required - An array of marketplace IDs. - **options** (object) - Optional - An object for additional options. - **version** (string) - Optional - The API version to use. ### Request Example ```javascript let res = await spClient.callAPI({ operation: 'catalogItems.getCatalogItem', path: { asin: 'B084J4QQFT' }, query: { marketplaceIds: ['A1PA6795UKMFR9'] }, options: { version: '2022-04-01' } }); ``` ``` -------------------------------- ### Full SellingPartner Client Configuration Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Create a SellingPartner client with a comprehensive configuration object, including region, tokens, endpoint versions, credentials, and various options. ```javascript // Full config with all options const spClientFull = new SellingPartner({ region: 'na', refresh_token: '', access_token: '', // optional — reuse an existing token endpoints_versions: { catalogItems: '2022-04-01', // pin specific endpoint versions globally orders: '2026-01-01' }, credentials: { SELLING_PARTNER_APP_CLIENT_ID: '', SELLING_PARTNER_APP_CLIENT_SECRET: '' }, options: { auto_request_tokens: true, // auto-refresh expired tokens (default: true) auto_request_throttled: true, // auto-retry throttled requests (default: true) version_fallback: true, // fall back to older version if op missing (default: true) use_sandbox: false, // use SP-API sandbox endpoint (default: false) only_grantless_operations: false, // skip refresh_token requirement (default: false) debug_log: false, // log retry/throttle events to console (default: false) return_as_payload: false, // wrap result in { payload, restore_rate } (default: false) retry_remote_timeout: true, // retry on ETIMEDOUT/ECONNRESET (default: true) timeouts: { response: 5000, // ms until first byte timeout idle: 10000, // ms between chunks timeout deadline: 30000 // ms total request timeout } } }); ``` -------------------------------- ### Initialize Grantless SP-API Client Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Instantiate the SellingPartner client for grantless operations only. Set `auto_request_tokens` to false and `only_grantless_operations` to true. This configuration does not require a `refresh_token`. ```javascript const spClient = new SellingPartner({ region: 'eu', options: { auto_request_tokens: false, only_grantless_operations: true } }); ``` -------------------------------- ### Call API Operation with Query Parameters Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Demonstrates calling an API operation with query parameters, including marketplace IDs, interval, and granularity. ```javascript let res = await spClient.callAPI({ operation: 'getOrderMetrics', endpoint: 'sales', query: { marketplaceIds: ['A1PA6795UKMFR9'], interval: '2020-10-01T00:00:00-07:00--2020-10-01T20:00:00-07:00', granularity: 'Hour' } }); ``` -------------------------------- ### Fallback to earlier endpoint version Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md When `version_fallback` is enabled (default), the client automatically attempts to use an earlier version of an operation if it's not found in the specified version. This example calls `listCatalogCategories` which might not be in the newer `catalogItems` version, but will fallback to `v0`. ```javascript let res = await spClient.callAPI({ operation: 'listCatalogCategories', endpoint: 'catalogItems', query: { MarketplaceId: 'A1PA6795UKMFR9', ASIN: 'B084DWG2VQ' } }); ``` -------------------------------- ### API Call with Options and Raw Result Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Shows how to use the `options` parameter, including setting `raw_result` to true, and handling potential errors. ```APIDOC ## API Call with Options and Raw Result ### Description This example demonstrates making an API call with various options, including `raw_result: true` to get the raw response, and includes comprehensive error handling for different API response timeout scenarios. ### Method `spClient.callAPI` ### Parameters - **operation** (string) - Required - The name of the API operation, potentially using shorthand notation. - **query** (object) - Optional - An object containing key-value pairs for query parameters. - **PostedAfter** (string) - Required - Timestamp after which to retrieve financial events. - **PostedBefore** (string) - Required - Timestamp before which to retrieve financial events. - **options** (object) - Optional - An object for additional options. - **raw_result** (boolean) - Optional - If true, returns the raw result object. - **version** (string) - Optional - The API version to use. - **timeouts** (object) - Optional - Configuration for request timeouts. - **response** (number) - Optional - Response timeout in milliseconds. - **idle** (number) - Optional - Idle timeout in milliseconds. - **deadline** (number) - Optional - Deadline timeout in milliseconds. ### Request Example ```javascript try { let res = await spClient.callAPI({ operation: 'finances.listFinancialEvents', query: { PostedAfter: '2020-03-01T00:00:00-07:00', PostedBefore: '2020-03-02T00:00:00-07:00' }, options: { raw_result: true } }); } catch (err) { if (err.code) { if (err.code === 'API_RESPONSE_TIMEOUT') console.log('SP-API ERROR: response timeout: ' + err.timeout + 'ms exceeded.', err.message); if (err.code === 'API_IDLE_TIMEOUT') console.log('SP-API ERROR: idle timeout: ' + err.timeout + 'ms exceeded.', err.message); if (err.code === 'API_DEADLINE_TIMEOUT') console.log('SP-API ERROR: deadline timeout: ' + err.timeout + 'ms exceeded.', err.message); } } ``` ``` -------------------------------- ### Configuring Endpoint Versions Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Shows how to configure default endpoint versions for an entire client instance using the `endpoints_versions` setting in the constructor. ```APIDOC ## Client Configuration with Default Endpoint Versions ### Description Configure the Selling Partner API client to use a specific version for all operations of a given endpoint by default. This avoids specifying the version in each `callAPI` request. ### Constructor Configuration ```javascript const spClient = new SellingPartner({ region: 'eu', refresh_token: '', endpoints_versions: { catalogItems: '2020-12-01' } }); ``` ### Usage When `endpoints_versions` is set, calls to operations within the specified endpoint (e.g., `catalogItems`) will automatically use the configured version ('2020-12-01' in this example) unless overridden in the `callAPI` options. ``` -------------------------------- ### SellingPartner Constructor Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Instantiates an authenticated SP-API client. Credentials can be provided via the constructor config, a credentials file, or environment variables. Supports various configuration options for region, tokens, endpoint versions, and client behavior. ```APIDOC ## `new SellingPartner(config)` — Constructor Creates an authenticated SP-API client instance. Credentials are resolved in priority order: constructor config object → credentials file (`~/.amzspapi/credentials`) → environment variables (`SELLING_PARTNER_APP_CLIENT_ID`, `SELLING_PARTNER_APP_CLIENT_SECRET`). ```javascript // CommonJS const SellingPartner = require('amazon-sp-api'); // ESM import { SellingPartner } from 'amazon-sp-api'; // Minimal setup — credentials from env vars const spClient = new SellingPartner({ region: 'eu', // required: 'eu' | 'na' | 'fe' refresh_token: process.env.SP_REFRESH_TOKEN }); // Full config with all options const spClientFull = new SellingPartner({ region: 'na', refresh_token: '', access_token: '', // optional — reuse an existing token endpoints_versions: { catalogItems: '2022-04-01', // pin specific endpoint versions globally orders: '2026-01-01' }, credentials: { SELLING_PARTNER_APP_CLIENT_ID: '', SELLING_PARTNER_APP_CLIENT_SECRET: '' }, options: { auto_request_tokens: true, // auto-refresh expired tokens (default: true) auto_request_throttled: true, // auto-retry throttled requests (default: true) version_fallback: true, // fall back to older version if op missing (default: true) use_sandbox: false, // use SP-API sandbox endpoint (default: false) only_grantless_operations: false, // skip refresh_token requirement (default: false) debug_log: false, // log retry/throttle events to console (default: false) return_as_payload: false, // wrap result in { payload, restore_rate } (default: false) retry_remote_timeout: true, // retry on ETIMEDOUT/ECONNRESET (default: true) timeouts: { response: 5000, // ms until first byte timeout idle: 10000, // ms between chunks timeout deadline: 30000 // ms total request timeout } } }); // Credentials from file (default path ~/.amzspapi/credentials): // SELLING_PARTNER_APP_CLIENT_ID= // SELLING_PARTNER_APP_CLIENT_SECRET= const spClientFile = new SellingPartner({ region: 'fe', refresh_token: '', options: { credentials_path: '/etc/myapp/sp-credentials' } }); ``` ``` -------------------------------- ### SP-API Client Configuration Object Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Use this object to configure the SP-API client constructor. Ensure all required properties like region and tokens are provided based on your authentication strategy. ```javascript { region:'', refresh_token:'', access_token:'', endpoints_versions:{ ... }, credentials:{ SELLING_PARTNER_APP_CLIENT_ID:'', SELLING_PARTNER_APP_CLIENT_SECRET:'' }, options:{ credentials_path:'~/.amzspapi/credentials', auto_request_tokens:true, auto_request_throttled:true, version_fallback:true, use_sandbox:false, only_grantless_operations:false, user_agent:'amazon-sp-api/ (Language=Node.js/; Platform=/)', debug_log:false, timeouts:{ ... }, retry_remote_timeout:true, https_proxy_agent: } } ``` -------------------------------- ### Download Report with Options Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Use this to download a report, transform it to JSON, and save it to a specified file path. The `interval` option allows for periodic re-requesting of the report. ```javascript let res = await sellingPartner.downloadReport({ body: { reportType: 'GET_FLAT_FILE_OPEN_LISTINGS_DATA', marketplaceIds: ['A1PA6795UKMFR9'] }, version: '2021-06-30', interval: 8000, download: { json: true, file: '/report.json' } }); ``` -------------------------------- ### API Call with Query Parameters Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Shows how to include query parameters in an API call, such as filtering by marketplace IDs and specifying a time interval. ```APIDOC ## API Call with Query Parameters ### Description This example demonstrates making an API call with specific query parameters to filter and refine the results, such as specifying `marketplaceIds`, `interval`, and `granularity`. ### Method `spClient.callAPI` ### Parameters - **operation** (string) - Required - The name of the API operation. - **endpoint** (string) - Required - The name of the API endpoint. - **query** (object) - Optional - An object containing key-value pairs for query parameters. - **marketplaceIds** (array) - Required - An array of marketplace IDs. - **interval** (string) - Required - The time interval for the query. - **granularity** (string) - Required - The granularity of the data. ### Request Example ```javascript let res = await spClient.callAPI({ operation: 'getOrderMetrics', endpoint: 'sales', query: { marketplaceIds: ['A1PA6795UKMFR9'], interval: '2020-10-01T00:00:00-07:00--2020-10-01T20:00:00-07:00', granularity: 'Hour' } }); ``` ``` -------------------------------- ### Sandbox Mode Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Enable sandbox mode by setting `use_sandbox: true` in the client options to test API calls with static predefined responses without affecting live data. ```APIDOC ## Sandbox Mode Enable sandbox mode to test API calls with static predefined responses without affecting live data. ```javascript const sandboxClient = new SellingPartner({ region: 'na', refresh_token: '', options: { use_sandbox: true } }); // Use sandbox-specific parameters as documented in Amazon SP-API docs const sandboxResult = await sandboxClient.callAPI({ operation: 'getPricing', endpoint: 'productPricing', query: { MarketplaceId: 'TEST_CASE_400' // sandbox test case triggers 400 error response } }); ``` ``` -------------------------------- ### GetCatalogItem Operation (v0) Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Demonstrates how to call the `getCatalogItem` operation using the `v0` version of the catalogItems endpoint. This version requires `asin` and `MarketplaceId` as input. ```APIDOC ## GET catalogItems (v0) ### Description Retrieves catalog item details using the v0 version of the catalogItems API. ### Method GET ### Endpoint /catalog/items ### Parameters #### Path Parameters - **asin** (string) - Required - The Amazon Standard Identification Number of the item. #### Query Parameters - **MarketplaceId** (string) - Required - The marketplace identifier. #### Options - **version** (string) - Optional - Specifies the API version, defaults to 'v0' if not provided. ### Request Example ```javascript let res = await spClient.callAPI({ operation: 'getCatalogItem', endpoint: 'catalogItems', query: { MarketplaceId: 'A1PA6795UKMFR9' }, path: { asin: 'B084DWG2VQ' }, options: { version: 'v0' } }); ``` ### Response #### Success Response (200) - **[Response fields depend on the specific API version and requested data]** #### Response Example ```json { "example": "[Response body for getCatalogItem v0]" } ``` ``` -------------------------------- ### Inspect Supported Endpoints with spClient.endpoints Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Use the `spClient.endpoints` getter to discover all available endpoints, their supported versions, and operations at runtime. This is useful for dynamic client configuration. ```javascript const allEndpoints = spClient.endpoints; // List all endpoint names console.log(Object.keys(allEndpoints)); // ['amazonWarehousingAndDistribution', 'aplusContent', 'catalogItems', 'orders', 'reports', ...] // Inspect an endpoint's versions and operations console.log(allEndpoints.catalogItems.__versions); // ['v0', '2020-12-01', '2022-04-01'] console.log(allEndpoints.catalogItems.__operations); // ['getCatalogItem', 'listCatalogCategories', 'searchCatalogItems'] console.log(allEndpoints.orders.__versions); // ['v0', '2026-01-01'] console.log(allEndpoints.reports.__versions); // ['2021-06-30'] ``` -------------------------------- ### ListCatalogCategories Operation with Fallback Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Demonstrates the `version_fallback` mechanism, where if an operation is not found in the specified or default endpoint version, the client attempts to use an earlier version. ```APIDOC ## GET catalogItems (with version fallback) ### Description Calls the `listCatalogCategories` operation. If the operation is not available in the currently configured or default version of the `catalogItems` endpoint, the client will automatically fallback to an earlier version (e.g., `v0`) if `version_fallback` is enabled (default behavior). ### Method GET ### Endpoint /catalog/items ### Parameters #### Query Parameters - **MarketplaceId** (string) - Required - The marketplace identifier. - **ASIN** (string) - Required - The Amazon Standard Identification Number. ### Request Example ```javascript let res = await spClient.callAPI({ operation: 'listCatalogCategories', endpoint: 'catalogItems', query: { MarketplaceId: 'A1PA6795UKMFR9', ASIN: 'B084DWG2VQ' } }); ``` ### Response #### Success Response (200) - **[Response fields depend on the specific API version and requested data]** #### Response Example ```json { "example": "[Response body for listCatalogCategories]" } ``` ``` -------------------------------- ### Configure Proxy Agent for HTTPS Requests Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Route all HTTPS requests through a proxy by providing an HttpsProxyAgent instance in the client options. Ensure the proxy URL is correctly formatted. ```javascript const { HttpsProxyAgent } = require('hpagent'); const agent = new HttpsProxyAgent({ proxy: 'http://proxy.mycompany.com:8080' }); const spClient = new SellingPartner({ region: 'eu', refresh_token: '', options: { https_proxy_agent: agent } }); ``` -------------------------------- ### Basic API Call Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Demonstrates a basic call to an SP-API operation using the `callAPI` method, specifying both the operation and the endpoint. ```APIDOC ## Basic API Call ### Description This example shows how to make a simple API call by specifying the operation and its corresponding endpoint. ### Method `spClient.callAPI` ### Parameters - **operation** (string) - Required - The name of the API operation to call. - **endpoint** (string) - Required - The name of the API endpoint the operation belongs to. ### Request Example ```javascript let res = await spClient.callAPI({ operation: 'getMarketplaceParticipations', endpoint: 'sellers' }); ``` ``` -------------------------------- ### Update App Credentials at Runtime Source: https://context7.com/jrl84/amazon-sp-api/llms.txt Replaces the Selling Partner API client's internal app credentials without needing to instantiate a new client. Ensure the new credentials are valid before updating. ```javascript spClient.updateCredentials({ SELLING_PARTNER_APP_CLIENT_ID: '', SELLING_PARTNER_APP_CLIENT_SECRET: '' }); ``` -------------------------------- ### API Call with Shorthand Notation Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md Illustrates using shorthand dot notation to specify the endpoint and operation in a single string. ```APIDOC ## API Call with Shorthand Notation ### Description This example demonstrates using a shorthand dot notation to combine the endpoint and operation names for a more concise API call. ### Method `spClient.callAPI` ### Parameters - **operation** (string) - Required - The name of the API operation, prefixed with the endpoint name using dot notation (e.g., 'endpoint.operation'). ### Request Example ```javascript let res = await spClient.callAPI({ operation: 'sellers.getMarketplaceParticipations' }); ``` ``` -------------------------------- ### Download Report Function Source: https://github.com/jrl84/amazon-sp-api/blob/main/README.md The `.downloadReport()` function simplifies the process of requesting and retrieving reports by internally orchestrating calls to `createReport`, `getReport`, `getReportDocument`, and a download function. It accepts a configuration object to customize the report download process. ```APIDOC ## downloadReport(config) ### Description Downloads a report by orchestrating `createReport`, `getReport`, and `getReportDocument` operations. ### Parameters #### Body Parameters - **config** (object) - Required - Configuration object for the download. - **body** (object) - Required - Parameters for requesting the report (similar to `createReport` operation). - **reportType** (string) - Required - The type of report to generate. - **marketplaceIds** (string array) - Required - A list of marketplace identifiers for the report. - **dataStartTime** (string) - Optional - The start of the date range for report data (ISO 8601 format). Defaults to now. - **dataEndTime** (string) - Optional - The end of the date range for report data (ISO 8601 format). Defaults to now. - **version** (string) - Optional - The version of the report endpoint. Defaults to '2021-06-30'. - **interval** (number) - Optional - Interval in milliseconds for re-requesting `getReport` if the report is still processing. Defaults to 10000. - **cancel_after** (number) - Optional - Cancels the report request after a specified number of retries. - **download** (object) - Optional - Parameters for downloading the report, such as enabling JSON output or saving to a file. ```