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?

Node.js で YouTube Data API(v3)を軽く試す: 動画のタイトルの取得

Posted at

はじめに

以下の YouTube Data API を少し Node.js で試してみた話です。

●YouTube Data API の概要  |  Google for Developers
 https://developers.google.com/youtube/v3/getting-started?hl=ja

さっそく試す

それでは、さっそく試していきます。

プロジェクトの新規作成

以下の手順で、今回用のプロジェクトを新しく作ります。

●プロジェクトを作成  |  Google App Engine standard environment docs  |  Google Cloud
 https://cloud.google.com/appengine/docs/standard/nodejs/building-app/creating-project?hl=ja

名前は、分かりやすい適当な名前にしました。

APIキーの取得

上記で作ったプロジェクトで APIキーを作成します。

公式のクイックスタート(Node.js用)のステップ1 に書かれた「こちらのウィザード」というテキストのリンクを開きます。

image.png

選択されたいるプロジェクトが、意図したものであることを確認して、YouTube Data API v3 を有効にします。

image.png

あとは、認証情報のページ( https://console.cloud.google.com/apis/credentials )の画面上部の「+ 認証情報の作成」から、APIキーを作成します。
APIキーが作成された後は、APIキーの名前を分かりやすいものにしたり、API の制限で「YouTube Data API v3」のみを対象にしたり、ということを行いました。

そして、この時に作成した APIキーをメモしておきます。

Node.js で YouTube Data API を使う

あとは、Node.js で YouTube Data API を使ってみます。内容はシンプルなものにします。

下準備

下準備として、以下のパッケージ(Google APIs Node.js Client)をインストールします。

npm install googleapis

また、上で作成した APIキーを YOUTUBE_API_KEY という名前の環境変数で使えるようにしました。

Node.js での実装・処理の実行

Node.js で実装した内容は以下のとおりです。

自分が過去にアップロードした動画を指定して、そのタイトルを取得するという簡単な内容のものです。

import { google } from "googleapis";

const apiKey = process.env.YOUTUBE_API_KEY;
if (!apiKey) {
  console.error("環境変数 YOUTUBE_API_KEY が設定されていません");
  process.exit(1);
}
const youtube = google.youtube({ version: "v3", auth: apiKey });

// 動画IDを指定: https://www.youtube.com/watch?v=hC7aml8pTa0
const videoId = "hC7aml8pTa0";

async function fetchVideoTitle(videoId) {
  const res = await youtube.videos.list({
    part: ["snippet"],
    id: [videoId],
  });
  const snip = res.data.items?.[0]?.snippet;
  return snip ? snip.title : null;
}

(async () => {
  try {
    const title = await fetchVideoTitle(videoId);
    console.log("動画タイトル:", title);
  } catch (err) {
    console.error("動画タイトル取得中にエラー:", err);
    process.exit(1);
  }
})();

上記を実行した結果は以下のとおりです。自分が過去にアップロードした動画のタイトルを取得できました。

image.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?