Huli 的程式導師計畫第五期第四週的作業四,是要串接 Twitch API :
請參考 Twitch API v5 的文件,寫一隻程式去呼叫 Twitch API,並拿到「最受歡迎的遊戲列表(Get Top Games)」,並依序印出目前觀看人數跟遊戲名稱。
首先進到 Using the Legacy Twitch API v5 這個頁面,頁面中介紹了如何串接 Twitch API,首先要申請到 Client ID。
在申請 ID 之前,首先要註冊 Twitch 帳號。
按照流程註冊帳號,然後信箱通過驗證。
來到 Get Started with the Twitch API 這個頁面,點進Twitch developer console的連結中,會來到下圖這個畫面。
其中的 OAuth 網址不會用到,下方說明有寫可以填 http://localhost
這個網址即可。
建立後如果跳出提示要你啟用二階段驗證或是 2FA,請到 安全性與隱私中進行驗證,過程中我有按照指示下載了 Authy 這個驗證APP。
建立好應用程式後,請再點選應用程式進入頁面後,點選 管理。 下方會出現用戶端ID,THAT'S IT!
進入到 github - request 頁面中,可以看到request
這個 library 的用法及注意事項。
首先需要先 require request module.
如果跳出錯誤訊息,可能需要先 npm install 載入 module.
在 Using the Legacy Twitch API v5 頁面中,可以找到以下段落:
Requests
For client IDs created on or after May 31, 2019, the only available version of the Legacy Twitch API is v5. For client IDs created prior to May 31, 2019, use the Accept: application/vnd.twitchtv.v5+json header on your requests to access v5 of the Legacy Twitch API API.
雖然時間點上 2019/5/31 之後的使用者不需要在 headers 帶入 Accept 參數,但實際操作上還是必須帶入否則無法成功串接。
因此,在 github - request 頁面中,也找到了以下段落:
Custom HTTP Headers
這裡可以看到 request 的參數是 (options, callback),因此可以在 options 中建立 headers 帶入參數。
可以先把 data 印出來看一下回傳資料的內容,再依序拿到題目指定的觀看人數和遊戲名稱。