JavaScript Send JSON to Google API - javascript

I am new to the Google API (Calendar V3) and I have the authorization through obtaining a token working. I am using a get request to get the users calendar_Id in which I want to send in a POST request in order to add an event to the calendar.
Here is what I am working with:
var json_body = {
"end": {
"date": "2013-09-06"
},
"start": {
"date": "2013-09-06"
},
"summary": "test event 1"
};
var json_string = JSON.stringify(json_body);
http.setRequestHeader("Content-Type", "application/json");
http.setRequestHeader("Authorization","Bearer " + access_key);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert("in here");
alert(http.responseText);
}
}
http.send(json_string);
The response I am getting is:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
I know that the access_key authorization header is correct since it is not giving me the authorization error. I have ran this JSON structure in Googles API Explorer tool and it adds an element to my calendar correctly. I am assuming that the way I am building my JSON is incorrect. Any ideas?
Thank you in advance.
EDIT:
I found the correct solution. I was mis-using a parameter in the url request. The code above works in case anyone stumbles upon this for reference in the future.

Related

JSON post request shows 405 not allowed error (using XMLHttpRequest())

here's my js code:
var myreq=new XMLHttpRequest();
myreq.open("GET","https://<username>.github.io/test/data/data.json",true);
myreq.onload =function(){
console.log(JSON.parse(myreq.response));
}
myreq.send();
const data={
"name": "jayant",
"job": "leader"
};
function here()
{
var myreq1=new XMLHttpRequest();
myreq1.onload = () => {
// print JSON response
if (myreq1.status >= 200 && myreq1.status < 300) {
// parse JSON
const response = JSON.parse(myreq1.responseText);
console.log(response);
}
};
myreq1.open("POST",'https://<username>.github.io/test/data/data.json');
myreq1.setRequestHeader('Content-Type', 'application/json');
myreq1.send(JSON.stringify(data));
}
Function here is called on a button click
and here's my JSON code:
[
{
"name1":"jayant",
"age":58,
"pass":"LetsLearnJson"
},
{
"name1":"jayant2",
"age":45,
"pass":"ok"
},
{
"name1":"jayant3",
"age":24,
"pass":"test"
},
{
"name1":"abcd",
"age":75,
"pass":"abcd"
}
]
I am getting this error when I try to post:
POST https://<username>.github.io/test/%22https://<username>.github.io/test/data/data.json%22 405
Please help. I have tried many things already available online but nothing seems to work
The 405 Method Not Allowed Error occurs when the web server is configured so that you cannot perform a specific action for a specific URL. It is an HTTP response status code that indicates that the request method is known to the server, but is not supported by the target resource.

Google API Batch returns 401

Doing two or more requests in one batch at once leads to a 401 for each request.
const batch = gapi.client.newBatch();
batch.add(gapi.client.drive.files.list());
batch.add(gapi.client.drive.files.list());
batch.then((e) => {
console.log(e);
});
The error is:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Using only one batch.add works perfectly fine. It doesn't make any sense to me.
Why? What do I do wrong?
Directly from the documentation handle errors
401: Invalid Credentials
Invalid authorization header. The access token you're using is either expired or invalid.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization",
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Suggested action: Refresh the access token using the long-lived refresh token. If this fails, direct the user through the OAuth flow, as described in Authorizing Your App with Google Drive.
Batch documentation.
var searchRequest = function(name) {
return gapi.client.request({
'path': 'plus/v1/people',
'params': {'query': name}
});
};
var searchAlvin = searchRequest('Alvin');
var searchSimon = searchRequest('Simon');
// Adding just the request
batch.add(searchAlvin);
// Adding the request with an ID
batch.add(searchSimon, {'id': 'searchSimon'});

In a Camunda process, How can I retrieve a boolean value from JSON using JavaScript and Spin?

I have a service task which calls a REST API; the API is returning the following JSON:
{
"success": true,
"message": null,
"details": [],
"errors": [],
"transactions": []
}
The service task has a JavaScript output parameter to process the JSON output:
var statusCode = connector.getVariable("statusCode");
if (statusCode != 200) {
throw new Error(connector.getVariable("response"));
}
else {
var output = S(connector.getVariable("response"));
output.prop("success").value==true; // Problem line
}
I have sent the output to a process variable and confirmed that it contains the JSON above. However, I cannot get this output to ever register as true for the subsequent forking of the process. I have tried all of the following:
output.prop("success");
output.prop("success").value;
output.prop("success").value==true;
output.prop("success").value===true;
output.prop("success").value=="true";
Can anyone help with getting this right?
I got help with this in the Camunda forum here. My code now reads as below, and works as desired:
var statusCode = connector.getVariable("statusCode");
if (statusCode != 200) {
throw new Error(connector.getVariable("response"));
}
else {
var output = S(connector.getVariable("response"), "application/json");
output .prop("success").boolValue();
}

