HASH
HASH

Reputation: 64

How to upload file to folder using google api

I am stuck at this point. Can somebody help me with how to upload files to a folder? using google drive API I am new using API and sending HTTPS requests. I added the parents section but it still upload the file to root.

import sys
import json
import requests
import sys

Refreshtoken = ""
params = {
       "grant_type": "refresh_token",
       "client_id": "xxxxx",
       "client_secret": "xxxxxxxxxxx",
       "refresh_token": "xxxxxxxxxxx"
       }

authorization_url = "https://www.googleapis.com/oauth2/v4/token"

r = requests.post(authorization_url, data=params)

if r.ok:
   token = str((r.json()['access_token']))
   Refreshtoken = Refreshtoken + token
else:
  print("Failed")
  sys.exit()


headers = {
       "Authorization": "Bearer " + str(Refreshtoken),
   }


metadata= {
   'name': "Test",
   'parents':"1vXn346cBsarvkPthqtI1OLzsMzeQQlBX"
}

files = {
   'data': ('metadata', json.dumps(metadata), 'application/json; charset=UTF-8'),
   'file': open("./test.txt", "rb"),
   }

r2= requests.post(
   "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
   headers= headers,
   files= files
)


print(r2.text)```

Upvotes: 2

Views: 1097

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116869

Parents is an array files.create

metadata= {
   'name': "Test",
   'parents': ["1vXn346cBsarvkPthqtI1OLzsMzeQQlBX"]
}

Have you considered using the Google Apis python client library?

Upvotes: 3

Related Questions