Youtube Data API 使用手札 - HackMD

文章推薦指數: 80 %
投票人數:10人

在此紀錄, Youtube Data API In Node.js 的實做過程, 以免下一次忘記如何做! ... 如果想要限制API 金鑰, 可自行設定, 本文建議先測通 Youtube Search API 再做限制 ...       Published LinkedwithGitHub Like2 Bookmark Subscribe Edit #YoutubeDataAPI使用手札 ######tags:`w3HexSchool`.`youtube`.`node.js` >最近因為搭捷運時,看Hahow影片卡爆, >所以起心動念想要將自己買的課程,放到私人的Youtube撥放清單中 >手動一個影片.一個的影片下載,之後上傳實在太慢了, >因此我做了一個electron處理上傳&下載的事情 >程序化上傳部分,我們可以用YoutueDataAPI處理 >在此紀錄,YoutubeDataAPIInNode.js的實做過程,以免下一次忘記如何做! >題外話,不知道Hahow的使用者條款,有沒有禁止軟體工程師製作應用程式批次下載`已購買課程`呢? ##取得YoutubeAPI_KEY 首先進入[GoogleDevelopersConsole](https://console.developers.google.com/apis/dashboard)建立新專案來產生一組API_KEY ==建立一個新專案== ![新增專案](https://i.imgur.com/nNiZMJd.png) ==輸入專案名稱`youtube-test`== ![輸入專案名稱](https://i.imgur.com/TJ3AvSW.png) ![切換面板到新的專案](https://i.imgur.com/6hqLdOF.png) ![到API資料庫](https://i.imgur.com/scPbZTs.png) ![查詢YouTubeDataAPI](https://i.imgur.com/TaXpTQX.png) ![啟用YouTubeDataAPI](https://i.imgur.com/thzVjn6.png) ![建立憑證](https://i.imgur.com/VdTiAqe.png) ==這次我們要建立的是API_KEY== ![選擇建立API_KEY](https://i.imgur.com/F3dkh8L.png) ![已建立的API_KEY](https://i.imgur.com/nqIiVnl.png) :::info 如果想要限制API金鑰,可自行設定,本文建議先測通`YoutubeSearchAPI`再做限制 ::: ![](https://i.imgur.com/cxKz1XV.png) ##YoutubeSearchAPI :::info 我們可以直接用axios做一個getrequest來訪問YoutubeSearchAPI ::: ```javascript= /*youtube-search.js*/ //參考資料:https://medium.com/%E5%B0%8F%E9%83%AD-%E0%B9%80%E0%B8%88%E0%B8%99/%E8%8F%9C%E9%B3%A5%E5%B7%A5%E7%A8%8B%E5%B8%AB-youtube-data-api-%E8%BC%89%E5%85%A5%E6%92%AD%E6%94%BE%E6%B8%85%E5%96%AE%E4%B8%A6%E5%88%87%E6%8F%9B%E6%AD%8C%E6%9B%B2-356d8e454ca3 constaxios=require('axios'); constAPI_KEY='AIzaSyCfTvOCJ5JA5eTeetkHSfDBUurdJeBDm94';//youmustreplaceAPI_KEY asyncfunctionrunSample(){ constres=awaitaxios.get('https://www.googleapis.com/youtube/v3/search', { params:{ part:'id,snippet',//必填,把需要的資訊列出來 q:'韓國瑜',//查詢文字 maxResults:50,//預設為五筆資料,可以設定1~50 key:API_KEY,//使用API只能取得公開的播放清單 } }); console.log(res.data); } runSample().catch(err=>console.error(err)); ``` :::warning 別忘了,要將剛剛產生的API_KEY取代`AIzaSyCfTvOCJ5JA5eTeetkHSfDBUurdJeBDm94`歐! ::: :::info 如果要確認SearchAPI有甚麼其他的`參數`可以使用,請看==[官方文件](https://developers.google.com/youtube/v3/docs/search/list)== ::: ##GoogleOAuth2身份認證 :::info 如果要上傳影片,就需要OAuth2登入,取得`access_token`才能上傳 ::: ==先設定OAuth同意畫面== ![](https://i.imgur.com/6nZVZsd.png) ![](https://i.imgur.com/JKjQgCF.png) ==OAuth同意畫面== ![](https://i.imgur.com/AsmbkmP.png) ==範圍== ![](https://i.imgur.com/039o6vf.png) ==選填資訊== ![](https://i.imgur.com/dljvh40.png) ==摘要== ![](https://i.imgur.com/A5wtFWG.png) ==建立憑證== ![建立憑證](https://i.imgur.com/ZfguEau.png) ==這次我們建立OAuth用戶端ID== ![](https://i.imgur.com/2jLcBYp.png) ![建立OAuth用戶端ID](https://i.imgur.com/3JUeBW0.png) ![建立OAuth用戶端ID-輸入文字](https://i.imgur.com/gcld6JY.png) ==下載client_secret.json檔== ![下載client_secret.json檔](https://i.imgur.com/tAPDKQZ.png) ==client_secret.json內容== ![](https://i.imgur.com/CUTcc5x.png) :::warning `redirect_uris`與`javascript_origins`這兩個欄位必須存在 如果不存在,就需要重新設定`OAuth用戶端ID` ::: >我們利用`google-OAuth-test.js`來產生`access_token` ```javascript= /*google-OAuth-test.js*/ constfs=require('fs'); constpath=require('path'); consthttp=require('http'); consturl=require('url'); constopn=require('open'); constaxios=require('axios'); constreadline=require('readline'); const{google}=require('googleapis'); constyoutube=google.youtube('v3');//google.options有設定oauth2Client之後會用那裏的驗證 constAPI_KEY='[YOUR_API_KEY]'; /** *TouseOAuth2authentication,weneedaccesstoaaCLIENT_ID,CLIENT_SECRET,ANDREDIRECT_URI.Togetthesecredentialsforyourapplication,visithttps://console.cloud.google.com/apis/credentials. */ constkeyPath=path.join(__dirname,'./client_secret.json');//設定client_secret.json放的位置 letkeys={}; if(fs.existsSync(keyPath)){ keys=require(keyPath).web; } /** *CreateanewOAuth2clientwiththeconfiguredkeys. */ constoauth2Client=newgoogle.auth.OAuth2( keys.client_id, keys.client_secret, keys.redirect_uris[0] ); /** *Thisisoneofthemanywaysyoucanconfiguregoogleapistouseauthenticationcredentials.Inthismethod,we'resettingaglobalreferenceforallAPIs.AnyotherAPIyouusehere,likegoogle.drive('v3'),willnowusethisauthclient.Youcanalsooverridetheauthclientattheserviceandmethodcalllevels. */ google.options({auth:oauth2Client}); /** *Openanhttpservertoaccepttheoauthcallback.Inthissimpleexample,theonlyrequesttoourwebserveristo/callback?code= */ asyncfunctionauthenticate(scopes){ returnnewPromise((resolve,reject)=>{ //grabtheurlthatwillbeusedforauthorization constauthorizeUrl=oauth2Client.generateAuthUrl({ access_type:'offline', scope:scopes.join(''), }); constserver=http .createServer((req,res)=>{ if(req.url.indexOf('/oauth2callback')>-1){ constqs=newurl.URL(req.url,'http://localhost:3000').searchParams; oauth2Client.getToken(qs.get('code')) .then(({tokens})=>{ //showaccess_tokenandapi_keytohtml res.end(`

