Amazon Selling Partner API Models

repository·main·Indexed 21 days ago

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

Central source of truth for Amazon Selling Partner API (SP-API) Swagger models and schemas. This repository provides Mustache templates for Swagger Codegen and OpenAPI Generator to create type-safe, authenticated client libraries. It includes implementation details and SDK generation guides for C#, Java, JavaScript (Node.js v18+), and PHP, covering LWA authorization, Restricted Data Token (RDT) support, and client-side rate limiting.

Tokens
12.9K
Snippets
32
Records
49
Agent score
74%

What's inside amzn-selling-partner-api-models

  1. Overview of the Selling Partner API JavaScript client library

    main

    This library simplifies SP-API development for Node.js (v18+) by providing a generated SDK that handles HTTP communication via superagent.

    Key features include:

    • LWA Helper: Automates the Login with Amazon (LWA) OAuth token refresh flow.
    • Header Management: Automatically includes the required x-amz-access-token header in requests.
    • RDT Support: Simplifies calls to "Restricted Operations" by combining the two-step process (retrieving a Restricted Data Token via the Tokens API and then calling the protected operation) into a single library call.
  2. Access Selling Partner API models and schemas

    main

    The repository is organized into several key directories for different integration needs:

    • models/: Contains all currently available Swagger models for the Selling Partner APIs.
    • schemas/: Contains all currently available Selling Partner API schemas.
    • clients/: Contains pre-configured templates for generating client libraries:
      • sellingpartner-api-aa-java/: Java library templates.
      • sellingpartner-api-aa-csharp/: C# library templates.
  3. Download and decrypt a document

    main

    Use DownloadHelper to download encrypted documents and read their decrypted contents. The process returns a DownloadBundle which can be used to access the decrypted data stream.

    Key components:

    • DownloadHelper: The main class for performing downloads.
    • DownloadSpecification: Defines the download parameters including the AESCryptoStreamFactory and the document url. You can also specify a CompressionAlgorithm using .withCompressionAlgorithm().
    • DownloadBundle: An object returned by download() that implements AutoCloseable. It provides methods like newBufferedReader() to read the decrypted content.
    • CompressionAlgorithm: Use CompressionAlgorithm.fromEquivalent(string) to map a string representation to the required algorithm.
    import com.amazon.spapi.documents.DownloadHelper;
    import com.amazon.spapi.documents.DownloadSpecification;
    import com.amazon.spapi.documents.DownloadBundle;
    import com.amazon.spapi.documents.CompressionAlgorithm;
    import com.amazon.spapi.documents.impl.AESCryptoStreamFactory;
    import java.io.BufferedReader;
    
    public void downloadAndDecrypt(String key, String initializationVector, String url, String compressionAlgorithm) {
        AESCryptoStreamFactory aesCryptoStreamFactory = 
                new AESCryptoStreamFactory.Builder(key, initializationVector).build();
    
        DownloadSpecification downloadSpec = new DownloadSpecification.Builder(aesCryptoStreamFactory, url)
                .withCompressionAlgorithm(CompressionAlgorithm.fromEquivalent(compressionAlgorithm))
                .build();
    
        DownloadHelper downloadHelper = new DownloadHelper.Builder().build();
    
        try (DownloadBundle downloadBundle = downloadHelper.download(downloadSpec)) {
            try (BufferedReader reader = downloadBundle.newBufferedReader()) {
                String line;
                while ((line = reader.readLine()) != null) {
                    // Process the decrypted line
                }
            }
        } catch (Exception e) {
            // Handle CryptoException, HttpResponseException, IOException, or MissingCharsetException
        }
    }
  4. Sign Selling Partner API requests with LWAAuthorizationSigner

    main

    The LWAAuthorizationSigner class handles obtaining and signing HTTP requests with an access token from Login with Amazon (LWA) for a specific endpoint. It is designed to work with Selling Partner API Client Libraries generated via openapi-generator using Guzzle.

    To use it, provide LWAAuthorizationCredentials containing your clientId, clientSecret, refreshToken, and the LWA endpoint. You then initialize the signer and pass the configuration to your generated API client.

    $lwaAuthorizationCredentials = new LWAAuthorizationCredentials([
    "clientId" => '.....',
    "clientSecret" => '.....',
    "refreshToken" => '.....',
    "endpoint" => 'https://api.amazon.com/auth/o2/token'
    ]);
    
    // Initialize LWAAuthorizationSigner instance
    $lwaAuthorizationSigner = new LWAAuthorizationSigner($lwaAuthorizationCredentials);
    $config = new Configuration([], $lwaAuthorizationCredentials);
    
    // Setting SP-API endpoint region. Change it according to the desired region
    $config->setHost('https://sellingpartnerapi-na.amazon.com');
    
    // Create a new HTTP client
    $client = new GuzzleHttp\Client();
    
    // Create an instance of the Orders Api client
    $api = new OrdersApi($config, null, $client);
  5. Workaround for Merchant Fulfillment API SDK generation error

    main

    The Merchant Fulfillment V0 API causes a fatal error during SDK generation. To fix this, you must manually modify the model file before running the generation script.

    1. Download the models using ./generate-js-sdk.sh.
    2. Locate the file: <package root>/models/merchant-fulfillment-api-model/merchantFulfillmentV0.json.
    3. Find this block:
    "AvailableFormatOptionsForLabel": {
          "$ref": "#/definitions/AvailableFormatOptionsForLabelList"
    },
    1. Replace it with this snippet:
    "AvailableFormatOptionsForLabel": {
        "type": "array",
        "description": "The available label formats.",
        "items": {
            "$ref": "#/definitions/LabelFormatOption"
        }
    },
    1. Run the generation script again:
    $ ./generate-js-sdk.sh -j <path/to/swagger-codegen-cli-2.4.29.jar>

    Important: When prompted Found <package root>/models already exists. Would you like to delete all the files under '<package root>/models' and clone again? [y/n]:, answer n. Answering y will overwrite your manual fix.

  6. Generate a Python client from Swagger definitions

    main

    Use the swagger-codegen-cli.jar to generate a Python client based on a specific SP-API Swagger JSON file.

    Command Template:

    java -jar /[path_to_swagger_jar]/swagger-codegen-cli.jar generate -l python -t /[path_to_mustach_resources]/resources/ -D packageName=swagger_client -o /[path_to_client_folder]/client/[SP-API_NAME] -i /[path_to_model_folder]/models/[SP-API_NAME]/SP-API.json

    Parameters:

    • -l python: Specifies the target language as Python.
    • -t: Path to Mustache resources.
    • -D packageName: The name of the generated package (e.g., swagger_client).
    • -o: The output directory for the generated client.
    • -i: The input path to the SP-API Swagger JSON file.
  7. Generate client libraries from Selling Partner API models

    main

    This repository provides Swagger models that can be used to generate client libraries for calling Selling Partner APIs. You can use swagger codegen to generate your own client libraries from the models found in the models directory.

    To simplify this process, the repository provides mustache templates for Java and C# located in resources/swagger-codegen within the respective client directories. These templates allow you to generate client libraries that include built-in authentication and authorization functionality.

    # Example workflow concept:
    # 1. Locate models in /models
    # 2. Use swagger-codegen with templates from /clients/sellingpartner-api-aa-java/resources/swagger-codegen
    # 3. Generate your custom client library