How to replace file in google drive using google drive API, Fix Error In google Drive API *fileIdInUse*

Viewed 178

It's been a while since I've worked with the Google Drive API. And I want to replace files using Google Drive API. I want to do that only using the Python HTTP requests module. Unfortunately, I always encounter an error. Could you please respond to this? It would be greatly appreciated.

CODE:

filedirectory = './Test.txt'
filename = 'Test.txt'
folderid = 'XXXXX'
updateFileId = 'XXXX'

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

metadataF= {
    'id':updateFileId,
    'fileId': updateFileId,
    'name': filename,
    'parents':[folderid]
}

files = {
    'data':('metadata', json.dumps(metadataF), '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,
)

Error:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "fileIdInUse",
    "message": "A file already exists with the provided ID."
   }
  ],
  "code": 409,
  "message": "A file already exists with the provided ID."
 }
}
<Response [409]>

It would be extremely helpful if you could assist me with this issue.

1 Answers

You are using the wrong end point and the wrong HTTP type.

You are using the Files.create end point.

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

To update an existing file you use Files.update

Which is a HTTP PATCH call and requires that you send the file id.

PATCH https://www.googleapis.com/upload/drive/v3/files/fileId

You need to remember to pass the id in the request. note the fileId part in the request above.

filedirectory = './Test.txt'
filename = 'Test.txt'
folderid = 'XXXXX'
updateFileId = 'XXXX'

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

metadataF= {
    'name': filename,
    'parents':[folderid]
}

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

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