HomeDocumentationCode SamplesAnnouncementsMigration HubModelsRelease NotesFAQsBlogVideos
Developer HubAPI StatusSupport
Developer HubAPI StatusSupport

Tutorial: Automate your SP-API calls using C# SDK

Tutorial to automate your SP-API calls with C# SDK with Login with Amazon (LWA) token exchange and authentication.

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

You can use this SDK to integrate Amazon marketplace features into your applications, including accessing product information, managing orders, handling shipments, and more.

Tutorial

The following tutorial will help you set up your own C# SDK for automating SP-API calls.

Prerequisites

To complete this tutorial, you need the following prerequisites:

  • A hybrid or SP-API app in draft or published state
  • Integrated development environment (IDE) software (this walkthrough uses Visual Studio IDE on Windows OS)

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

Next, set up your workspace for the tutorial.

Step 1. Set up your workspace

  1. On your local drive, create a directory for this project and name it SwaggerToCL.

  2. Download the following tools.

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

wget https://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.4.13/swagger-codegen-cli-2.4.13.jar -O swagger-codegen-cli.jar
  1. Copy swagger-codegen-cli.jar into your local directory C:\\SwaggerToCL.

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

git clone https://github.com/amzn/selling-partner-api-models
  1. Navigate to the selling-partner-api-models\\models folder in your local copy of the repository and copy a JSON file from the models subfolders into C:\\SwaggerToCL. This tutorial uses the Sellers.json file.

  2. In GitHub, go to https://github.com/amzn/selling-partner-api-models/tree/main/clients/sellingpartner-api-aa-csharp and download the sellingpartner-api-aa-csharp folder to your local computer.

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

Now that you have completed the required setup, the next step is to generate the C# SDK with the authentication and authorization classes provided in the sellingpartner-api-aa-csharp folder.

Step 2. Generate a C# SDK with LWA token exchange and authentication

  1. Open Visual Studio.

  2. In the sellingpartner-api-aa-csharp folder, select the SellingPartnerAPIAuthAndAuthCSharp.sln file and build it using the build option in Visual Studio. This generates the Amazon.SellingPartnerAPIAA.dll assembly in the folder sellingpartner-api-aa-csharp\\src\\Amazon.SellingPartnerAPIAA\\bin\\Debug\\netstandard2.0.

  3. Open a terminal and run the following commands to generate the C# client library. The default package name for the generated client library is Swagger.IO. These commands generate the client libraries with their respective API names as the package name instead of Swagger.IO.

    • In C:\\SwaggerToCL, create a JSON file named csharpConfig.json, open an editor and add the following code. For packageName, use the same name of the API you want to generate the client library for:
{"packageName":"SellingPartnerAPI.SellerAPI","targetFramework":"v4.7.2"}

Run this command to generate C# code with a customized package name:

java -jar C:\SwaggerToCL\swagger-codegen-cli.jar generate -i C:\SwaggerToCL\[name of model].json -l csharp -t [path to selling-partner-api-models\clients\sellingpartner-api-aa-csharp folder]\src\Amazon.SellingPartnerAPIAA\resources\swagger-codegen\templates\ -o C:\SwaggerToCL\[name of client library] -c C:\SwaggerToCL\csharpConfig.json

This command uses Sellers.json to generate C# code:

java -jar C:\SwaggerToCL\swagger-codegen-cli.jar generate -i C:\SwaggerToCL\Sellers.json -l csharp -t C:\SwaggerToCL\sellingpartner-api-aa-csharp\src\Amazon.SellingPartnerAPIAA\resources\swagger-codegen\templates\ -o C:\SwaggerToCL\Sellers_CsharpCL -c C:\SwaggerToCL\csharpConfig.json

The SDK is created in C:\\SwaggerToCL\\Sellers_CsharpCL. The next step is to write the actual application and connect to the SP-API using the generated C# SDK.

