YoutubeDataAPIを使ってわちゃわちゃしたので、
簡単に使い方についての備忘録です。
YoutubeDataAPIとは
動画をアップロードしたり、キーワードで検索などができるみたいです。
今回はキーワードで検索しようと思います。
使用する言語はPHPでFWはLaravelです。
参考(これさえ見ればOKとは言わないこと)https://developers.google.com/youtube/v3/code_samples/php?hl=ja#search_by_keyword
前提
- GoogleDeveloperConsoleのアカウントを持ってる
- Laravelある程度わかる
GoogleDeveloperConsoleでの準備
- GoogleDeveloperConsoleでプロジェクトを作成する
- プロジェクトでサービス一覧→YoutubeDataAPIを有効にする
- 認証情報でAPIキーを作成する
- 作成したAPIキーでYoutubeDataAPIを利用できるようにする
以下、簡易的なスクショ
2で有効にするサービス
4で作成したキーにYoutubeDataAPIを有効にする
Laravelのサンプルコード
- .envファイルに作成したAPIキーを設定する
- YoutubeDataAPIを利用するためのルーティング、コントローラを作成
1の例
.env
1 |
GOOGLE_DEVELOPER_KEY=AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXXX |
2のルーティングやコントローラのファイルの記述
routes/api.php
1 2 3 |
Route::prefix('/post')->group(function () { Route::get('/search', 'PostController@searchMovieList'); }); |
app/Http/Controllers/PostController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Http\Response; use App\Services\PostService; class PostController extends Controller { public function __construct( PostService $post_service ) { $this->post_service = $post_service; } public function searchMovieList(Request $request) { $keyword = $request->input('q'); $response = $this->post_service->searchMovieList($keyword); return response('', 200); } } |
app/Services/PostService.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php namespace App\Services; use App\Utils\YoutubeApi; class PostService { public function __construct( YoutubeApi $youtube ) { $this->youtube = $youtube; } public function searchMovieList(string $keyword) { return $this->youtube->searchList($keyword); } } |
app/Utils/YoutubeApi.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?php namespace App\Utils; class YoutubeApi { private $client; private $youtube; const SEARCH_RESULT_MAX = 5; public function __construct() { $this->client = new \Google_Client(); $this->client->setDeveloperKey(env('GOOGLE_DEVELOPER_KEY')); $this->youtube = new \Google_Service_Youtube($this->client); } public function searchList(string $keyword) { try { $search_response = $this->youtube->search->listSearch( 'id,snippet', [ 'q' => $keyword, 'maxResults' => self::SEARCH_RESULT_MAX ] ); \Log::debug(json_encode($search_response)); } catch (Google_Service_Exception $e) { \Log::error('Google_Service_Error'); \Log::error($e->getMessage()); } catch (Google_Exception $e) { \Log::error('Google_Exception'); \Log::error($e->getMessage()); } catch (\Exception $e) { \Log::error($e->getMessage()); } } } |
あとはAPIを実行するだけ
APIの実行
curlやpostman(https://www.postman.com/)で実行
1 |
curl http://localhost:10088/api/post/search?q='プログラミング Laravel' |
レスポンスはログ(storage/logs/laravel.log)に出しているので中身を確認
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
{ "etag": "L3ysakb-ZPp3jPpuPi5yPTLE2sY", "eventId": null, "kind": "youtube#searchListResponse", "nextPageToken": "CAUQAA", "prevPageToken": null, "regionCode": "JP", "visitorId": null, "pageInfo": { "resultsPerPage": 5, "totalResults": 93011 }, "items": [ { "etag": "Uw_iN4UBZ1e9LpwJSJjfhu2PNj4", "kind": "youtube#searchResult", "id": { "channelId": null, "kind": "youtube#video", "playlistId": null, "videoId": "E9V0-5ekhYE" }, "snippet": { "channelId": "UC_HLK-ksslL-Z_2wiIZDlMg", "channelTitle": "KENTA / 雑食系エンジニアTV", "description": "いまだに「PHPとLaravelでポートフォリオを作るという選択に関してはどう思われますか」的なご質問を頂くことが多いので、今回はこの件と、あとは「キャリアの中でPHP ...", "liveBroadcastContent": "none", "publishedAt": "2020-12-27T11:00:04Z", "title": "PHPとLaravelに「一生」関わる必要がない理由", "thumbnails": { "default": { "height": 90, "url": "https://i.ytimg.com/vi/E9V0-5ekhYE/default.jpg", "width": 120 }, "medium": { "height": 180, "url": "https://i.ytimg.com/vi/E9V0-5ekhYE/mqdefault.jpg", "width": 320 }, "high": { "height": 360, "url": "https://i.ytimg.com/vi/E9V0-5ekhYE/hqdefault.jpg", "width": 480 } } } }, { "etag": "1cOUiTG1LuHEcJEUHiSMOmpqI_c", "kind": "youtube#searchResult", "id": { "channelId": null, "kind": "youtube#video", "playlistId": null, "videoId": "H4FvS5wPHVI" }, "snippet": { "channelId": "UCGlgXjYVoHLD86TQQ799WIw", "channelTitle": "キノコード / プログラミング学習チャンネル", "description": "目次 ・Laravelとは ・Laravelの特徴 ・フルスタックフレームワーク ▽文字書き起こし Laravelとは、PHPのフレームワークです。 フレームワークとは、WebサイトやWeb ...", "liveBroadcastContent": "none", "publishedAt": "2019-11-28T09:00:02Z", "title": "Laravelとは?|Laravelとは何か、特徴などを3分でわかりやすく解説します【プログラミング初心者向け】", "thumbnails": { "default": { "height": 90, "url": "https://i.ytimg.com/vi/H4FvS5wPHVI/default.jpg", "width": 120 }, "medium": { "height": 180, "url": "https://i.ytimg.com/vi/H4FvS5wPHVI/mqdefault.jpg", "width": 320 }, "high": { "height": 360, "url": "https://i.ytimg.com/vi/H4FvS5wPHVI/hqdefault.jpg", "width": 480 } } } }, { "etag": "mdThK_JS1LviY1WQMkuct-8FxbE", "kind": "youtube#searchResult", "id": { "channelId": null, "kind": "youtube#playlist", "playlistId": "PLCyDm9NTxdhLnA4tH5ToQR1K1LcWIAdOa", "videoId": null }, "snippet": { "channelId": "UCqzJi2o7bAPtRD3tTFvi7zA", "channelTitle": "渋谷で働くエンジニア福の「実践で学ぶプログラミング入門」", "description": "", "liveBroadcastContent": "none", "publishedAt": "2020-01-07T13:48:41Z", "title": "Laravel入門(全13回)", "thumbnails": { "default": { "height": 90, "url": "https://i.ytimg.com/vi/cO9Kfh3lypg/default.jpg", "width": 120 }, "medium": { "height": 180, "url": "https://i.ytimg.com/vi/cO9Kfh3lypg/mqdefault.jpg", "width": 320 }, "high": { "height": 360, "url": "https://i.ytimg.com/vi/cO9Kfh3lypg/hqdefault.jpg", "width": 480 } } } }, { "etag": "h2lgk_RSAsvk2Eg2zS4Cv4I2mY4", "kind": "youtube#searchResult", "id": { "channelId": null, "kind": "youtube#video", "playlistId": null, "videoId": "M7ZV0GKm4lI" }, "snippet": { "channelId": "UCphTq6mefx_15CjD35qgXgA", "channelTitle": "たにぐち まことのともすたチャンネル", "description": "再生リストはこちら https://www.youtube.com/playlist?list=PLh6V6_7fbbo8bb7eajaLdsQZ9fLhMJ-oc 独学応援コミュニティ運用中(Salckアカウントが必要です) ...", "liveBroadcastContent": "none", "publishedAt": "2019-06-13T09:00:07Z", "title": "Laravel入門 #01:Composerで作る Laravelの開発環境", "thumbnails": { "default": { "height": 90, "url": "https://i.ytimg.com/vi/M7ZV0GKm4lI/default.jpg", "width": 120 }, "medium": { "height": 180, "url": "https://i.ytimg.com/vi/M7ZV0GKm4lI/mqdefault.jpg", "width": 320 }, "high": { "height": 360, "url": "https://i.ytimg.com/vi/M7ZV0GKm4lI/hqdefault.jpg", "width": 480 } } } }, { "etag": "vBQRLgvQBBJDsS08GkejESKtyg0", "kind": "youtube#searchResult", "id": { "channelId": null, "kind": "youtube#video", "playlistId": null, "videoId": "M8GreoaLScs" }, "snippet": { "channelId": "UCcnk1Rc0TS27CwyMsC5qOaw", "channelTitle": "OASYS Technologies Inc.", "description": "再生リスト 【プログラミング入門】初心者がTodoアプリを作ってみた!【ToDo管理アプリ】 ...", "liveBroadcastContent": "none", "publishedAt": "2021-05-02T01:00:06Z", "title": "【プログラミング入門】初心者がTodoアプリ作ってみた!#1【php/Laravel】", "thumbnails": { "default": { "height": 90, "url": "https://i.ytimg.com/vi/M8GreoaLScs/default.jpg", "width": 120 }, "medium": { "height": 180, "url": "https://i.ytimg.com/vi/M8GreoaLScs/mqdefault.jpg", "width": 320 }, "high": { "height": 360, "url": "https://i.ytimg.com/vi/M8GreoaLScs/hqdefault.jpg", "width": 480 } } } } ] } |
items->id->videoIdで動画のユニークになる値が格納されてます。
つまずいた点
実行したら、"Exceed Quota"という403のエラーが出た。
これは元々勉強用に色々利用していた既存のプロジェクトにYoutubeDataAPIを利用した際に、APIの実行上限が一日0になっていて
実行ができない状態になっていた現象。
新しく新規でプロジェクトを作成してAPIを利用するキーを発行することで解決した。
まとめ
- YoutubeDataAPIを使うとキーワードで動画リストを取得できる
- APIには実行上限があるのに注意
- PHPで利用するための公式リファレンスがある(https://developers.google.com/youtube/v3/code_samples/php?hl=ja#search_by_keyword)