楽天APIから商品データを受信してSpringBootで表示する方法

coding

楽天APIから商品データを受信するために、Spring Bootを使ったJavaプログラムの基本的な構成を以下に示します。このプログラムは、楽天の商品検索APIを利用して商品情報を取得する例です。

まず、楽天APIを利用するには、楽天の「楽天デベロッパーズサイト」でアプリケーションID(APIキー)を取得する必要があります。

1. Spring Bootプロジェクトを作成

pom.xml に以下の依存関係を追加します。

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Boot Starter JSON (RestTemplateのため) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-json</artifactId>
    </dependency>

    <!-- Spring Boot Starter Test (JUnit) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- Jackson JSONを扱うため -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
</dependencies>

2. アプリケーション設定

application.properties に楽天APIのアプリケーションID(APIキー)を設定します。

rakuten.api.app-id=YOUR_APP_ID_HERE
rakuten.api.endpoint=https://app.rakuten.co.jp/services/api/IchibaItem/Search/20170706

3. 商品検索API用のサービスクラス

楽天の商品検索APIを呼び出すためのサービスクラスを作成します。

RakutenProductService.java

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.fasterxml.jackson.databind.JsonNode;

@Service
public class RakutenProductService {

    @Value("${rakuten.api.app-id}")
    private String appId;

    @Value("${rakuten.api.endpoint}")
    private String apiEndpoint;

    private final RestTemplate restTemplate;

    public RakutenProductService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public JsonNode searchProducts(String keyword) {
        String url = UriComponentsBuilder.fromHttpUrl(apiEndpoint)
                .queryParam("applicationId", appId)
                .queryParam("keyword", keyword)
                .queryParam("hits", 10)
                .build().toUriString();

        return restTemplate.getForObject(url, JsonNode.class);
    }
}

4. コントローラークラス

API呼び出しを制御するためのコントローラーを作成します。

RakutenProductController.java

package com.example.demo.controller;

import com.example.demo.service.RakutenProductService;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RakutenProductController {

    private final RakutenProductService rakutenProductService;

    public RakutenProductController(RakutenProductService rakutenProductService) {
        this.rakutenProductService = rakutenProductService;
    }

    @GetMapping("/search")
    public JsonNode searchProducts(@RequestParam String keyword) {
        return rakutenProductService.searchProducts(keyword);
    }
}

5. Spring Bootのメインクラス

アプリケーションのエントリーポイントを定義します。

DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

6. テスト用のRestTemplate Bean

RestTemplateを使って外部APIと通信するために、@ConfigurationクラスでBeanを定義します。

AppConfig.java

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

7. 実行方法

このアプリケーションを実行すると、以下のエンドポイントで楽天の商品検索結果を取得できます。

  • GET /search?keyword=パソコン

このリクエストを実行すると、楽天APIから商品情報がJSON形式で返されます。

結果

検索したキーワードに関連する商品データがJSON形式で返されます。このデータは以下のような形です:

{
  "Items": [
    {
      "Item": {
        "itemName": "Sample Product",
        "itemPrice": 10000,
        "itemUrl": "https://example.com"
      }
    },
    ...
  ]
}

このコードを実行するためには、実際に楽天のアプリケーションIDを取得して設定する必要があります。また、必要に応じてレスポンスデータのパース処理やエラーハンドリングを追加することをお勧めします。

コメント