Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I upload file to google drive using drive API using python?

I want to upload a file to google drive using its API, I am using the code

def newer():
    url= 'https://USERNAME:[email protected]/upload/drive/v3/files?uploadType=media'
    data='''{{
      "name":"testing.txt",
    }}'''
    response = requests.post(url, data=data)
    print response.text

However, I am getting response error message as below.

{ "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "HTTP Basic Authentication is not supported for this API", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "HTTP Basic Authentication is not supported for this API" } }

Is there some other way to do my job using python.

Should I need to sign in to google cloud to access API for authentication token or credentials

like image 234
Deepak N Avatar asked Dec 14 '22 16:12

Deepak N


1 Answers

Finally I Understood how do I upload file to google drive using api.

first you need to install python library which gives the methods to use drive api. installing the library: pip install google-api-python-client then code as below.

from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from apiclient.http import MediaFileUpload,MediaIoBaseDownload
import io

# Setup the Drive v3 API
SCOPES = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
drive_service = build('drive', 'v3', http=creds.authorize(Http()))

above code snippet is to create object/variable which allow you to get inside the drive with a right credential. here drive_service does that work.

File uploading code is below here.

def uploadFile():
    file_metadata = {
    'name': 'fileName_to_be_in_drive.txt',
    'mimeType': '*/*'
    }
    media = MediaFileUpload('Filename_of_your_local_file.txt',
                            mimetype='*/*',
                            resumable=True)
    file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
    print ('File ID: ' + file.get('id'))

The file ID is important because if you want to download the file from the drive you need the file ID.

like image 71
Deepak N Avatar answered Dec 29 '22 11:12

Deepak N