I’m having trouble with the Google Drive API. My function should duplicate a document and rename it, but something weird is happening. When I try to change the title of the copied file, the API overwrites the entire document content with my request parameters instead of just updating the filename.
function duplicateAndRename(category, sourceFileId){
var token = gapi.auth.getToken().access_token;
var newName = "Report - " + category + " " + getCurrentDate();
// First copy the original document
fetch('https://www.googleapis.com/drive/v3/files/' + sourceFileId + '/copy', {
method: "POST",
headers: new Headers({ 'Authorization': 'Bearer ' + token})
})
.then(response => response.json())
.then(function(result) {
// Try to update the title of the copied file
fetch('https://www.googleapis.com/upload/drive/v2/files/' + result.id, {
method: "PUT",
headers: new Headers({ 'Authorization': 'Bearer ' + token}),
body: JSON.stringify({'name': 'updated document'})
});
console.log(result);
window.open("https://docs.google.com/document/d/" + result.id + "/edit");
});
}
Instead of just changing the filename, the document body gets replaced with my JSON data. What am I doing wrong here?
ah i see the issue - you’re using the upload url which treats everything as file content replacement. try removing /upload from your second fetch url and use PATCH instead of PUT. also make sure to set content-type header to application/json or it might get confused about what you’re sending
The upload endpoint is your problem. I encountered the same issue six months back while building a document automation tool. That /upload path only handles file content, not metadata updates. When you send JSON there, the API assumes you’re replacing the file content rather than updating metadata. You’re also mixing v3 and v2 APIs; your first request uses v3, then you switch to v2 with the upload path. Stick with v3 and drop the upload prefix from your files endpoint. Additionally, consider implementing error handling for both requests, as Drive API calls can fail silently, which might leave you with incomplete operations.
You’re mixing API versions and hitting the wrong endpoint. You’re doing a v3 copy but then switching to the v2 upload endpoint for metadata updates - that’s what’s killing your content. Stick with v3 for everything. After copying, use the regular v3 files endpoint (drop the upload prefix) to update just the metadata. Replace your second fetch with: fetch(‘https://www.googleapis.com/drive/v3/files/’ + result.id, { method: “PATCH”, headers: new Headers({ ‘Authorization’: 'Bearer ’ + token, ‘Content-Type’: ‘application/json’ }), body: JSON.stringify({‘name’: newName}) }); The upload endpoint is meant for file content uploads - that’s why it’s overwriting your document body. PATCH works better than PUT here since you’re only updating specific fields, not replacing everything.