Authenticationsuccessful!

ACCESS_TOKEN ${tokens.access_token} API_KEY ${YOUTUBE_TOKEN.API_KEY} `); console.log('token=',tokens); oauth2Client.credentials=tokens; resolve({access_token:tokens.access_token,api_key:API_KEY}); //Closetheserver server.close(()=>console.log('Serverclosed!')); }) .catch(e=>{ res.end('Authenticationfailed.'); reject(e); //Closetheserver server.close(()=>console.log('Serverclosed!')); }); }else{ res.end('WrongUrl.Youneedtosethttp://localhost:3000/oauth2callbackasredirect_uri'); } }) .listen(3000,()=>{ //openthebrowsertotheauthorizeurltostarttheworkflow opn(authorizeUrl,{wait:false}).then(cp=>cp.unref()); console.log('accessapiathttp://localhost:3000'); }); }); } constscopes=[ 'https://www.googleapis.com/auth/youtube'//scopeforaddplaylist.uploadvideo... ]; authenticate(scopes) .then(({access_token,api_key})=>console.table({access_token,api_key})) .catch(err=>console.error(err)); ``` ==執行`google-OAuth2-test.js`後,會自動開啟瀏覽器== ![](https://i.imgur.com/pqzwHdG.png) ==因為使用http,所以會有"應用程式未驗證"== ![](https://i.imgur.com/xBGnIp2.png) ![](https://i.imgur.com/wp2k0uM.png) ![](https://i.imgur.com/4TnxbLO.png) ==驗證成功後,會自動轉址到`http://localhost:3000/oauth2callback`== ![](https://i.imgur.com/z6hJLEm.png) :::info 之後,我們就可以使用`access_token`與`api_key`訪問`YoutubeVideoUploadAPI`來上傳影片檔 ::: ##VideoUploadAPI :::info 延續之前的認證,取得`access_token`後,我們才能將影片上傳到自己的頻道 ::: ```javascript=105 //上傳影片(youtube-upload) asyncfunctionaddVideo({access_token,api_key,channelId='UC8eCqbosTLZdvFCGid5YllA',fileName='../data/video.mp4'}){ //youtube.video.insert constnowStr=newDate().getTime().toString(36).substring(0,4); constfileSize=fs.statSync(fileName).size; constres=awaityoutube.videos.insert( { part:'id,snippet,status,contentDetails', notifySubscribers:false, requestBody:{ snippet:{ channelId,//上傳影片到哪個頻道 title:`your-video-${nowStr}`,//影片標題 description:'測試上傳影片',//影片描述 }, status:{ privacyStatus:"private" }, }, media:{ body:fs.createReadStream(fileName), }, }, { //Usethe`onUploadProgress`eventfromAxiostotrackthe //numberofbytesuploadedtothispoint. onUploadProgress:evt=>{ constprogress=(evt.bytesRead/fileSize)*100; console.log(`${Math.round(progress)}%complete`);//顯示目前上傳進度 }, } ); console.log('Videosuccessfulupload😊'); return{access_token,api_key,data:res.data,videoId:res.data.id}; } authenticate(scopes) .then(addVideo) .catch(err=>console.error(err)); ``` :::info 如果要確認VideoUploadAPI有甚麼其他的`參數`可以使用,請看==[官方文件](https://developers.google.com/youtube/v3/docs/videos/insert)== ::: ##[YoubuteDataAPI配額](https://developers.google.com/youtube/v3/getting-started#calculating-quota-usage) ![](https://i.imgur.com/3M5QsFE.png) :::info ==說明[IAM配額管理](https://console.cloud.google.com/iam-admin/quotas?service=youtube.googleapis.com&project=ezoom-test)== -YoutubeDataAPI每天預設有`10,000`units可使用 -每次videoupload會用掉`1600`units -每次insert.update會用掉`50`units ::: ![](https://i.imgur.com/Z6MiGbp.png) ##參考資料 -[YouTubeDataAPIOverview-quota](https://developers.google.com/youtube/v3/getting-started#calculating-quota-usage) -[youtubedataapi載入播放清單並切換歌曲](https://medium.com/%E5%B0%8F%E9%83%AD-%E0%B9%80%E0%B8%88%E0%B8%99/%E8%8F%9C%E9%B3%A5%E5%B7%A5%E7%A8%8B%E5%B8%AB-youtube-data-api-%E8%BC%89%E5%85%A5%E6%92%AD%E6%94%BE%E6%B8%85%E5%96%AE%E4%B8%A6%E5%88%87%E6%8F%9B%E6%AD%8C%E6%9B%B2-356d8e454ca3) 2 × Signin Email Password Forgotpassword or Byclickingbelow,youagreetoourtermsofservice. SigninviaFacebook SigninviaTwitter SigninviaGitHub SigninviaDropbox SigninviaGoogle NewtoHackMD?Signup



請為這篇文章評分?