如果你想上傳檔案到Google Drive或是從Google Drive下載檔案到本地端
不想要手動上傳而是想要自動上傳的話,推薦你可以使用Google Drive API
那到底該如何使用Google Drive API呢?
照著下方一步一步來,順利完成OAuth 2.0 憑證。
內容目錄
申請 Google Drive API OAuth 2.0 憑證 流程
要如何申請Google Drive API Oauth 2.0憑證呢?
首先到GCP(google cloud platform),申請新專案
專案內可以建立多個Google 相關的服務,我們則是建立一個Google Drive API的服務功能
建立 GCP(google cloud platform) 專案
假設你不知道怎麼建立GCP專案,可以照著下面做就行
進入到GCP後,點擊圖片1的位置,新增一個專案

建立一個自己喜歡的專案名稱,接著按下建立

選擇到自己新建立的專案,如下方圖片

啟動 Google Drive API
進入API服務資訊主頁平台,主要是申請Google相關服務API以及憑證的項目

點擊啟用API和服務

由於我們是要使用Google Drive,因此我們直接搜尋Google Drive

點擊 Google Drive API

啟用 Google Drive API,點擊啟用

建立 Google Drive API 憑證
當我們啟用Google Drive API還是不夠的,需要建立憑證,作為我們執行程式中間的橋樑
因此點擊“建立憑證”

選擇 Google Drive API
選擇 使用者資料
接著點擊下一步

應用程式名稱可以看你想取名什麼,我則是另名為Demo與專案名稱相同
使用者支援電子郵件以及開發人員聯絡資訊
輸入你目前登入GCP的Gmail

範圍部分就不用做選擇,直接點擊儲存並繼續

應用程式類型選擇電腦版應用程式
名稱可以自行定義,最後按下建立即可

順利建立好你的憑證嚕!
可以先點擊下方下載也可以按下完成後,憑證頁面也是有下載的地方。
接著點擊完成就可以了!

Google Drive API OAuth 同意畫面新增測試使用者
這時候不代表完成了,我們要去更改OAuth同意畫面的資訊
如果沒有更改的話,是沒有辦法順利授權的!
因此點擊OAuth同意畫面去新增測試使用者

點擊ADD USERS 新增測試使用者

一樣輸入登入GCP的帳戶,當然的你可以新增其他使用者的帳戶
當他們使用同一個憑證時,只要有符合測試使用者Gmail時,就會給於授權

回到憑證頁面,點擊下載icon也就是你的憑證
下載檔案會是一個json檔案

授權 OAuth 執行 Python 取得 Google Drive 目錄檔案名稱
下載後,先建立一個資料夾,把檔名修改為 credentials.json
另外在建立一個檔案叫做 quickstart.py
程式碼參考下方,直接複製儲存,不用作任何修改
再終端機執行 python3 quickstart.py
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
def main():
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
return
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
except HttpError as error:
# TODO(developer) - Handle errors from drive API.
print(f'An error occurred: {error}')
if __name__ == '__main__':
main()

會叫起瀏覽器,選擇你的google帳號
你會發現OAuth名稱會是你建立的對應名稱,像我的名稱就是Demo

這時候請點擊繼續,為何上面顯示這個應用程式未經Google驗證呢?
主要是我們還是在測試階段,如果上到正式的話,需要更完善的資料才行
但我主要是自己本地端使用,不需要上到正式。

點擊允許

授權給Demo 查看你的Google雲端硬碟檔案

搞定!授權成功嚕!

切回你的終端機查看,可以取得到你的Google Drive雲端目錄的資料名稱嚕!

Google API error 403: access_denied
假設你沒有將你的google帳號加入到測試使用者
想要授權成功,就必須新增 OAuth 同意畫面測試使用者或是更改資訊
出現下面的畫面,代表顯示授權錯誤

授權過後,再次執行還需要走這些流程嗎?
是不用的,再執行的資料夾下會自動產生一個 token
事後就不需要走這些過程嚕!
透過上面的教學,我們可以針對Google 提供的各種服務API,建立 OAuth 2.0憑證。
文章內的程式碼都可以直接複製下來練習操作,或是直接套用到自己的專案都行!
多練習,對自已會有很大的幫助!
一回生二回熟,將所學習到內容變成自己的知識。
人就是要學習自己不會的事情,這樣才會不斷的成長、進步!
更多技術文章
透過下方按鈕找尋到相關的技術文章,希望可以幫助到正在學習的你
加入到我的粉絲專頁,不定期發布最新文章資訊!
有任何文章問題都可以詢問喔!