Google API demo does not work locally; GAPI is null - javascript

I copied Google's demo code from this tutorial:
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get
However, when I tried to run this locally, I get the error below.
testoJS.html:14 Uncaught TypeError: Cannot read property 'signIn' of null
at authenticate
I'm not sure why the gapi variable is null even though the code imports the api module beforehand.
Here is a copy of my code; my client id, api key, and spreadsheetid are correct - I tested those values in the above website's "try this API" section. The http request works great there and returns the spreadsheet's content. However, I can't seem to run it locally.
<html>
<head></head>
<body>
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for sheets.spreadsheets.values.get
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/spreadsheets.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("API_KEY");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/sheets/v4/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.sheets.spreadsheets.values.get({
"spreadsheetId": "SPREADSHEETID",
"range": "A1:D4"
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "CLIENT_ID"});
});
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
</body>
</html>

Related

Recover json data from youtube api call

I executed the code to retrieve the info from subscriber and all is well but the problem I can't get the info in json format
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for youtube.subscriptions.list
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("AIzxxxxxxxxxxx");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.youtube.subscriptions.list({
"part": [
"snippet,contentDetails"
],
"forChannelId": "UCASxxxxxxxxxxxx",
"mine": true
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
?????????????
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "5000000020-au42cxxxxxxxxxxxx.apps.googleusercontent.com"});
});
</script>
I looked at the console and I saw that the information is retrieved in response but not in json format
enter image description here
Once you have the response of the API, you need to check its content and get the values you need.
Example:
.then(function(response) {
// This is the response of the API.
console.log(response);
// Once you got the response, view its content.
// For example, if you want get the "results" value
// of the "response", use:
console.log(response.results);
},
function(err) {
console.error("Execute error", err);
});

bad request while using google index api in javascript

Hello evrey one i want to make a script that update my new urls of my website by using google indexing api from http://localhost:8000/test.html
i add http://localhost:8000 to Authorised JavaScript origins in the client ID
but i have error 400 :
Sign-in successful
cb=gapi.loaded_0:228 GET https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest?pp=0&fields=kind%2Cname%2Cversion%2CrootUrl%2CservicePath%2Cresources%2Cparameters%2Cmethods%2CbatchPath%2Cid&key='my api' 400
wh # cb=gapi.loaded_0:228
g # cb=gapi.loaded_0:228
xh # cb=gapi.loaded_0:229
(anonymous) # cb=gapi.loaded_0:229
d # cb=gapi.loaded_0:186
b # cb=gapi.loaded_0:181
Error loading GAPI client for API
{error: {…}}
error:
code: 400
message: "Request contains an invalid argument."
status: "INVALID_ARGUMENT"
__proto__: Object
__proto__: Object
i change the browser from chrome to edge it work one time then i shutdown my pc but day after the problem apear again.
i am using the api expoler script : link
i put the script and the console log as image
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for indexing.urlNotifications.publish
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({
scope: "https://www.googleapis.com/auth/indexing"
})
.then(function() {
console.log("Sign-in successful");
},
function(err) {
console.error("Error signing in", err);
});
}
function loadClient() {
gapi.client.setApiKey("My-API");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
.then(function() {
console.log("GAPI client loaded for API");
},
function(err) {
console.error("Error loading GAPI client for API", err);
});
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.indexing.urlNotifications.publish({
"resource": {
"url": "example",
"type": "URL_UPDATED"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) {
console.error("Execute error", err);
});
}
gapi.load("client:auth2", function() {
gapi.auth2.init({
client_id: "my OAuth client ID"
});
});
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
</body>
</html>
here the console log
thanx to god, i try loadClient then authenticate and it works
like this <button onclick="loadClient().then(authenticate)">authorize and load</button>
then i use chrome incognito
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for indexing.urlNotifications.publish
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/indexing"})
.then(function () { console.log("Sign-in successful"); },
function (err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("My API");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
.then(function () { console.log("GAPI client loaded for API"); },
function (err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.indexing.urlNotifications.publish({
"resource": {
"url": "my web site",
"type": "URL_UPDATED"
}
})
.then(function (response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function (err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function () {
gapi.auth2.init({client_id:"My client ID"});
});
</script>
<button onclick="loadClient().then(authenticate)">authorize and load</button>
<button onclick="execute()">execute</button>
</body>
</html>
GAPI client loaded for API
Sign-in successful
Response {result: {…}, body: "{↵ "urlNotificationMetadata": {↵ "url": "https…e": "2020-09-15T20:34:07.091671446Z"↵ }↵ }↵}↵", headers: {…}, status: 200, statusText: null}
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for indexing.urlNotifications.publish
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/code-samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/indexing"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("xxxxxxxxxxxxxxxxxxxx");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.indexing.urlNotifications.publish({
"resource": {}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "samplexxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"});
});
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
not working and
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for indexing.urlNotifications.publish
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/code-samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/indexing"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("xxxxxxxxxxxxxxxxxxxx");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/indexing/v3/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.indexing.urlNotifications.publish({
"resource": {}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "samplexxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"});
});
</script>
<button onclick="loadClient().then(authenticate)">authorize and load</button>
<button onclick="execute()">execute</button>
not working all error;
code code: 400
message: "Request contains an invalid argument."
status: "INVALID_ARGUMENT"

