Friday, December 10, 2021

Upload Files on Google Drive using CURL

Initiate an automated backup on Google Drive using shell script.

Steps :

a) Generate client id and secret key.

b) Add Google logged in user as a Test user in consent screen.

c) Enable Google drive API

d) Generate Authorization Code (One Time)

https://accounts.google.com/o/oauth2/auth?client_id=xxxxxxxx&redirect_uri=http://localhost&response_type=code&scope=https://www.googleapis.com/auth/drive&access_type=offline
e) Generate Refresh Token (One Time)
curl --request POST --data "code=xxxxxxxx&client_id=xxxxxxxxxxxx&client_secret=xxxxxxxxxxxx&redirect_uri=http://localhost&grant_type=authorization_code" https://oauth2.googleapis.com/token
f) Generate Access Token (Always)
curl --request POST --data "client_id=xxxxxxxxxxx&client_secret=xxxxxxxxxxxxxxx&refresh_token=xxxxxxxxxxxxx&grant_type=refresh_token" https://oauth2.googleapis.com/token
g) Upload File on Google Drive (Always)
curl -X POST -L \
    -H "Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxx" \
    -F "metadata={name : 'imagename.png'};type=application/json;charset=UTF-8" \
    -F "file=@imagename.png;type=image/png" \
   "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"

Note : Refresh Tokens expire in 1 week if your app is not set as production. Change publishing status of your app from testing to production to use your refresh token always.

The Publishing Status option can be found in 'Oauth Consent Screen' which is under API & Services.

See complete instructions in this video. 

 



4 comments:

  1. I use procedure step by step, and one time it works.
    But in next times, it causes errors like invalid_grant/Bad_request,
    what should I do?

    ReplyDelete
    Replies
    1. It appears you are using incorrect authorization code. To generate Refresh token, you need to follow all the steps. Once the refresh token is generated, you can always generate access token using it.

      Delete
  2. Hello, I have the following problem when executing the command curl -X POST -L \ it returns the error curl: (3) URL rejected: Bad hostname
    greetings

    ReplyDelete