Google API Key 啟用 & Python 建立 google sheet = ###### tags: `Tutorial` `Google API` `Google Sheet` `Python` Google API Apply - ### Project 建立 進入 Google 官網:[Google Official Website](https://console.developers.google.com/apis/) 點選左上角下拉選單,並新增專案,如下圖示: * 選取專案 ![](https://hackmd.io/_uploads/rkM1LYQM6.png) * 新增專案 ![](https://hackmd.io/_uploads/H1W9UKXzp.png =60%x) * 自訂專案名稱 ![](https://hackmd.io/_uploads/HkbrvYXz6.png =60%x) 完成上述步驟,按下**鍵立**即完成專案建置。 ### 啟用 Google API 服務 點選左側欄位的『已啟用的API和服務』,再點選『+啟用API和服務』 ![](https://hackmd.io/_uploads/S1dVdFmza.png =60%x) 進入API程式庫,並搜尋想啟用的API服務 ![](https://hackmd.io/_uploads/BykhdtmGp.png) EX:若想啟用**Google Sheet API**,則可搜尋**sheet api**等關鍵字,如下結果: ![](https://hackmd.io/_uploads/rJpOKtmfa.png) 進入頁面,並點選啟用即完成 ![](https://hackmd.io/_uploads/rJJhKK7fT.png =60%x) ### 取得 Google API Key 啟用完API服務後,回主頁,點選憑證->建立憑證->服務帳戶 ![](https://hackmd.io/_uploads/BkeGjtQfa.png) 進入**IAM與管理**頁面,填寫服務**帳戶名稱**,即會自動生成**服務帳戶ID**,其餘可自由選填 ![](https://hackmd.io/_uploads/SJlciKQMa.png =70%x) 完成後,即可在憑證頁面上看到剛剛創建到服務帳戶 ![](https://hackmd.io/_uploads/H1atnF7Mp.png) 點選剛剛創建的服務帳戶再次進入**IAM與管理**,並點選金鑰->新增金鑰->建立新的金鑰,如下圖示: ![](https://hackmd.io/_uploads/ByzyRKXGp.png) 跳出金鑰存檔畫面,一般會選擇以JSON檔案類型為主,選取好之後按建立,此金鑰會下載到自己端的電腦保存 ![](https://hackmd.io/_uploads/SJINRt7fT.png =50%x) ### 查詢 Google API 使用額度 進入Project主頁,在最下方會列出啟用的API,點選進入 ![](https://hackmd.io/_uploads/B1cYe9mz6.png) 進入**API和服務頁面**,點選**配額**,下方會列出配額上限和使用次數 ![](https://hackmd.io/_uploads/HkDkZcmfa.png) Python Build Google Sheet - ### 建立Google Sheet 開啟雲端硬碟,並建立Google Sheet,點選檔案->共用->與他人共用 ![](https://hackmd.io/_uploads/r1iFM97Gp.png =50%x) 在新增使用者和群組的欄位輸**服務帳戶ID**(於**取得 Google API Key步驟**時創建) ![](https://hackmd.io/_uploads/SyKJm5mfp.png =50%x) 並將剛剛創建的Google Sheet的key記下,位置如下: ![](https://hackmd.io/_uploads/rJTXEcXMp.png) ### Python Code ``` import gspread from oauth2client.service_account import ServiceAccountCredentials auth_json_path = 'key file' # 下載在自己端的key(JSON檔) gss_scopes = ['https://spreadsheets.google.com/feeds'] # Connect credentials = ServiceAccountCredentials.from_json_keyfile_name(auth_json_path,gss_scopes) gss_client = gspread.authorize(credentials) # Open Google Sheet spreadsheet_key = 'google sheet key' # 創建Google Sheet 的key # Build Google Sheet Table sheet = gss_client.open_by_key(spreadsheet_key).sheet1 # clear sheet.clear() ``` Reference - [Google API Key settings](https://www.wfublog.com/2018/12/google-api-key-activate-quota.html) [Python Build Google Sheet](https://yanwei-liu.medium.com/%E5%A6%82%E4%BD%95%E9%80%8F%E9%81%8Epython%E5%BB%BA%E7%AB%8Bgoogle%E8%A1%A8%E5%96%AE-%E4%BD%BF%E7%94%A8google-sheet-api-314927f7a601)