Step 3. Connect to the Selling Partner API using the generated C# SDK

  1. In Visual Studio IDE, navigate to your generated library Sellers_CsharpCL folder and open the .sln file. The .sln package file will have the name as provided in Step 2. Generate a C# SDK with LWA token exchange and authentication. In this example, the package file name is SellingPartnerAPI.SellerAPI.sln.

  2. Right-click the SellingPartnerAPI.SellerAPI file and select Add > References.

  3. In the References window, choose Browse, navigate to sellingpartner-api-aa csharp/src/Amazon.SellingPartnerAPIAA/bin/Debug/netstandard2.0 and choose Amazon.SellingPartnerAPIAA.dll.

  4. Repeat steps 1-3 for the SellingPartnerAPI.SellerAPI.Test file.

  5. Navigate to your generated library Sellers_CsharpCL folder, right-click the SellingPartnerAPI.SellerAPI file, choose Options > General, and change the target framework to .net Framework v4.7 and above.

  6. Repeat step 5 for the SellingPartnerAPI.SellerAPI.Test file.

  7. Right-click the SellingPartnerAPI.SellerAPI file and choose Manage NuGet Packages. Make sure you have the following package versions (If not, install the respective NuGet packages):

    • JsonSubTypes 1.2.0 or newer
    • Newtonsoft.json 12.0.3 or newer
    • RestSharp 106.12.0
    • RateLimiter 2.2.0 or newer (this will also install ComposableAsync.Core)
  8. Right-click the SellingPartnerAPI.SellerAPI.Test file and choose Manage NuGet Packages. Install the Nunit 2.6.4 package.

📘

Manual installation of NuGet packages

In some scenarios (for example, using IOS), the required versions in the NuGet packages appear, but you may encounter an error. In this scenario, you must manually add the packages from the package folder in the file system:

  1. In Visual Studio IDE, navigate to your generated library Sellers_CsharpCL folder and open the .sln file.
  2. Right-click the SellingPartnerAPI.SellerAPI file and select Add > References.
  3. In the References window, choose Browse, navigate to sellingpartner-api-aa csharp/src/Amazon.SellingPartnerAPIAA/bin/Debug/netstandard2.0, choose the generated client library folder (for example, Sellers_CsharpCL), then choose packages and add the package for which you are facing the error.
  1. In the SellingPartnerAPI.SellerAPI.Test > Api folder, open the [Modelname]Tests.cs file and add the following code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using RestSharp;
using SellingPartnerAPI.SellerAPI.Client;
using SellingPartnerAPI.SellerAPI.Api;
using SellingPartnerAPI.SellerAPI.Model;
using Amazon.SellingPartnerAPIAA;

namespace SellingPartnerAPI.SellerAPI.Test
{
    class SellersApiTests
    {
        public static void Main(string[] args)
        {
            try
            {
                LWAAuthorizationCredentials lwaAuthorizationCredentials = new LWAAuthorizationCredentials
                {
                    ClientId = "amzn1.application-oa2-client.******************",
                    ClientSecret = "***********************************",
                    RefreshToken = "Atzr|***********************************",
                    Endpoint = new Uri("https://api.amazon.com/auth/o2/token")
                };
                SellersApi sellersApi = new SellersApi.Builder()
                    .SetLWAAuthorizationCredentials(lwaAuthorizationCredentials)
                    .Build();

                GetMarketplaceParticipationsResponse result = sellersApi.GetMarketplaceParticipations();
                Console.WriteLine(result.ToJson());
            }
            catch (LWAException e)
            {
                Console.WriteLine("LWA Exception when calling SellersApi#getMarketplaceParticipations");
                Console.WriteLine(e.getErrorCode());
                Console.WriteLine(e.getErrorMessage());
                Console.WriteLine(e.Message);
            }
            catch (ApiException e)
            {
                Console.WriteLine("Exception when calling SellersApi#getMarketplaceParticipations");
                Console.WriteLine(e.Message);
            }
        }
    }
}

LWAAuthorizationCredentials instance parameters:

NameDescriptionRequired
ClientIdYour LWA client identifier. For more information, refer to Viewing your application information and credentials.Yes
ClientSecretYour LWA client secret. For more information, refer to Viewing your application information and credentials.Yes
RefreshTokenThe LWA refresh token. Get this value when the selling partner authorizes your application. For more information, refer to Authorizing Selling Partner API applications. No. Include RefreshToken if the operation that you call in the following step requires selling partner authorization. All operations that are not grantless operations require selling partner authorization. If you include RefreshToken, do not include Scopes.
Scopes

