Use the Amazon Product Advertising API 5.0 (PA-API v5) SDK (paapi5-java-sdk-1.0.0)

Overview

--Use Amazon Product Advertising API 5.0 (PA-API v5) from Java --Use the official SDK (paapi5-java-sdk-1.0.0) provided by AWS instead of calling the API directly --This execution environment: macOS Catalina + Java 8 + Gradle 6.1

Download paapi5-java-sdk-1.0.0

Since paapi5-java-sdk-1.0.0 is not distributed in Maven Central Repository etc., download and use the jar file.

Download paapi5-java-sdk-example.zip from Using SDK · Product Advertising API 5 \ .0 And deploy.

The sdk directory contains sample code that uses paapi5-java-sdk-1.0.0.

$ ls ./sdk/ | sort
Callback.java
ConnectionPoolSampleRequest.java
GetBrowseNodes.java
GetBrowseNodesAsync.java
GetBrowseNodesWithHttpInfo.java
GetItems.java
GetItemsAsync.java
GetItemsWithHttpInfo.java
GetVariations.java
GetVariationsAsync.java
GetVariationsWithHttpInfo.java
SearchItems.java
SearchItemsAsync.java
SearchItemsWithHttpInfo.java

The dependencies directory contains the SDK paapi5-java-sdk-1.0.0.jar and its dependent library jar files.

$ ls ./dependencies/ | sort
commons-codec-1.11.jar
commons-logging-1.2.jar
gson-2.8.1.jar
gson-fire-1.8.0.jar
hamcrest-core-1.3.jar
httpclient-4.5.5.jar
httpcore-4.4.9.jar
jackson-annotations-2.9.0.jar
jackson-core-2.9.5.jar
jackson-core-asl-1.9.2.jar
jackson-databind-2.9.3.jar
jackson-mapper-asl-1.9.2.jar
jackson-xc-1.9.2.jar
jackson-xml-databind-0.6.2.jar
json-20180130.jar
junit-4.12.jar
logging-interceptor-2.7.5.jar
okhttp-2.7.5.jar
okio-1.6.0.jar
paapi5-java-sdk-1.0.0.jar
stax-api-1.0-2.jar
stax2-api-3.1.0.jar
swagger-annotations-1.5.15.jar
threetenbp-1.3.5.jar

If you expand the paapi5-java-sdk-1.0.0.jar file and look at pom.xml, you will find the dependency information, so refer to this for the settings for the dependency library.

Below is a partial excerpt of dependency information from META-INF / maven / com.amazon.paapi5 / paapi5-java-sdk / pom.xml.

<dependencies>
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>${swagger-core-version}</version>
    </dependency>
    <dependency>
        <groupId>com.squareup.okhttp</groupId>
        <artifactId>okhttp</artifactId>
        <version>${okhttp-version}</version>
    </dependency>
    <dependency>

Sample code using paapi5-java-sdk-1.0.0

File list

This time, put the downloaded paapi5-java-sdk-1.0.0.jar under the libs directory.

├── build.gradle
├── libs
│   └── paapi5-java-sdk-1.0.0.jar
├── settings.gradle
└── src
    └── main
        └── java
            └── com
                └── example
                    └── App.java

build.gradle

Gradle configuration file.

plugins {
  id 'java'
  id 'application'
}

repositories {
  mavenCentral()
}

dependencies {

  //Downloaded paapi5-java-sdk
  implementation files('libs/paapi5-java-sdk-1.0.0.jar')

  // paapi5-java-Libraries on which the sdk depends(paapi5-java-sdk-1.0.0.jar pom.I referred to xml)
  implementation 'io.swagger:swagger-annotations:1.5.15'
  implementation 'com.squareup.okhttp:okhttp:2.7.5'
  implementation 'com.squareup.okhttp:logging-interceptor:2.7.5'
  implementation 'com.google.code.gson:gson:2.8.1'
  implementation 'io.gsonfire:gson-fire:1.8.0'
  implementation 'org.threeten:threetenbp:1.3.5'
}

application {
  mainClassName = 'com.example.App'
}

sourceCompatibility = targetCompatibility = '1.8'

settings.gradle

Gradle configuration file.

rootProject.name = 'hello-amazon-pa-api-world'

