LoginSignup
0
0

springのRestTemplateでqitaのAPIコールを実装

Posted at

今日も備忘録です。

このドキュメントについて

下記について記載していきます。

  1. springのRestTemplateを利用したAPIコールの実装
    (qitaのAPIをコールしてみました)

APIコールする方法を色々実装してみましたが、
感覚的にはRestTemplateが1番理解しやすく、簡単に実装できました。
(RestTemplateは今後非推奨になるらしいですが、、、)

他の方法としては下記を試しました。
・WebCilent (springで今後推奨される)
・Okhttp3とretrofit2
・HttpClient

実行環境

・Java17
・springboot 3.0.2

実装

getForを利用する場合

var url = new StringBuilder()
    .append(Constant.qitaBaseUrl)
    .append("/api/v2/items/")
    .append(request.getItemId())
    .append("/comments").toString();
var restTemplate = new RestTemplate();

try {
    var response = restTemplate.getForEntity(url, QitaGetItemCommentDto[].class);
            return response.getBody();
        } catch (HttpClientErrorException e) {
            throw new RestClientException("400系エラーが発生しました", e);
        } catch (HttpServerErrorException e) {
            throw new RestClientException("500系エラーが発生しました", e);
        }

説明:
1.まずはリクエストする際のURLを作成する。
今回はqitaAPIの記事のコメント取得のAPIをコールします。
GET通信です。

2.restTemplateのgetForEntityメソッドを利用するとGET通信を実行できます。
引数にはurlとレスポンスの受け取り時の型を指定してあげます。
(今回だとQitaGetItemCommentDtoの配列を受け取ります。)
(post通信の場合は、postForEntity)

3.400系もしくは500系のエラーが起きた際は、上記のエラーが投げられるので、それをハンドリングしてあげる。

万能exchangeを利用する場合

var url = new StringBuilder()
            .append(Constant.qitaBaseUrl)
            .append("/api/v2/items/")
            .append(request.getItemId())
            .append("/comments").toString();
// リクエストボディ作成
var requestBody = new QitaWriteReactionsResource("テストでコメントします")
var requestEntity = RequestEntity
            .post(url)
            .accept(MediaType.APPLICATION_JSON)
            .header("Authorization", "Bearer " + "")
            .body(requestBody);

var restTemplate = new RestTemplate();
try {
    var response = restTemplate.exchange(requestEntity, QitaWriteReactionsDto.class);
    return response.getBody();
} catch (HttpClientErrorException e) {
    throw new RestClientException("400系エラーが発生しました", e);
} catch (HttpServerErrorException e) {
    throw new RestClientException("500系エラーが発生しました", e);
}

説明:
先ほどとの違いは、RequestEntityを用意する点で、exchangeメソッドはGET通信でもPOST通信でもRequestEntityに設定した方式で実行される。
(qitaのpost通信はAuthorizationが必要なので、header情報に設定してあげる必要がある)


まとめ

タイムアウトや通信障害の可能性もあるので、リトライ処理を入れてあげる方が良いですよね。
リトライ処理についても最近学んだので、以下にリンクを貼っておく。

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
0
0