Tutorial: Automate your SP-API Calls Using a C# SDK
Automate your SP-API calls with Login with Amazon (LWA) token exchange and authentication.
This tutorial provides you with all the required information to generate a C# SDK with Login with Amazon (LWA) token exchange and an authentication to build your application.
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
-
On your local drive, create a directory for this project and name it
SwaggerToCL
. -
Download the following tools.
- IDE software (this walkthrough uses Visual Studio IDE on Windows OS)
- GNU Wget
- Java 8 or newer
-
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
-
Copy
swagger-codegen-cli.jar
into your local directoryC:\\SwaggerToCL
. -
In GitHub, go to
https://github.com/amzn/selling-partner-api-models/tree/main/models
and use the following command to clone theselling-partner-api-models
repository to your local directoryC:\\SwaggerToCL
.git clone https://github.com/amzn/selling-partner-api-models
-
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 intoC:\\SwaggerToCL
. This tutorial uses theSellers.json
file. -
In GitHub, go to
https://github.com/amzn/selling-partner-api-models/tree/main/clients/sellingpartner-api-aa-csharp
and download thesellingpartner-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
-
Open Visual Studio.
-
In the
sellingpartner-api-aa-csharp
folder, select theSellingPartnerAPIAuthAndAuthCSharp.sln
file and build it using the build option in Visual Studio. This generates theAmazon.SellingPartnerAPIAA.dll
assembly in the foldersellingpartner-api-aa-csharp\\src\\Amazon.SellingPartnerAPIAA\\bin\\Debug\\netstandard2.0
. -
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 ofSwagger.IO
.- In
C:\\SwaggerToCL
, create a JSON file namedcsharpConfig.json
, open an editor and add the following code. ForpackageName
, 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. - In
Step 3. Connect to the Selling Partner API using the generated C# SDK
-
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 isSellingPartnerAPI.SellerAPI.sln
. -
Right-click the
SellingPartnerAPI.SellerAPI
file and select Add > References. -
In the References window, choose Browse, navigate to
sellingpartner-api-aa csharp/src/Amazon.SellingPartnerAPIAA/bin/Debug/netstandard2.0
and chooseAmazon.SellingPartnerAPIAA.dll
. -
Repeat steps 1-3 for the
SellingPartnerAPI.SellerAPI.Test
file. -
Navigate to your generated library
Sellers_CsharpCL
folder, right-click theSellingPartnerAPI.SellerAPI
file, choose Options > General, and change the target framework to .net Framework v4.7 and newer. -
Repeat step 5 for the
SellingPartnerAPI.SellerAPI.Test
file. -
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 newerNewtonsoft.json 12.0.3
or newerRestSharp 106.12.0
RateLimiter 2.2.0
or newer (this will also installComposableAsync.Core
)
-
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 can encounter an error. In this scenario, you must manually add the packages from the package folder in the file system:
- In Visual Studio IDE, navigate to your generated library
Sellers_CsharpCL
folder and open the.sln
file. - Right-click the
SellingPartnerAPI.SellerAPI
file and select Add > References. - 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.
- In Visual Studio IDE, navigate to your generated library
-
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:
Name | Description | Required |
---|---|---|
ClientId | Your LWA client identifier. For more information, refer to Viewing your application information and credentials. | Yes |
ClientSecret | Your LWA client secret. For more information, refer to Viewing your application information and credentials | Yes |
RefreshToken | The 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:- ScopeNotificationsAPI . For the Notifications API.- ScopeMigrationAPI . For the Authorization API. | 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 . |
Endpoint | The LWA authentication server URI. | Yes |
Example of an operation call that requires selling partner authorization:
```csharp
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:
```csharp
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"")
};
```
-
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. -
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.
-
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
”
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 have the required version in the NuGet
packages for Newtonsoft, you need to manually add the package from the package folder in the file system. To resolve this, use the following steps:
-
In Visual Studio, right-click your generated SDK package and choose
Add
, thenReferences
. -
On the references window in the .Net Assembly, choose
browse
**. -
Navigate to the generated client library folder in local → packages 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."
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."
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”
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;
// }
Updated 3 months ago