App.java

A sample program that uses paapi5-java-sdk-1.0.0.

package com.example;

import com.amazon.paapi5.v1.ApiClient;
import com.amazon.paapi5.v1.ApiException;
import com.amazon.paapi5.v1.ByLineInfo;
import com.amazon.paapi5.v1.Contributor;
import com.amazon.paapi5.v1.ErrorData;
import com.amazon.paapi5.v1.GetItemsRequest;
import com.amazon.paapi5.v1.GetItemsResource;
import com.amazon.paapi5.v1.GetItemsResponse;
import com.amazon.paapi5.v1.Item;
import com.amazon.paapi5.v1.PartnerType;
import com.amazon.paapi5.v1.SearchItemsRequest;
import com.amazon.paapi5.v1.SearchItemsResource;
import com.amazon.paapi5.v1.SearchItemsResponse;
import com.amazon.paapi5.v1.api.DefaultApi;

import java.util.ArrayList;
import java.util.List;

public class App {

  public static void main(String[] args) {

    ApiClient client = new ApiClient();
    client.setAwsAccessKey("<YOUR-ACCESS-KEY-HERE>"); //Obtained access key
    client.setAwsSecretKey("<YOUR-SECRET-KEY-HERE>"); //Obtained secret key
    client.setHost("webservices.amazon.co.jp"); // Amazon.co.jp Web API host
    client.setRegion("us-west-2"); // Amazon.co.jp in us-west-Specify 2

    String trackingId = "<YOUR-PARTNER-TAG-HERE>"; //Obtained tracking ID

    //Search for products by keyword
    System.out.println("===== searchItems ================================");
    String keywords = "Shakespeare";
    searchItems(client, trackingId, keywords);

    //Get product information from ASIN
    System.out.println("===== getItems ===================================");
    List<String> itemIds = new ArrayList<>();
    itemIds.add("4391641585");
    itemIds.add("B010EB1HR4");
    itemIds.add("B0125SPF90");
    itemIds.add("B07V52KSGT");
    getItems(client, trackingId, itemIds);
  }

  //Search for products by keyword
  public static void searchItems(ApiClient client, String trackingId, String keywords) {

    //Specify the type of value to include in the response
    // https://webservices.amazon.com/paapi5/documentation/search-items.html#resources-parameter
    List<SearchItemsResource> searchItemsResources = new ArrayList<SearchItemsResource>();
    searchItemsResources.add(SearchItemsResource.ITEMINFO_TITLE);
    searchItemsResources.add(SearchItemsResource.ITEMINFO_PRODUCTINFO);
    searchItemsResources.add(SearchItemsResource.IMAGES_PRIMARY_MEDIUM);
    searchItemsResources.add(SearchItemsResource.OFFERS_LISTINGS_PRICE);

    //Assemble request information
    SearchItemsRequest req = new SearchItemsRequest()
      .itemCount(5) //Number of search results
      .partnerTag(trackingId) //Tracking ID
      .keywords(keywords) //Search keyword
      .searchIndex("All") //Search category(AmazonVideo, Books, Hobbies,Music etc. can be specified)
      .resources(searchItemsResources) //Type of value to include in the response
      .partnerType(PartnerType.ASSOCIATES);

    try {
      //Perform a search
      DefaultApi api = new DefaultApi(client);
      SearchItemsResponse res = api.searchItems(req);

      //Get results
      if (res.getSearchResult() != null) {
        for (Item item : res.getSearchResult().getItems()) {
          System.out.println("--------------------------------------------------");
          //title, ASIN,Product URL
          System.out.println("Title: " + item.getItemInfo().getTitle().getDisplayValue());
          System.out.println("ASIN: " + item.getASIN());
          System.out.println("DetailPageURL: " + item.getDetailPageURL());
          //Whether it is an adult product
          System.out.println("IsAdultProduct: " + item.getItemInfo().getProductInfo().getIsAdultProduct().isDisplayValue());
          //Image URL
          System.out.println("ImageURL: " + item.getImages().getPrimary().getMedium().getURL());
          //price
          if (item.getOffers() != null
            && item.getOffers().getListings() != null
            && item.getOffers().getListings().get(0).getPrice() != null
            && item.getOffers().getListings().get(0).getPrice().getDisplayAmount() != null) {
            System.out.println("Price: " + item.getOffers().getListings().get(0).getPrice().getDisplayAmount());
          }
        }
      }
      //Error handling
      if (res.getErrors() != null) {
        for (ErrorData error : res.getErrors()) {
          System.out.println("Error code: " + error.getCode());
          System.out.println("Error message: " + error.getMessage());
        }
      }
    } catch (ApiException e) {
      //Error handling
      e.printStackTrace();
      System.out.println("Status code: " + e.getCode());
      System.out.println("Errors: " + e.getResponseBody());
      System.out.println("Message: " + e.getMessage());
      if (e.getResponseHeaders() != null) {
        System.out.println("Request ID: " + e.getResponseHeaders().get("x-amzn-RequestId"));
      }
    } catch (Exception e) {
      //Error handling
      e.printStackTrace();
    }
  }

