I created a key in the google cloud console. I even tried remaking it and using a the new one.
Im trying to use it like so:
export const getSheet= async () => {
try {
const sheetId ='xxxxxxx'
const tabName = 'myTab'
const accountKey = 'xxxxxxx'
const url =' https://sheets.googleapis.com/v4/spreadsheets/' sheetId '/values/' tabName '?key=' accountKey
console.log(url)
const response = await fetch(url);
console.log(response);
return '';
} catch (error) {
console.log(error);
} finally {
console.log('finally');
}
};
The request being sent is:
https://sheets.googleapis.com/v4/spreadsheets/xxxxxxx/values/myTab?key=xxxxxxx
No matter what I do I get
error: {code: 403, message: "The caller does not have permission", status: "PERMISSION_DENIED"}
Ive refered to these stack overflow posts regarding the same issue with no luck
- Error 403 on Google Sheets API
- Google Sheets API V4 403 Error
- Getting 403 from Google Sheets API using apikey
Has anyone come across this and was able to fix it?
Thanks -Coffee
CodePudding user response:
You can't use an API key to access (Google Workplace) user data such as sheets; you may (!?) be able to get away with only use an API Key if the sheet were public (anyone with the link).
The options are admittedly confusing but:
- API keys authenticate apps
- OAuth is used to authenticate users
Have a look at authentication & authorization and OAuth for client-side web apps.
CodePudding user response:
You can look through the Javascript Quickstart guide for Sheets API for the OAuth Setup. And you can access the sheet using Spreadsheet.values.get
method similar to this sample script on the provided URL reference.
async function listMajors() {
let response;
try {
// Fetch first 10 files
response = await gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: 'SHEETID',
range: 'SHEETRANGE',
});
} catch (err) {
document.getElementById('content').innerText = err.message;
return;
}
const range = response.result;
if (!range || !range.values || range.values.length == 0) {
document.getElementById('content').innerText = 'No values found.';
return;
}
And just like what DazWilkin provided. Make sure that your app complies with Google's OAuth2 policies.
You can also test your request url first on a browser and see if it returns a JSON response of the sheet data. Tested this https://sheets.googleapis.com/v4/spreadsheets/xxxxxxx/values/myTab?key=xxxxxxx
format on a public sheet, and it returned the sheet data as long as it is set to 'Anyone with the link'