Getting File Not Found on Export of Google Drive

I'm getting a 404 file not found error when using the google drive v3 API. The file-Id I'm getting from google picker so I know the id is correct. The offending code is as following (javascript):
downloadFile: function () {
var _this = this;
gapi.client.init({
apiKey: this.developerKey,
clientId: this.clientId,
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
scope: 'https://www.googleapis.com/auth/drive'
}).then(function () {
// not working with private files
gapi.client.setToken(_this.oauthToken);
gapi.client.drive.files.export({
'fileId': _this.selectedFileId,
'mimeType': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}).then(function (response) {
console.log('success!');
});
}, function (error) {
console.log(error);
});
}, function (error) {
console.log(error);
});
}
Funnily enough it doesn't happen with all files only private files. So I assume the file not found error is just a generic response back from google indicating I wasn't allowed to access the file.
Oddly enough doing a files.get works fine:
gapi.client.drive.files.get({
fileId: _this.selectedFileId,
supportsTeamDrives: true
}).then(function (response) {
console.log('worked');
}, function (error) {
console.log('failed');
});
I saw this same error when I used the https://www.googleapis.com/auth/drive.file permission: to get export to work you need to have at least the https://www.googleapis.com/auth/drive.readonly permission granted to the OAuth token you are using.

Is there a way to execute spreadsheets.values.update without OAuth authentication?

I'm making a discord bot that will be open to the public to use, and it will work by updating a google spreadsheet with values given in a command. Unfortunately, from what I see in the API documentation's "Try this API" feature, I can only use Google OAuth v2. Using an API key as a form of authentication gives me the error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. How can I make it so that a user doesn't need to sign in for this to work?
This is the code:
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/spreadsheets"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/sheets/v4/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.sheets.spreadsheets.values.update({
"spreadsheetId": "1AFCiplLlZRdO5Phb4DUh8M8sKKnUimJftVDGH9UAA3M",
"range": "Ratings!H2",
"valueInputOption": "RAW",
"resource": {
"values": [
[
7.5
]
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: YOUR_CLIENT_ID});
});
Thank you if you can help me, this has been stumping me for a while now.
spreadsheet: https://docs.google.com/spreadsheets/d/1AFCiplLlZRdO5Phb4DUh8M8sKKnUimJftVDGH9UAA3M/edit#gid=569426832

web javascript Google Play API OAuth 2.0 access

Hello I have a problem with data loading from Google Play API. I tried to load leaderboard data from my game (Looney Invaders). I want show game statistic at my custom website. I tried to do this with "Google API Client Library for JavaScript" for "authorized" OAuth 2.0 access.
I used sample example of "authorized" access to a Google API (using OAuth 2.0).
Javascript code:
<script type="text/javascript">
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
//API key from google
apiKey: '***',
discoveryDocs: ["www.googleapis.com/discovery/v1/apis/games/v1/rest"],
//ClientID (for OAuth 2.0) from google develope console
clientId: '***',
scope: 'www.googleapis.com/auth/games'
}).then(function (data) {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
}, function (err) {
console.error('Our Error: ');
console.error(err);
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
makeApiCall();
}
}
function handleSignInClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignOutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
function makeApiCall() {
// Make an API call to the People API, and print the user's given name.
console.log('api call');
return gapi.client.games.leaderboards.list()
.then(function(response) {
console.log(response);
}, function(reason) {
console.log(reason);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
I test it locally at http://localhost, so I added "Authorized JavaScript origins" as localhost and "Authorized redirect URIs" as localhost/.
I have the following error result after API call (gapi.client.games.leaderboards.list()):
{
"error": {
"errors": [
{
"domain": "global",
"reason": "UserRegistrationIncomplete",
"message": "User has not completed registration."
}
],
"code": 401,
"message": "User has not completed registration."
}
}
Also initialization phase (gapi.client.init()) ends without any errors.
Please, help me to solve this problem, or tell what I do wrong?

Categories

Resources