Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ASINから商品情報のJSONを取得する

 ここでは、ISBNやASINという本の情報から、アマゾンの表紙画像や、タイトル著者名、出版社、価格、本の種類などの情報を取得してサイトとして出力する方法を書く。
 Creators APIでは、様々な言語用にツールが配布されているが、私はnode.jsが一番慣れているので、node.jsを用いた方法について書いていきます。

アクセスキーやSDKは以前の記事から取得する。

鍵はjsonにまとめておいておく、.gitignoreに追加すると公開するリスクを減らせる。
key.json

{"accessKey":"アクセスキー",
"secretKey" :"シークレットキー",
"PartnerTag":"パートナータグ",
"CredentialId":"ID",
"CredentialSecret":"シークレット",
"Version":"v2.3"
}

サンプルコードではasinをまとめたjsonファイルからasinを10個ずつ読み込んでAPIレスポンスをjsonとして保存している。1回毎に3秒程度のsleepを挟んでいるので適宜調整する。

sample.json

[
 "B0D7DPXQT8",
 "B0GYRP2LP7"
 ]

サンプルコード

const fs = require('fs');

/* ====== key.json 読み込み ====== */
const json = fs.readFileSync(__dirname + '/key.json', 'utf-8');
const key = JSON.parse(json);

/* ====== sleep ====== */
function sleep(second) {
    return new Promise(resolve => {
        setTimeout(resolve, second * 1000);
    });
}

/* ====== Creators API SDK ====== */
const {
    ApiClient,
    DefaultApi,
    GetItemsRequestContent
} = require('./dist/index');

/* ====== API Client 初期化 ====== */
const apiClient = new ApiClient();
apiClient.credentialId = key.CredentialId;
apiClient.credentialSecret = key.CredentialSecret;
apiClient.version = "2.3"; // 例: 2.3 (JP)

/* ====== API ====== */
const api = new DefaultApi(apiClient);

/* ====== GetItemsRequest テンプレ ====== */
function createGetItemsRequest(asinList) {
    const req = new GetItemsRequestContent();

    req.partnerTag = key.PartnerTag;
    req.itemIds = asinList;
    req.condition = 'New';

    req.resources = [
        'browseNodeInfo.browseNodes',
        'images.primary.small',
        'images.primary.medium',
        'images.primary.large',
        'itemInfo.byLineInfo',
        'itemInfo.classifications',
        'itemInfo.externalIds',
        'itemInfo.manufactureInfo',
        'itemInfo.productInfo',
        'itemInfo.title',
        'offersV2.listings.price',
        'offersV2.listings.loyaltyPoints'
    ];

    return req;
}

/* ====== メイン処理 ====== */
(async function () {

    let sale = 'sample';
    //sale = 'other';

    try {
        asinJson = fs.readFileSync(
            __dirname + '/json/kindle_sale/asin/' + sale + 'k.json',
            'utf-8'
        );
    } catch (err) {
        console.log('/json/kindle_sale/asin/' + sale + '.json が存在しません');
        return;
    }

    const asinarry = JSON.parse(asinJson);

    let jsondata = [];
    const filename = sale + '.json';
    const marketplace = 'www.amazon.co.jp';

    for (let i = 0; i < asinarry.length; i += 10) {

        await sleep(3);

        const asinSlice = asinarry.slice(i, i + 10);
        const getItemsRequest = createGetItemsRequest(asinSlice);

        try {
            const response = await api.getItems(marketplace, getItemsRequest);

            console.log(`GetItems success: ${asinSlice.join(', ')}`);

            if (response?.itemsResult?.items) {
                jsondata = jsondata.concat(response.itemsResult.items);
            }

            fs.writeFileSync(
                __dirname + '/json/kindle_sale/paapi/' + filename,
                JSON.stringify(jsondata, null, 1),
                'utf-8'
            );

            if (response?.errors) {
                console.log('API Errors:', JSON.stringify(response.errors, null, 2));
            }

} catch (error) {
    console.log('Error calling Creators API');

    // そのまま出す(最重要)
    console.dir(error, { depth: null });

    // よくある中身
    if (error?.response) {
        console.log('response:', JSON.stringify(error.response, null, 2));
    }
    if (error?.body) {
        console.log('body:', JSON.stringify(error.body, null, 2));
    }
}
    }

})();

Amazon Creators APIを利用して作ったサイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Would you support @99nyorituryo?

About supporter service
99nyorituryo

Thank you for reading. I'm encouraged by your support!

Support

@99nyorituryo's pickup articles

99nyorituryo

@99nyorituryo(99)

電子書籍に関する技術書を出してます。https://www.amazon.co.jp/-/e/B07Q2TZFCN

Linked from these articles

Comments

No comments

Let's comment your feelings that are more than good

Being held Article posting campaign

学生限定!夏の記事投稿チャレンジ

2026-06-01 ~ 2026-07-13

View details
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address