  //Get product information from ASIN
  public static void getItems(ApiClient client, String trackingId, List<String> asinList) {

    //Specify the type of value to include in the response
    // https://webservices.amazon.com/paapi5/documentation/get-items.html#resources-parameter
    List<GetItemsResource> getItemsResources = new ArrayList<GetItemsResource>();
    getItemsResources.add(GetItemsResource.ITEMINFO_TITLE);
    getItemsResources.add(GetItemsResource.ITEMINFO_BYLINEINFO);

    //Assemble request information
    GetItemsRequest req = new GetItemsRequest()
      .itemIds(asinList) //List of ASINs
      .partnerTag(trackingId) //Tracking ID
      .resources(getItemsResources) //Type of value to include in the response
      .partnerType(PartnerType.ASSOCIATES);

    try {
      //Perform a search
      DefaultApi api = new DefaultApi(client);
      GetItemsResponse res = api.getItems(req);

      //Get results
      if (res.getItemsResult() != null) {
        for (Item item : res.getItemsResult().getItems()) {
          System.out.println("--------------------------------------------------");
          //title, ASIN,Product URL
          System.out.println("Title: " + item.getItemInfo().getTitle().getDisplayValue());
          System.out.println("ASIN: " + item.getASIN());
          System.out.println("DetailPageURL: " + item.getDetailPageURL());
          //Contributor information such as authors
          ByLineInfo bi = item.getItemInfo().getByLineInfo();
          if (bi != null && bi.getContributors() != null) {
            for (Contributor c : bi.getContributors()) {
              System.out.println("Contributor: " + c.getRole() + ": " + c.getName());
            }
          }
        }
      }
      //Error handling
      if (res.getErrors() != null) {
        for (ErrorData error : res.getErrors()) {
          System.out.println("Error code: " + error.getCode());
          System.out.println("Error message: " + error.getMessage());
        }
      }
    } catch (ApiException e) {
      //Error handling
      e.printStackTrace();
      System.out.println("Status code: " + e.getCode());
      System.out.println("Errors: " + e.getResponseBody());
      System.out.println("Message: " + e.getMessage());
      if (e.getResponseHeaders() != null) {
        System.out.println("Request ID: " + e.getResponseHeaders().get("x-amzn-RequestId"));
      }
    } catch (Exception e) {
      //Error handling
      e.printStackTrace();
    }
  }
}

Sample code execution result

Execution environment: macOS Catalina + Gradle 6.1 + Java 8 (AdoptOpenJDK 1.8.0_242-b08)

$ gradle run

