LoginSignup
13
10

Youtube APIを使って検索+再生をやってみた(React+Typescript)

Last updated at Posted at 2021-03-21

はじめに

YoutubeAPI使ってみたいな〜と思ったので、React+Typescriptでサクッと実装してみました。
なかなか情報がなかったのでQiitaにまとめることにしました。
Reactのプロジェクトの導入についても軽く触れようかと思います。

###実行環境

$ npm -v
7.5.1
$ create-react-app -V
3.3.1

###作ったもの
「ヒカキン」のキーワードで検索して最も再生数が多い動画を表示します。
ちなみにこの動画は1.1億回再生されてました。すごい。(2021/3/21現在)
image.png

#APIキーを取得する
公式サイトにも説明がありますが、こちらの記事を参考にAPIキーを取得しました。
Youtube Data API で取得したデータをPython(Pandas/matplotlib)で可視化する。

#Reactのプロジェクトを作成する
まずはReact+Typescriptでプロジェクトを作りましょう

$ create-react-app youtube-project --template typescript

App.tsxの中身を書き換えます。

App.tsx
function App() {
  return (
    <div className="App">
      <p>Youtube APIのテストです</p>
      <Api />
    </div>
  );
}

Apiコンポーネントを作成します。まずは全文を載せておきます。解説はこの後

Api.tsx

import React, { useState, useEffect } from "react";

const YOUTUBE_SEARCH_API_URI = "https://www.googleapis.com/youtube/v3/search?";
const API_KEY = "[取得したAPIキー]";

const Api = () => {
  const [videoId, setVideoId] = useState("");

  useEffect(() => {
    // クエリ文字列を定義する
    const params = {
      key: API_KEY,
      q: "ヒカキン", // 検索キーワード
      type: "video", // video,channel,playlistから選択できる
      maxResults: "1", // 結果の最大数
      order: "viewCount", // 結果の並び順を再生回数の多い順に
    };
    const queryParams = new URLSearchParams(params);

    // APIをコールする
    fetch(YOUTUBE_SEARCH_API_URI + queryParams)
      .then((res) => res.json())
      .then(
        (result) => {
          console.log("API success:", result);

          if (result.items && result.items.length !== 0) {
            const firstItem = result.items[0];
            setVideoId(firstItem.id.videoId);
          }
        },
        (error) => {
          console.error(error);
        }
      );
  }, []);

  return (
    <iframe
      id="player"
      width="640"
      height="360"
      src={"https://www.youtube.com/embed/" + videoId}
      frameBorder="0"
      allowFullScreen
    />
  );
};

export default Api;

#解説
###Youtube Data APIで検索する
https://developers.google.com/youtube/v3/docs/search/list
Youtube Data APIのSearch listを使用して動画を検索します。

検索内容は全てクエリ文字列で与えるので、まずはクエリ文字列を定義します

    // クエリ文字列を定義する
    const params = {
      key: API_KEY,
      q: "ヒカキン", // 検索キーワード
      type: "video", // video,channel,playlistから選択できる
      maxResults: "1", // 結果の最大数
      order: "viewCount", // 結果の並び順を再生回数の多い順に
    };
    const queryParams = new URLSearchParams(params);

次にAPIコールを行います。
fetchを使った記載方法は公式ドキュメントに載っていた通りで実装しました。
https://ja.reactjs.org/docs/faq-ajax.html


    fetch(YOUTUBE_SEARCH_API_URI + queryParams) //さっき作成したクエリ文字列
      .then((res) => res.json())
      .then(
        (result) => {
          console.log("API success:", result);

          //result.itemsの中に検索結果が格納されるので、最初の検索結果を取り出す
          //検索条件でmaxResultsを1にしているので、1件しか返ってこない
          if (result.items && result.items.length !== 0) { 
            const firstItem = result.items[0];
            // videoIdを使用して動画を取得するので保存しておく
            setVideoId(firstItem.id.videoId);
          }
        },
        (error) => {
          console.error(error);
        }
      );

これをuseEffectで囲むことで初回render後にAPIコールを実施します。

###IFrame Player APIで動画を表示する
iframeタグを使用して動画を表示できます。
https://developers.google.com/youtube/iframe_api_reference?authuser=1

  return (
    <iframe
      id="player"
      width="640"
      height="360"
      src={"https://www.youtube.com/embed/" + videoId} //先ほど保存したvideoId
      frameBorder="0"
      allowFullScreen
    />
  );

#最後に
Textinputを使用して任意の検索ができるようにしても面白いですね。
YoutubeAPIは他にも種類があるので色々試してみようと思います。
以上です。

13
10
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
13
10