How can I retrieve a service account OAuth2 token from Google Api with Javascript?

I need to use a google projects service account to access google API using JavaScript. In order to do this I need to OAuth2 to google API servers to get an auth token.
I understand that Google provides a library (GAPI) for use on node servers, but I need a solution that will work in other secure JavaScript environments.
There are two major divisions to this task.
Configuring
Coding
First the Configuration steps.
If you don't have a google account:
Navigate to google.com
Find and Click "Sign In"
Click "More Options"
Click "Create Account"
Follow the steps to create an account
Navigate to the api dashboard: console.developers.google.com/apis/dashboard
Select or create a project by clicking on the current project. The project I have showing is called "My Project"
Click and enable those API you plan to work with
navigate to the credentials section: console.developers.google.com/apis/credentials
Click and select "Service account key"
If you create a new service account, for testing set the role to "project" "owner". You'll want to read up on google Api roles eventually. See Managing Roles and Granting Roles to Service Accounts
Ensure "Key Type" is "Json" and click "Create". You're key/cert will automatically download
Now for the Coding portion.
First download jsrsasign and add reference to "jsrsasign-all-min.js". If you want you can download just "jsrsasign-all-min.js" from github
Second update the following script with your cert/key (downloaded earlier):
function postJWT(jwt, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200 && callback) {
callback(this.responseText);
return;
}
if (console) console.log(this.responseText);
}
};
var parameters = "grant_type=" + encodeURIComponent("urn:ietf:params:oauth:grant-type:jwt-bearer") + "&assertion=" + encodeURIComponent(jwt);
xhttp.open("POST", "https://www.googleapis.com/oauth2/v4/token", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(parameters);
}
function getCert() {
var cert = //your json key (downloaded earlier) goes here
{
"type": "service_account",
"project_id": "proj..",
"private_key_id": "e18..",
"private_key": "-----BEGIN PRIVATE KEY-----\nMII..==\n-----END PRIVATE KEY-----\n",
"client_email": "service-account#...iam.gserviceaccount.com",
"client_id": "5761..",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/..service-account%40...iam.gserviceaccount.com"
};
return cert;
}
function getJWT() {
var cert = getCert();
var key = KEYUTIL.getKey(cert.private_key);
var headers = { "alg": "RS256", "typ": "JWT" };
var issued = Math.floor(new Date().getTime()/1000);
var claims = {
"iss": cert.client_email,
"scope": "https://www.googleapis.com/auth/analytics.readonly",
"aud": "https://www.googleapis.com/oauth2/v4/token",
"exp": issued + 3600,
"iat": issued
};
var jwt = KJUR.jws.JWS.sign(headers.alg, headers, JSON.stringify(claims), key);
return jwt;
}
When you test your code you should receive a json object back with an auth token. You can test your implementation like so:
postJWT(getJWT(text), function(){
let token = JSON.parse(response).access_token;
//Do your api calls here using the token.
//Reuse the token for up to 1 hour.
});
Here is an example successful json object with token:
{
"access_token": "ya29.c.ElkABZznrLNLK6ZAq2ybiH5lsRJpABE8p7MlZZJ0WCKcDNDv75lh-o1iRX__uMNUKSySiawm4YJGsbfqJH2JH61nRK6O2m0GJR7DgkEmo6ZlKtrvzke9C3xpwA",
"token_type": "Bearer",
"expires_in": 3600
}
Please note that this approach requires that the key/cert be accessible from your javascript environment. If this environment is public your api is vulnerable.

Authentication issue with simple upload on Google Drive API

I'm trying to upload a file to my Google Drive file space, and I'm using the following code:
var httpRequest = new XMLHttpRequest();
var url_goto = "https://www.googleapis.com/upload/drive/v2/files?uploadType=media";
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState==4 && httpRequest.status==200) {
Firebug.Console.log(httpRequest.responseText);
} else if (httpRequest.readyState==4 && httpRequest.status==401) {
Firebug.Console.log(httpRequest.responseText);
} else {
Firebug.Console.log('Other status: ' + httpRequest.readyState + ', ' + httpRequest.status);
}
};
var s = 'Test string';
httpRequest.open('POST', url_goto, true);
httpRequest.setRequestHeader('Content-Type', 'text/plain');
httpRequest.setRequestHeader('Content-Length', s.length);
httpRequest.setRequestHeader('Authorization', 'MY_AUTH_KEY');
httpRequest.send(s);
The problem is that I've the following output:
"Other status: 1, 0"
"Other status: 1, 0"
"Other status: 2, 401"
"Other status: 3, 401"
...and an exception is thrown:
"{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}"
Can anybody help me to understand why authentication is not working?
I'm using the API Key retrieved from my Google APIs Console, under section Simple API Access.
Thanks!
If you are using oauth2 token then you must specify the Bear along with auth token in Authorization header like
httpRequest.setRequestHeader("Authorization", "Bearer MY_AUTH_KEY");

Categories

Resources