The scope of the LWA authorization grant. You can specify one or more Scopes values:

No. Include Scopes if the operation that you call in the following step is a grantless operation. If you include Scopes, do not include the RefreshToken.
EndpointThe LWA authentication server URI.Yes
Example of an operation call that requires selling partner authorization:
using Amazon.SellingPartnerAPIAA;
LWAAuthorizationCredentials lwaAuthorizationCredentials = new LWAAuthorizationCredentials
{
  ClientId = "myClientId",
  ClientSecret = "myClientSecret",
  RefreshToken = "Aztr|...",
  Endpoint = new Uri(""https://api.amazon.com/auth/o2/token"")
};

Example of a grantless operation call:

using Amazon.SellingPartnerAPIAA;
LWAAuthorizationCredentials lwaAuthorizationCredentials = new LWAAuthorizationCredentials
{
  ClientId = "myClientId",
  ClientSecret = "myClientSecret",
  Scopes = new List<string>() { ScopeConstants.ScopeNotificationsAPI, ScopeConstants.ScopeMigrationAPI }
  Endpoint = new Uri(""https://api.amazon.com/auth/o2/token"")
};
  1. To view the output of the code, you need to convert it to a console application. To do so, right-click the SellingPartnerAPI.SellerAPI.Test file and choose Options.

  2. On the Project Options window, in the left navigation pane, expand Build, then choose General. In the Code Generation section, choose Compile Target and select Executable with GUI. Choose OK.

  3. Build and run the project.

Troubleshoot a C# SDK

Restsharp errors: “IRestRequest is defined in an assembly that is not referenced. You must add a reference to assembly RestSharp Version=105.0.0.0. Culture=neutral. PublicKevToken=598062e77f915f75

Select to expand the answer. Update the Restsharp package to version 106.12.0.0. Check the reference to make sure that version 106.12 updated successfully. If it continues to show 105.0.0.0, remove the old version from the reference and add the 106.12.0.0 package manually from the packages folder with the generated client library.

"The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)"

Select to expand the answer.

In some scenarios, even though you see the required version in the NuGet packages for Newtonsoft, it requires manual addition from the package folder in the file system. To resolve this, use the following steps:

  1. In Visual Studio, right-click your generated SDK package and choose AddReferences.

  2. On the references window in the .Net Assembly, choose browse**.

  3. Navigate to the generated client library folder in localpackages and add the specific package for Newtonsoft.

“Message : Could not load type of field SellingPartnerAPI.servicesApi.Client.ApiClient:rateLimiter (3) due to : Could not load file or assembly ComposableAsync.Core, Version=1.1.1.0, Culture=neutral, PublicKeyToken=null or one of its dependencies."

Select to expand the answer.

If you receive this error after you build and run your code, then the ComposableAsync.Core dependency package was downloaded but not included as a reference. Make sure to add the dll as a reference manually.

Mapping issues with models

Select to expand the answer.

The ItemAsin model was generated with the JsonObject type, but the required string ItemAttributes requires the JsonObjectAttribute. You can use this command, which uses the Catalog Items API, to import the required mapping for the models :

`java -jar swagger-codegen-cli.jar generate -i catalogItems_2022-04-01.json -l csharp -t sellingpartner-api-aa-csharp\src\Amazon.SellingPartnerAPIAA\resources\swagger-codegen\templates —import-mappings ItemAttributes=Newtonsoft.Json.JsonObjectAttribute —import-mappings ItemAsin=System.string -o catalogItems2022-04-01_import`

"HttpRequestHeaders.ToJson(): no suitable method found to override."

Select to expand the answer.

Modify the override keyword with virtual. Declare methods as virtual so that they can be overridden.

public virtual string ToJson()
{
  return JsonConvert.SerializeObject(this, Formatting.Indented);
}

“The name BaseValidate does not exist in the current context”

Select to expand the answer.

Uncomment the mentioned methods in the class:

// IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
//   {
//     foreach (var x in BaseValidate(validationContext))
//       yield return x;
//     yield break;
//   }

Conclusion

In this tutorial, you learned how to automate your SP-API calls using a C# SDK. In the walkthrough you learned how to set up your workspace, generate a C# SDK for the Selling Partner API, connect to the Sellers API, and make an API call.