How can I fix a parse error when making a post request with python?

Viewed 996
request = {
    "parents": ["1zaxxxxxxxxxxxxxxxZo"],
     "name": selected_name
    }
headers = {
     "Authorization": "Bearer "+creds.token,
     "Accept": "application/json",
     "Content-Type": "application/json"
     }
data = {
     "fileId": file_id,
     "request": request,
     "fields": "files(id)",
     "supportsAllDrives": True,
     "ignoreDefaultVisibility": True
     }
response = requests.post("https://www.googleapis.com/drive/v3/files/"+file_id+"/copy", data=data, headers=headers)
response = response.json()

I am trying to make a request to copy the file_id to the parent folder listed in my request. I am new to both google drive's api and making post requests, I can't understand what I'm doing wrong. I have been working on this issue for multiple hours now, and I'm getting a error response code 400, Parse Error. From what I have gathered, it means I'm formatting my request improperly. I've been trying different things for a long time now, I can't figure out how to make it properly. If anyone could help me it would be greatly appreciated, or point me to where to look to fix this issue on my own. I've been reading the docs, maybe I've bitten off more then I can chew. Thank you.

1 Answers

I believe your goal and situation as follows.

  • You want to copy a file on Google Drive using Drive API v3 with requests of python.
  • You have already had the access token for copying the file using Drive API.

In order to achieve your goal, I would like to propose the following modification.

Modification points:

  • Please set the values of fields, supportsAllDrives and ignoreDefaultVisibility to the query parameters.

  • Please modify fields from files(id) to id.

  • Request body is as follows.

      data = {
          "parents": ["1zaxxxxxxxxxxxxxxxZo"],
          "name": selected_name
      }
    
  • Please modify data=data to data=json.dumps(data).

When above points are reflected to your script, it becomes as follows.

Modified script:

import json
import requests

file_id = "###"  # Please set the source file ID.
selected_name = "###"  # Please set the filename.

headers = {
    "Authorization": "Bearer "+creds.token,
    "Accept": "application/json",
    "Content-Type": "application/json"
}
data = {
    "parents": ["1zaxxxxxxxxxxxxxxxZo"],  # Please set the folder ID.
    "name": selected_name
}
params = {
    "fields": "id",
    "supportsAllDrives": True,
    "ignoreDefaultVisibility": True
}
response = requests.post("https://www.googleapis.com/drive/v3/files/"+file_id+"/copy", data=json.dumps(data), params=params, headers=headers)
response = response.json()
print(response)

Result:

When above script is run, the following value is shown.

{'id': '###'}

Note:

  • This modified script supposes that your access token creds.token can be used for copying the file using Drive API. Please be careful this.

Reference:

Related