I'm working on a Chrome Extension with the Drive API v3. My OAuth, API key and client_id are working fine. I'm having trouble fetching any data.
I used this as a starting point and it works fine for the People API. I modified the oauth.js code to this:
window.onload = function() {
document.querySelector('button').addEventListener('click', function() {
chrome.identity.getAuthToken({interactive: true}, function(token) {
let init = {
method: 'GET',
async: true,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json'
};
fetch(
//'https://www.googleapis.com/drive/v3/files?mimeType!=\'application/vnd.google-apps.folder\'',
//'https://www.googleapis.com/drive/v3/files?q=name%20contains%20\'Yamaha\'',
//'https://www.googleapis.com/drive/v3/files?name=\'Spices\'',
'https://www.googleapis.com/drive/v3/files?q=\'0Bxl5Z50oMH4MX2E0UXdhQUdUbGs\'',
init)
.then((response) => response.json())
.then(response => {
console.log(JSON.stringify(response))
console.log("Done stringify");
console.log(response);
console.log("Done response");
})
});
});
};
The commented lines are attempts at different fetch syntaxes.
For each of these attempts, I do not get any console errors but instead I get the following:
What is the missing piece? Ideally, I'd like to get all the files/folders, their ids and names!
You're facing issues with the query parameters in your fetch URL. Here's how to fix it:
Correct Query Syntax:
To list all files (not just folders), use:
'https://www.googleapis.com/drive/v3/files'
To filter by name:
'https://www.googleapis.com/drive/v3/files?q=name+contains+\'Yamaha\''
Get All Files with Metadata: Include fields to specify what you need (e.g., name, id):
'https://www.googleapis.com/drive/v3/files?fields=files(id,name)'
Fix Authorization Scopes: Ensure your OAuth scope includes https://www.googleapis.com/auth/drive.readonly.
Debugging Tips:
Log token to verify it's valid.
Check the API response status and errors.
Example full working snippet:
chrome.identity.getAuthToken({interactive: true}, function(token) {
fetch('https://www.googleapis.com/drive/v3/files?fields=files(id,name)', {
method: 'GET',
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
});
This should fetch all files with their IDs and names. If not, check scopes or token validity.