### GET Request with Query Parameters Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/configuration.md Example of a GET request including marketplaceIds and other query parameters. ```bash curl -X GET \ 'https://sellingpartnerapi-na.amazon.com/listings/2021-08-01/restrictions?asin=B08XXLG119&marketplaceIds=ATVPDKIKX0DER&sellerId=AXXXXXXXXXXX' \ -H 'Authorization: Bearer Azc5Sj...' \ -H 'User-Agent: MyApp/1.0' ``` -------------------------------- ### GET Request Example for Listings Restrictions Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/listings-restrictions-api.md This example demonstrates how to make a GET request to the Listings Restrictions API to check for restrictions on a specific ASIN across multiple marketplaces. Ensure you include the ASIN, seller ID, and marketplace IDs. ```http GET https://sellingpartnerapi-na.amazon.com/listings/2021-08-01/restrictions ?asin=B08XXLG119 &sellerId=AXXXXXXXXXXX &marketplaceIds=ATVPDKIKX0DER,A2Q3Y263D00KWC &reasonLocale=en_US ``` -------------------------------- ### GET Listings Restrictions Request Example Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/endpoints.md Example of a GET request to retrieve listings restrictions for a catalog item. Ensure you include the necessary authorization header. ```http GET https://sellingpartnerapi-na.amazon.com/listings/2021-08-01/restrictions?asin=B08XXLG119&sellerId=AXXXXXXXXXXX&marketplaceIds=ATVPDKIKX0DER Authorization: Bearer {accessToken} ``` -------------------------------- ### Price Structure Example Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/feeds-api.md Defines the structure for item pricing, including currency and value. ```JSON "price": [ { "currency": "USD", "value": 19.99 } ] ``` -------------------------------- ### Fulfillment Availability Structure Example Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/feeds-api.md Specifies stock and fulfillment channel information, including quantity. ```JSON "fulfillment_availability": [ { "fulfillment_channel_code": "DEFAULT", "quantity": 100 }, { "fulfillment_channel_code": "AFN", "quantity": 50 } ] ``` -------------------------------- ### JSON Request Body Example Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/configuration.md Demonstrates the structure of a JSON request body, including nested objects and arrays. ```json { "field1": "value1", "field2": 123, "field3": true, "nestedObject": { "subField": "subValue" }, "arrayField": [1, 2, 3] } ``` -------------------------------- ### Price Format Example Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md When representing prices, use a string format with decimals, not a numerical type. ```string "19.99" ``` -------------------------------- ### Example Response (Restrictions Exist) Source: https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/use-case-guides/listings-restrictions-api-use-case-guide/listings-restrictions-api-use-case-guide_2021-08-01.md When restrictions exist, the 'reasons' array provides details including a 'reasonCode' (e.g., APPROVAL_REQUIRED), a message, and relevant 'links' for further action. ```json { "restrictions": [ { "marketplaceId": "ATVPDKIKX0DER", "conditionType": "collectible_like_new", "reasons": [ { "reasonCode": "APPROVAL_REQUIRED", "message": "You cannot list the product in this condition.", "links": [ { ``` -------------------------------- ### 400 Bad Request - Invalid ASIN Example Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/errors.md An example of an 'InvalidInput' error where the provided ASIN does not conform to the expected format. ```json { "errors": [ { "code": "InvalidInput", "message": "Parameter 'asin' is not a valid ASIN format", "details": { "parameterName": "asin", "parameterValue": "INVALID" } } ] } ``` -------------------------------- ### 404 Not Found Error Response Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/listings-restrictions-api.md Example of a 404 Not Found error response, which can occur if the selling partner or ASIN is not found. ```json { "errors": [ { "code": "NotFound", "message": "Selling partner or ASIN not found" } ] } ``` -------------------------------- ### 400 Bad Request - Missing Required Parameter Example Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/errors.md An example of an 'InvalidInput' error indicating that a required parameter, such as 'sellerId', was omitted from the request. ```json { "errors": [ { "code": "InvalidInput", "message": "Required parameter 'sellerId' is missing" } ] } ``` -------------------------------- ### Check Listing Restrictions (Python) Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md Example of how to check for listing restrictions before creating a listing. This snippet demonstrates the usage of the Listings Restrictions API in Python. ```python from sp_api.api import listings_restrictions def check_restrictions(): params = { 'asin': 'B0EXAMPLEASIN', 'marketplaceIds': ['ATVPDKIKX0DER'], 'conditionType': 'new', 'reasonLocale': 'en_US' } try: response = listings_restrictions.getListingsRestrictions(params=params) print(response.payload) except Exception as e: print(f'Error checking restrictions: {e}') check_restrictions() ``` -------------------------------- ### Example of ASIN Not Found Error Response Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/errors.md This JSON response indicates a 404 Not Found error, typically when a specified ASIN does not exist in the catalog. ```json { "errors": [ { "code": "NotFound", "message": "ASIN 'B08XXLG119' not found in catalog" } ] } ``` -------------------------------- ### 403 Forbidden Error Example - Missing Role Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/errors.md An example of a 'Forbidden' error indicating that the selling partner lacks a required role for the requested operation. ```json { "errors": [ { "code": "Forbidden", "message": "Selling partner lacks required Product Listing role" } ] } ``` -------------------------------- ### Check Listing Restrictions (JavaScript) Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md Example of how to check for listing restrictions before creating a listing. This snippet demonstrates the usage of the Listings Restrictions API in JavaScript. ```javascript const listingsRestrictions = require('amazon-sp-api').listingsRestrictions; async function checkRestrictions() { const params = { asin: 'B0EXAMPLEASIN', marketplaceIds: ['ATVPDKIKX0DER'], conditionType: 'new', reasonLocale: 'en_US' }; try { const data = await listingsRestrictions(params); console.log(JSON.stringify(data, null, 2)); } catch (error) { console.error('Error checking restrictions:', error); } } checkRestrictions(); ``` -------------------------------- ### POST Request with JSON Body Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/configuration.md Example of a POST request with a JSON payload, including feed type, marketplace IDs, and input document ID. ```bash curl -X POST \ 'https://sellingpartnerapi-na.amazon.com/feeds/2021-06-30/feeds' \ -H 'Authorization: Bearer Azc5Sj...' \ -H 'Content-Type: application/json' \ -H 'User-Agent: MyApp/1.0' \ -d '{ "feedType": "JSON_LISTINGS_FEED", "marketplaceIds": ["ATVPDKIKX0DER"], "inputFeedDocumentId": "docId123" }' ``` -------------------------------- ### Check Current Authorizations Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/roles-and-authorization.md Example using curl to check current authorizations by making a GET request to the application's authorization page. Requires a session cookie. ```bash curl -X GET \ 'https://sellercentral.amazon.com/gp/mcas-portal/developer/applications/my-app' \ -H 'Cookie: {session-cookie}' ``` -------------------------------- ### Success Response for GetListingsRestrictions Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/endpoints.md Example of a successful JSON response when restrictions are found for a listing. This includes marketplace ID, condition type, and reasons for the restriction. ```json { "restrictions": [ { "marketplaceId": "ATVPDKIKX0DER", "conditionType": "new_new", "reasons": [ { "reasonCode": "APPROVAL_REQUIRED", "message": "You need approval to list.", "links": [ { "resource": "https://sellercentral.amazon.com/hz/approvalrequest/restrictions/approve?asin=B08XXLG119", "verb": "GET", "title": "Request Approval via Seller Central.", "type": "text/html" } ] } ] } ] } ``` -------------------------------- ### 401 Unauthorized Error Example Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/errors.md This JSON shows an example of an 'Unauthorized' error, typically indicating an expired or invalid access token. ```json { "errors": [ { "code": "Unauthorized", "message": "Access token is expired or invalid" } ] } ``` -------------------------------- ### Create Listing via Listings Items API Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/examples-and-patterns.md If no restrictions are found, use the Listings Items API to create a new listing. This example shows a PUT request to create or update a listing item. ```bash PUT https://sellingpartnerapi-na.amazon.com/listings/2021-08-01/items/AXXXXXXXXXXX/MYSKU001 Body: { "attributes": { "item_type_name": "Luggage", "brand_name": "TravelPro", "price": [ { "currency": "USD", "value": 129.99 } ] } } ``` -------------------------------- ### Empty Response for GetListingsRestrictions Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/endpoints.md Example of a JSON response when no restrictions are found for a listing. The 'restrictions' array may be empty or contain an empty object. ```json { "restrictions": [ { } ] } ``` -------------------------------- ### 400 Bad Request - Invalid Marketplace Example Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/errors.md This JSON demonstrates an 'InvalidInput' error when an invalid marketplace ID is provided in the request. ```json { "errors": [ { "code": "InvalidInput", "message": "Marketplace 'XX' is not valid", "details": { "parameterName": "marketplaceIds", "validValues": ["ATVPDKIKX0DER", "A2Q3Y263D00KWC", "A1AM78C64UB0YL"] } } ] } ``` -------------------------------- ### Example Feed JSON Structure Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/feeds-api.md This JSON structure represents a feed payload for updating product listings. It includes header information and a list of messages, each detailing a product update. ```json { "header": { "sellerId": "AXXXXXXXXXXX", "version": "2.0" }, "messages": [ { "messageId": 1, "sku": "PROD-001", "operationType": "UPDATE", "productType": "SHOES", "attributes": { "item_type_name": "Running Shoes", "brand_name": "SneakerCo", "price": [ { "currency": "USD", "value": 89.99 } ] } } ] } ``` -------------------------------- ### Success Response with Restrictions Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/listings-restrictions-api.md Example JSON response indicating that restrictions exist for an item in specific marketplaces and conditions. It includes details about the reason for the restriction and a link to request approval. ```json { "restrictions": [ { "marketplaceId": "ATVPDKIKX0DER", "conditionType": "new_new", "reasons": [ { "reasonCode": "APPROVAL_REQUIRED", "message": "You need approval to list.", "links": [ { "resource": "https://sellercentral.amazon.com/hz/approvalrequest/restrictions/approve?asin=B08XXLG119", "verb": "GET", "title": "Request Approval via Seller Central.", "type": "text/html" } ] } ] }, { "marketplaceId": "ATVPDKIKX0DER", "conditionType": "used_like_new", "reasons": [ { "reasonCode": "APPROVAL_REQUIRED", "message": "You cannot list the product in this condition.", "links": [ { "resource": "https://sellercentral.amazon.com/hz/approvalrequest/restrictions/approve?asin=B08XXLG119", "verb": "GET", "title": "Request Approval via Seller Central.", "type": "text/html" } ] } ] } ] } ``` -------------------------------- ### Example Response for Listings Restrictions Source: https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/use-case-guides/listings-restrictions-api-use-case-guide/listings-restrictions-api-use-case-guide_2021-08-01.md This JSON structure represents a typical response when checking listing restrictions for an item, indicating reasons for restriction and providing links for further action. ```json { "reasonCode": "APPROVAL_REQUIRED", "message": "You cannot list the product in this condition.", "links": [ { "resource": "https://sellercentral.amazon.com/hz/approvalrequest/restrictions/approve?asin=B08XXLG119", "verb": "GET", "title": "Request Approval via Seller Central.", "type": "text/html" } ] } ``` -------------------------------- ### Example of Feed Not Ready Error Response Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/errors.md This JSON response signifies a 404 Not Found error, indicating that the requested feed submission result is not yet available. ```json { "errors": [ { "code": "NotFound", "message": "Feed submission result not yet available. Check feed status." } ] } ``` -------------------------------- ### Query String Building (JavaScript) Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md A helper function to construct URL query strings from an object of parameters. This is a common requirement when making GET requests to APIs. ```javascript function buildQueryString(params) { if (!params) return ''; const esc = encodeURIComponent; const query = Object.keys(params) .map(k => esc(k) + '=' + esc(params[k])) .join('&'); return query ? `?${query}` : ''; } // Example Usage: const queryParams = { asin: 'B0EXAMPLEASIN', marketplaceIds: 'ATVPDKIKX0DER', conditionType: 'new' }; const queryString = buildQueryString(queryParams); console.log('Query String:', queryString); const emptyParams = {}; console.log('Empty Params Query String:', buildQueryString(emptyParams)); ``` -------------------------------- ### Create Feed API Request Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/feeds-api.md This is an example of a POST request to the createFeed endpoint. It specifies the feed type, marketplace IDs, and the input feed document ID. ```http POST /feeds/2021-06-30/feeds { "feedType": "JSON_LISTINGS_FEED", "marketplaceIds": ["ATVPDKIKX0DER"], "inputFeedDocumentId": "documentId123" } ``` -------------------------------- ### Listings Restrictions API - Get Listings Restrictions Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/listings-restrictions-api.md Retrieves a list of restrictions for a given ASIN in a specific marketplace. This is the primary method for checking if a product can be listed. ```APIDOC ## GET /listings/2021-08-01/restrictions ### Description Retrieves a list of restrictions for a given ASIN in a specific marketplace. This is the primary method for checking if a product can be listed. ### Method GET ### Endpoint /listings/2021-08-01/restrictions ### Parameters #### Query Parameters - **marketplaceIds** (string) - Required - A list of marketplace identifiers. Example: ["A2EUQ1WTGCTBG2"] - **asins** (string) - Required - A list of ASINs to check for restrictions. Example: ["B0EXAMPLE1"] ### Request Example { "marketplaceIds": ["A2EUQ1WTGCTBG2"], "asins": ["B0EXAMPLE1"] } ### Response #### Success Response (200) - **asin** (string) - The ASIN of the product. - **condition** (string) - The condition of the product (e.g., `new_new`, `used_like_new`). - **restrictions** (array) - A list of restrictions for the product. - **reasonCode** (string) - The code indicating the reason for the restriction. - **message** (string) - A human-readable message describing the restriction. - **links** (array) - A list of links to resolve the restriction, if applicable. - **resource** (string) - URL to request approval. - **verb** (string) - HTTP method (usually GET). - **title** (string) - Human-readable description of the action. - **type** (string) - Content type (usually "text/html"). #### Response Example { "data": [ { "asin": "B0EXAMPLE1", "condition": "new_new", "restrictions": [ { "reasonCode": "APPROVAL_REQUIRED", "message": "Seller approval required for this product.", "links": [ { "resource": "https://sellercentral.amazon.com/gp/..., "verb": "GET", "title": "Request Approval", "type": "text/html" } ] } ] } ] } #### Error Responses - **400 Bad Request**: Invalid input parameters. - **401 Unauthorized**: Access token is expired or invalid. - **403 Forbidden**: Selling partner lacks required Product Listing role. - **404 Not Found**: Selling partner or ASIN not found. - **429 Too Many Requests**: Request rate limit exceeded. ``` -------------------------------- ### Handling Insufficient Permissions Error Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/roles-and-authorization.md Example of an HTTP 403 Forbidden response when a selling partner lacks the required role for an operation. The response body includes an error code and message. ```json { "errors": [ { "code": "Forbidden", "message": "Selling partner lacks required [RoleName] role" } ] } ``` -------------------------------- ### Repository Structure Overview Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md This is a representation of the Selling Partner API documentation repository structure, outlining key directories and files. ```tree / ├── README.md (Deprecated - redirects to new site) ├── guides/ (Deprecated use-case guides) │ ├── en-US/ │ │ ├── developer-guide/ │ │ ├── migration-guide/ │ │ └── use-case-guides/ │ └── [other-languages]/ ├── references/ (API reference documents) │ ├── feeds-api/ (Feeds API with JSON schemas) │ │ ├── schemas/ │ │ │ └── JSON_LISTINGS_FEED/ │ │ │ ├── listings-feed-schema-v2.json │ │ │ ├── listings-feed-message-schema-v2.json │ │ │ └── listings-feed-processing-report-schema-v2.json │ │ └── feeds_*.md (API reference) │ ├── listings-restrictions-api/ (Listings Restrictions API) │ └── [other-apis]/ ``` -------------------------------- ### Basic Workflow for Listings Restrictions API Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/listings-restrictions-api.md Outlines the fundamental steps for interacting with the Listings Restrictions API, from obtaining an ASIN to proceeding with listing creation. ```text 1. Get ASIN for desired product ↓ 2. Call getListingsRestrictions with ASIN ↓ 3. Evaluate response: - No restrictions → Proceed to create listing via Listings Items API - Restrictions exist: * reasonCode = APPROVAL_REQUIRED → Direct seller to approval link * Other reasonCode → Inform seller of restriction ↓ 4. If approval obtained, proceed with listing creation ``` -------------------------------- ### Get Feed Status Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/feeds-api.md Retrieves the status of a previously submitted feed. You can poll this endpoint until the feed status is 'DONE' or 'CANCELLED'. ```APIDOC ## GET /feeds/2021-06-30/feeds/{feedId} ### Description Retrieves the status of a previously submitted feed. You can poll this endpoint until the feed status is 'DONE' or 'CANCELLED'. ### Method GET ### Endpoint /feeds/2021-06-30/feeds/{feedId} ### Parameters #### Path Parameters - **feedId** (string) - Required - The identifier of the feed to retrieve status for. ``` -------------------------------- ### OAuth 2.0 Flow Steps Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md Outlines the steps involved in the OAuth 2.0 authorization flow for obtaining access tokens. ```text 1. Register application → Get Client ID, Client Secret 2. Direct seller to authorization URL 3. Seller grants permissions 4. Receive authorization code 5. Exchange code for access + refresh tokens 6. Use access token in API requests 7. Refresh token when it expires ``` -------------------------------- ### 429 Too Many Requests Error Response Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/listings-restrictions-api.md Example of a 429 Too Many Requests error response, indicating that the request rate limit has been exceeded. ```json { "errors": [ { "code": "Throttled", "message": "Request rate limit exceeded" } ] } ``` -------------------------------- ### LISTING_PRODUCT_ONLY Requirements Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/feeds-api.md Use this requirement when submitting product information without pricing or offers. ```JSON "requirements": "LISTING_PRODUCT_ONLY" ``` -------------------------------- ### Get Feed Submission Result Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/feeds-api.md Downloads the processing report for a completed feed. This report contains details about the success or failure of the feed processing. ```APIDOC ## GET /feeds/2021-06-30/feeds/{feedId}/result ### Description Downloads the processing report for a completed feed. This report contains details about the success or failure of the feed processing. ### Method GET ### Endpoint /feeds/2021-06-30/feeds/{feedId}/result ### Parameters #### Path Parameters - **feedId** (string) - Required - The identifier of the feed for which to retrieve the result. ``` -------------------------------- ### 400 Bad Request Error Response Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/listings-restrictions-api.md Example of a 400 Bad Request error response indicating invalid input, such as an incorrectly formatted ASIN. ```json { "errors": [ { "code": "InvalidInput", "message": "Parameter 'asin' is not a valid ASIN format" } ] } ``` -------------------------------- ### Create Feed Submission Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/examples-and-patterns.md Initiate a feed submission using the uploaded document ID and specify the target marketplace IDs. The response contains the feed ID for tracking. ```bash POST https://sellingpartnerapi-na.amazon.com/feeds/2021-06-30/feeds Headers: Authorization: Bearer Azc5Sj7iVJb2E... Content-Type: application/json Body: { "feedType": "JSON_LISTINGS_FEED", "marketplaceIds": ["ATVPDKIKX0DER", "A2Q3Y263D00KWC"], "inputFeedDocumentId": "amzn1.sp-doc-id-123456" } ``` -------------------------------- ### Get Feed Document Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/feeds-api.md Downloads the content of a feed or a processing report document. This is used to retrieve feed content before submission or to download the result report. ```APIDOC ## GET /feeds/2021-06-30/documents/{documentId} ### Description Downloads the content of a feed or a processing report document. This is used to retrieve feed content before submission or to download the result report. ### Method GET ### Endpoint /feeds/2021-06-30/documents/{documentId} ### Parameters #### Path Parameters - **documentId** (string) - Required - The identifier of the document to retrieve. ``` -------------------------------- ### Exponential Backoff Strategy Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/configuration.md Illustrates an exponential backoff strategy for handling rate limiting and network timeouts, with a maximum wait time. ```text Wait 1 second, retry Wait 2 seconds, retry Wait 4 seconds, retry Wait 8 seconds, retry ...maximum wait of 60 seconds ``` -------------------------------- ### createFeed Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/endpoints.md Creates a feed submission for bulk data operations. This is an asynchronous process. ```APIDOC ## POST /feeds/2021-06-30/feeds ### Description Create a feed submission for bulk data operations. ### Method POST ### Endpoint /feeds/2021-06-30/feeds ### Request Body `CreateFeedRequest` ### Response Schema `CreateFeedResponse` ### Authorization Required Appropriate role for feed type ``` -------------------------------- ### Response - Feed Processing Status Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/examples-and-patterns.md This response shows the current processing status of a feed, including start time. The status can be 'PROCESSING', 'DONE', or 'FAILED'. ```json { "feedId": "4ec62e5e-cfb2-4f20-b893-c6d2e98b0f42", "feedType": "JSON_LISTINGS_FEED", "processingStatus": "PROCESSING", "processingStartTime": "2024-05-29T10:00:00Z" } ``` -------------------------------- ### Minimize API Scopes Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/roles-and-authorization.md Illustrates how to define and use only the necessary scopes for API requests, adhering to the principle of least privilege. ```javascript const requiredScopes = ['sellingpartnerapi::orders::v1']; // Only what's needed const unnecessaryScopes = [ 'sellingpartnerapi::finances::v1', // Not needed 'sellingpartnerapi::messaging::v1' // Not needed ]; ``` -------------------------------- ### LISTING_OFFER_ONLY Requirements Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/feeds-api.md Use this requirement for offer-only listings, providing only sales terms like pricing and availability. ```JSON "requirements": "LISTING_OFFER_ONLY" ``` -------------------------------- ### Example of Feed Processing Errors Response Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/errors.md This JSON structure details issues encountered during feed processing, including severity, error codes, and affected attributes. ```json { "header": { "sellerId": "AXXXXXXXXXXX", "version": "2.0", "feedId": "feed-123" }, "issues": [ { "messageId": 1, "severity": "ERROR", "code": "MISSING_REQUIRED_ATTRIBUTE", "message": "'brand_name' is required but not supplied.", "attributeName": "brand_name" }, { "messageId": 2, "severity": "WARNING", "code": "VALUE_OUT_OF_RANGE", "message": "Quantity exceeds maximum allowed value", "attributeName": "quantity" } ], "summary": { "errors": 1, "warnings": 1, "messagesProcessed": 2, "messagesAccepted": 1, "messagesInvalid": 1 } } ``` -------------------------------- ### LISTING Requirements Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/feeds-api.md Specifies the default 'LISTING' requirements, indicating that product facts and sales terms are necessary for a complete listing submission. ```json "requirements": "LISTING" ``` -------------------------------- ### Example of Malformed JSON Error Response Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/errors.md This JSON structure indicates a 400 Bad Request error due to invalid JSON syntax or data types. ```json { "errors": [ { "code": "InvalidInput", "message": "Request body contains invalid JSON: unexpected character at line 2, column 5" } ] } ``` -------------------------------- ### OAuth 2.0 with Token Refresh (JavaScript) Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md Implementation of the OAuth 2.0 flow with automatic token refresh using the SellingPartnerAPIClient in JavaScript. This pattern ensures continuous API access. ```javascript const SellingPartner = require('amazon-sp-api'); async function getOAuthClient() { const sp = new SellingPartner({ region: 'na', refresh_token: 'YOUR_REFRESH_TOKEN', client_id: 'YOUR_CLIENT_ID', client_secret: 'YOUR_CLIENT_SECRET', aws_access_key_id: 'YOUR_AWS_ACCESS_KEY_ID', aws_secret_access_key: 'YOUR_AWS_SECRET_ACCESS_KEY', aws_session_token: 'YOUR_AWS_SESSION_TOKEN' }); return sp; } async function callApiWithAuth() { try { const spClient = await getOAuthClient(); // Example: Call a protected API endpoint // const orders = await spClient.orders.getOrders({ marketplaceIds: ['ATVPDKIKX0DER'] }); // console.log(orders); console.log('OAuth client initialized. Token refresh handled automatically.'); } catch (error) { console.error('Error during OAuth flow:', error); } } callApiWithAuth(); ``` -------------------------------- ### Check Listing Restrictions Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/examples-and-patterns.md Use this endpoint to check if a product is restricted for listing in specific marketplaces before attempting to create a listing. It helps prevent errors by identifying approval requirements upfront. ```bash GET https://sellingpartnerapi-na.amazon.com/listings/2021-08-01/restrictions ?asin=B08XXLG119 &sellerId=AXXXXXXXXXXX &marketplaceIds=ATVPDKIKX0DER,A2Q3Y263D00KWC &reasonLocale=en_US Headers: Authorization: Bearer Azc5Sj7iVJb2E... User-Agent: MyListingApp/1.0 ``` -------------------------------- ### SellingPartnerListingsFeed Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/types.md Represents a complete feed submission for product listings, including a header and a list of messages. ```APIDOC ## SellingPartnerListingsFeed ### Description Complete feed submission containing header and messages. ### Schema ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Selling Partner Listings Feed (v2)", "type": "object", "required": ["header", "messages"], "properties": { "header": { "type": "object", "title": "Feed Header", "required": ["sellerId", "version"] }, "messages": { "type": "array", "title": "Feed Messages", "minItems": 1 } } } ``` ### Properties | Property | Type | Required | Description | |----------|------|----------|-------------| | header | FeedHeader | Yes | Metadata about the feed submission | | messages | FeedMessage[] | Yes | Array of listing update messages (minimum 1) | ### Used By Top-level feed submission to Feeds API ``` -------------------------------- ### Bulk Listing Update via Feeds API (JavaScript) Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md Demonstrates how to perform a bulk listing update using the Feeds API in JavaScript. This involves creating a feed with 'UPDATE' message operation types. ```javascript const feeds = require('amazon-sp-api').feeds; async function updateListings() { const feedType = '_POST_PRODUCT_DATA_'; const feedContents = { "header": { "version": "1.0", "sellerId": "YOUR_SELLER_ID" }, "messages": [ { "messageType": "Product", "messageId": 1, "product": { "sku": "SKU123", "attributes": { "product_type": "object.product.clothing", "item_name": "Example T-Shirt", "brand_name": "ExampleBrand" } } } ] }; try { const data = await feeds.createFeed(feedType, feedContents); console.log('Feed created:', JSON.stringify(data, null, 2)); } catch (error) { console.error('Error creating feed:', error); } } updateListings(); ``` -------------------------------- ### 403 Forbidden Error Example - PII Access Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/errors.md This JSON illustrates a 'Forbidden' error when attempting to access Personally Identifiable Information (PII) without a required Restricted Data Token. ```json { "errors": [ { "code": "Forbidden", "message": "Restricted data token required for accessing PII" } ] } ``` -------------------------------- ### Marketplace Code Lookup (JavaScript) Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md A utility function to get the correct marketplace ID based on a country code or name. This is useful for constructing API requests that target specific marketplaces. ```javascript const marketplaceMap = { 'US': 'ATVPDKIKX0DER', 'CA': 'A2EUQ1WTGCTBG2', 'MX': 'A1AM78C64UM0Y6', 'UK': 'A1F83G8C2ARO1P', 'DE': 'A1PA6795UKMFR9', 'FR': 'A13VMI1ZPCK2YQ', 'ES': 'A1RKKUPIHCE830', 'IT': 'APJ6J863Y6D80', 'AE': 'AE0135R67994X', 'AU': 'A39IBJ373P6080', 'BR': 'A2Q3Y263Y0X305', 'JP': 'A1VC38T4GH8LZG', 'SG': 'A19VA1974W7UGQ', 'IN': 'A21TJCEPYNUROK' }; function getMarketplaceId(countryCodeOrName) { const code = countryCodeOrName.toUpperCase(); return marketplaceMap[code] || null; } // Example Usage: console.log('US Marketplace ID:', getMarketplaceId('US')); console.log('Germany Marketplace ID:', getMarketplaceId('DE')); console.log('Unknown Marketplace ID:', getMarketplaceId('XYZ')); ``` -------------------------------- ### Response - No Listing Restrictions Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/examples-and-patterns.md This JSON response indicates that there are no restrictions for the specified ASIN in the given marketplaces. ```json { "restrictions": [ {} ] } ``` -------------------------------- ### Get Listings Restrictions for an Item Source: https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/use-case-guides/listings-restrictions-api-use-case-guide/listings-restrictions-api-use-case-guide_2021-08-01.md Call the getListingsRestrictions operation to return any listings restrictions for a given ASIN. This requires the ASIN, seller ID, and marketplace IDs. The conditionType and reasonLocale are optional. ```http https://sellingpartnerapi-na.amazon.com/listings/2021-08-01/restrictions ?asin=B08XXLG119 &conditionType= &sellerId=AXXXXXXXXXXX &marketplaceIds=ATVPDKIKX0DER ``` -------------------------------- ### Feed Processing with Status Polling (JavaScript) Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md Illustrates a complete feed submission workflow, including creating a feed, submitting it, and then polling for its processing status using the Feeds API. This ensures you know when your data has been processed. ```javascript const feeds = require('amazon-sp-api').feeds; async function processFeed(feedType, feedContents) { try { // 1. Create and submit the feed const createFeedResponse = await feeds.createFeed(feedType, feedContents); const feedId = createFeedResponse.payload.feedId; console.log(`Feed submitted with ID: ${feedId}`); // 2. Poll for status let feedStatus = 'IN_PROGRESS'; while (feedStatus === 'IN_PROGRESS' || feedStatus === 'SUBMITTED') { await new Promise(resolve => setTimeout(resolve, 60000)); // Wait 1 minute const getFeedResponse = await feeds.getFeed(feedId); feedStatus = getFeedResponse.payload.processingReport.processingStatus; console.log(`Feed status: ${feedStatus}`); } if (feedStatus === 'DONE') { console.log('Feed processing complete.'); // Optionally, get the feed document // const getFeedDocumentResponse = await feeds.getFeedDocument(feedId); // console.log('Feed document:', getFeedDocumentResponse); } else { console.error('Feed processing failed or cancelled.'); } } catch (error) { console.error('Error during feed processing:', error); } } // Example usage: const exampleFeedType = '_POST_PRODUCT_DATA_'; const exampleFeedContents = { "header": {"version": "1.0", "sellerId": "YOUR_SELLER_ID"}, "messages": [{"messageType": "Product", "messageId": 1, "product": {"sku": "SKU456", "attributes": {"item_name": "Test Item"}}}] }; // processFeed(exampleFeedType, exampleFeedContents); // Uncomment to run ``` -------------------------------- ### Selling Partner API Client Implementation Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/examples-and-patterns.md This JavaScript class encapsulates the OAuth 2.0 authorization flow and API request logic for the Selling Partner API. It handles generating authorization URLs, exchanging codes for tokens, refreshing tokens, and making authenticated requests. ```javascript class SellingPartnerAPIClient { constructor(clientId, clientSecret, redirectUri) { this.clientId = clientId; this.clientSecret = clientSecret; this.redirectUri = redirectUri; this.accessToken = null; this.refreshToken = null; this.tokenExpiration = null; } // Generate authorization URL for seller getAuthorizationUrl(state) { const params = new URLSearchParams({ client_id: this.clientId, response_type: 'code', redirect_uri: this.redirectUri, state: state, scopes: [ 'sellingpartnerapi::sellers::v1', 'sellingpartnerapi::orders::v1', 'sellingpartnerapi::finances::v1' ].join(' ') }); return `https://sellercentral.amazon.com/apps/authorize?${params}`; } // Exchange authorization code for tokens async exchangeAuthorizationCode(authorizationCode) { const response = await fetch('https://api.amazon.com/auth/o2/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', code: authorizationCode, client_id: this.clientId, client_secret: this.clientSecret, redirect_uri: this.redirectUri }) }); const data = await response.json(); if (data.error) { throw new Error(`Authorization failed: ${data.error}`); } this.accessToken = data.access_token; this.refreshToken = data.refresh_token; this.tokenExpiration = Date.now() + (data.expires_in * 1000); return data; } // Refresh access token when expired async ensureValidToken() { if (Date.now() < this.tokenExpiration - 60000) { return this.accessToken; // Token still valid (60 sec buffer) } const response = await fetch('https://api.amazon.com/auth/o2/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: this.refreshToken, client_id: this.clientId, client_secret: this.clientSecret }) }); const data = await response.json(); if (data.error) { throw new Error(`Token refresh failed: ${data.error}`); } this.accessToken = data.access_token; this.tokenExpiration = Date.now() + (data.expires_in * 1000); return this.accessToken; } // Make authenticated API request async request(method, path, body = null) { const token = await this.ensureValidToken(); const options = { method: method, headers: { 'Authorization': `Bearer ${token}`, 'User-Agent': 'MyApp/1.0' } }; if (body) { options.headers['Content-Type'] = 'application/json'; options.body = JSON.stringify(body); } const response = await fetch( `https://sellingpartnerapi-na.amazon.com${path}`, options ); if (!response.ok) { const error = await response.json(); throw new APIError(error.errors[0].code, error.errors[0].message, response.status); } return await response.json(); } } // Usage const client = new SellingPartnerAPIClient( 'amzn1.application-oa2-client.1234567890', 'clientSecret123', 'https://myapp.com/oauth/callback' ); // Get authorization URL to show seller const authUrl = client.getAuthorizationUrl('unique-state-value'); // After seller authorizes and redirects back with code await client.exchangeAuthorizationCode('authorizationCode123'); // Make API requests (token will auto-refresh if needed) const restrictions = await client.request( 'GET', '/listings/2021-08-01/restrictions?asin=B08XXLG119&sellerId=AXXXXXXXXXXX&marketplaceIds=ATVPDKIKX0DER' ); ``` -------------------------------- ### Price Formatting (JavaScript) Source: https://github.com/amzn/selling-partner-api-docs/blob/main/_autodocs/INDEX.md Provides a function to format prices according to Amazon's requirements, including currency and decimal places. Correct price formatting is essential for listing accuracy. ```javascript function formatPrice(amount, currencyCode = 'USD') { // Ensure amount is a number const numericAmount = parseFloat(amount); if (isNaN(numericAmount)) { throw new Error('Invalid amount provided.'); } // Format the number to two decimal places const formattedAmount = numericAmount.toFixed(2); // Return in the expected structure for some APIs (e.g., Feeds API) return { "amount": formattedAmount, "currencyCode": currencyCode }; } // Example Usage: const price1 = formatPrice(19.99); console.log('Formatted Price 1:', JSON.stringify(price1)); const price2 = formatPrice('123.456', 'EUR'); console.log('Formatted Price 2:', JSON.stringify(price2)); try { formatPrice('invalid'); } catch (e) { console.error(e.message); } ``` -------------------------------- ### Get Listings Restrictions Source: https://github.com/amzn/selling-partner-api-docs/blob/main/guides/en-US/use-case-guides/listings-restrictions-api-use-case-guide/listings-restrictions-api-use-case-guide_2021-08-01.md Retrieves any listing restrictions for a given item in the Amazon catalog. This operation is useful for validating if an item can be listed before attempting to do so, and for understanding any requirements or next steps if restrictions are in place. ```APIDOC ## GET /listings/2021-08-01/restrictions ### Description Retrieves any listings restrictions for a given item in the Amazon catalog. This operation is useful for validating if an item can be listed before attempting to do so, and for understanding any requirements or next steps if restrictions are in place. ### Method GET ### Endpoint /listings/2021-08-01/restrictions ### Parameters #### Query Parameters - **asin** (string) - Required - The Amazon Standard Identification Number (ASIN) of the item. - **conditionType** (enum) - Optional - The condition used to filter restrictions. Refer to `ConditionType` for possible values. - **sellerid** (string) - Required - A selling partner identifier, such as a merchant account. - **marketplaceIds** (array(csv)) - Required - Comma-delimited list of Amazon marketplace identifiers for the request. - **reasonLocale** (string) - Optional - A locale for reason text localization. Defaults to the language code of the first marketplace if not provided. ### Request Example ```http https://sellingpartnerapi-na.amazon.com/listings/2021-08-01/restrictions?asin=B08XXLG119&conditionType=&sellerId=AXXXXXXXXXXX&marketplaceIds=ATVPDKIKX0DER ``` ### Response #### Success Response - **restrictions** (array) - A list of restrictions for the specified Amazon catalog item. The list will be empty if there are no restrictions. #### Response Example (no restrictions) ```json { "restrictions": [ { } ] } ``` #### Response Example (restrictions exist) ```json { "restrictions": [ { "marketplaceId": "ATVPDKIKX0DER", "conditionType": "collectible_like_new", "reasons": [ { "reasonCode": "APPROVAL_REQUIRED", "message": "You cannot list the product in this condition.", "links": [ { "title": "Link Title", "href": "https://example.com/approval-link" } ] } ] } ] } ``` ```