> Task :run
===== searchItems ================================
--------------------------------------------------
Title:7 Shakespeare NON SANZ DROICT (11)(Young Magazine Comics)
ASIN: B084BP9ZD9
DetailPageURL: https://www.amazon.co.jp/dp/B084BP9ZD9?tag=<YOUR-PARTNER-TAG-HERE>&linkCode=osi&th=1&psc=1
IsAdultProduct: false
ImageURL: https://m.media-amazon.com/images/I/51KrT7qGuOL._SL160_.jpg
Price: ¥660
--------------------------------------------------
Title:Shakespeare Complete Works(1)Hamlet(Chikuma Bunko)
ASIN: 4480033017
DetailPageURL: https://www.amazon.co.jp/dp/4480033017?tag=<YOUR-PARTNER-TAG-HERE>&linkCode=osi&th=1&psc=1
IsAdultProduct: false
ImageURL: https://m.media-amazon.com/images/I/51RZYRYGQ8L._SL160_.jpg
Price: ¥726
--------------------------------------------------
Title:Hamlet(Subtitled version)
ASIN: B015BY1Q6Q
DetailPageURL: https://www.amazon.co.jp/dp/B015BY1Q6Q?tag=<YOUR-PARTNER-TAG-HERE>&linkCode=osi&th=1&psc=1
IsAdultProduct: false
ImageURL: https://m.media-amazon.com/images/I/516XD+o35gL._SL160_.jpg
Price: ¥400
--------------------------------------------------
Title:All Shakespeare works read in the synopsis(Shodensha Shinsho)
ASIN: B06ZZH149Y
DetailPageURL: https://www.amazon.co.jp/dp/B06ZZH149Y?tag=<YOUR-PARTNER-TAG-HERE>&linkCode=osi&th=1&psc=1
IsAdultProduct: false
ImageURL: https://m.media-amazon.com/images/I/41Ms+C0NwNL._SL160_.jpg
Price: ¥836
--------------------------------------------------
Title:Episode 8
ASIN: B07WPX7D76
DetailPageURL: https://www.amazon.co.jp/dp/B07WPX7D76?tag=<YOUR-PARTNER-TAG-HERE>&linkCode=osi&th=1&psc=1
IsAdultProduct: false
ImageURL: https://m.media-amazon.com/images/I/517ol4X4BwL._SL160_.jpg
===== getItems ===================================
--------------------------------------------------
Title:Sumikko Gurashi Test Official Guidebook Sumikko Gurashi Encyclopedia(Life series)
ASIN: 4391641585
DetailPageURL: https://www.amazon.co.jp/dp/4391641585?tag=<YOUR-PARTNER-TAG-HERE>&linkCode=ogi&th=1&psc=1
Contributor:Supervision:San-X
Contributor:Edit:Shufu to Seikatsusha
--------------------------------------------------
Title:Guardian Shinden Chapter 2<Expanded Edition>(Remaster)
ASIN: B010EB1HR4
DetailPageURL: https://www.amazon.co.jp/dp/B010EB1HR4?tag=<YOUR-PARTNER-TAG-HERE>&linkCode=ogi&th=1&psc=1
Contributor:Artist:Halloween
--------------------------------------------------
Title:Halloween Rocking Pumpkin Home decoration accessory H 130cm
ASIN: B0125SPF90
DetailPageURL: https://www.amazon.co.jp/dp/B0125SPF90?tag=<YOUR-PARTNER-TAG-HERE>&linkCode=ogi&th=1&psc=1
--------------------------------------------------
Title:Halloween(Subtitled version)
ASIN: B07V52KSGT
DetailPageURL: https://www.amazon.co.jp/dp/B07V52KSGT?tag=<YOUR-PARTNER-TAG-HERE>&linkCode=ogi&th=1&psc=1
Contributor:Appearance:Jamie Lee Curtis
Contributor:Appearance:Judy Greer
Contributor:Appearance:Andy Mattichuck
Contributor:Appearance:Will Patton
Contributor:Appearance:Virginia Gardner
Contributor:Appearance:Nick Castle
Contributor:Appearance:James Jude Courtney
Contributor:Appearance:Hulk Birginer
Contributor:Appearance:Lian Reese
Contributor:Appearance:Jefferson Hall
Contributor:directed by:David Gordon Green
Contributor: Writer:David Gordon Green
Contributor: Writer:Jeff Floodley
Contributor: Writer:Danny McBride
Contributor:Produced:Marek Akkad
Contributor:Produced:Jason Blum
Contributor:Produced:Bill block

BUILD SUCCESSFUL in 3s
2 actionable tasks: 2 executed

Reference material

-PA-API v5 Migration Guide --Associate Central

Recommended Posts

Use the Amazon Product Advertising API 5.0 (PA-API v5) SDK (paapi5-java-sdk-1.0.0)
Call Amazon Product Advertising API 5.0 (PA-API v5) in Java
I tried to make a product price comparison tool of Amazon around the world with Java, Amazon Product Advertising API, Currency API (2017/01/29)