Related
I'm trying to hit the Intercom API to retrieve a list of conversations and I can't figure out what's wrong. Here is the code:
const request=require('request')
const search_intercom=(admin_id, callback) => {
const options = {
url: 'https://api.intercom.io/conversations/search',
method: 'POST',
headers: {
Authorization: 'Bearer <token>'
},
json: {
query: JSON.stringify({
"field": "teammate_ids",
"operator": "=",
"value": admin_id
})
}
};
request(options, (error, {body} = {}) => {
if (error) {
callback('unable to connect to intercom API', undefined)
} else if (body.length === 0) {
callback('something went wrong', undefined)
} else {
callback(undefined, {
conversation_id: body.conversations[0].id,
client_name: body.conversations[0].source.author.name
})
console.log(body)
}
})
}
module.exports = search_intercom
I was able to wire it up correctly with the web server, so when I debug, options.json.query.admin_id does contain a valid id.
It breaks and says
conversation_id: body.conversations[0].id,
TypeError: Cannot read property '0' of undefined
Here is the content of the body response:
{
type: 'error.list',
request_id: '<some request_id>',
errors: [ { code: 'server_error', message: 'Server Error' } ]
}
Where should I look? I've tried a few different variations of options for sending the payload and I am guessing this is the issue, but I can't find the winning formula...
It looks like I got the body all wrong.
options should look like this instead:
const options = {
url: 'https://api.intercom.io/conversations/search',
method: 'POST',
headers: {
Authorization: 'Bearer <token>'
},
json: true,
body: {
query: {
"field": "teammate_ids",
"operator": "=",
"value": JSON.stringify(admin_id)
}
}
};
I'm trying to use the LinkedIn API to create a post using Node & Express with the node-fetch package to make the requests, however I always seem to get the error message "Empty entity body is not allowed for create method request" and I don't know how to resolve the error. I've included the body in the request but I guess not in the correct way. I also get the error code 400 so I know I'm doing something wrong, I'm just not sure what.
My questions are:
What is the entity body?
And how do I add it to my request?
function newPost(req, done) {
const id = "XXX";
const url = "https://api.linkedin.com/v2/ugcPosts";
const title = "Title title";
const text = "Text text";
const body = {
owner: `urn:li:person:${id}`,
subject: title,
text: {
text: text,
},
content: {
title: title,
},
};
const headers = {
'Authorization': `Bearer ${YYY}`,
'cache-control': 'no-cache',
'X-Restli-Protocol-Version': '2.0.0',
'x-li-format': 'json',
}
fetch(url, {
method: "POST",
headers: headers,
json: body,
}).then(res => res.json()).then(result => {
console.log(result);
const message = {
text: "Posted",
success: true,
}
done(message, "linkedin");
}).catch(err => {
console.log(err);
const message = {
text: "Failed",
success: false,
}
done(message, "linkedin");
});
}
As described in the to the doc, Post with JSON section, you should JSON.stringify the json body object, so try this:
fetch(url, {
method: "POST",
headers: headers,
json: JSON.stringify(body),
instead of:
fetch(url, {
method: "POST",
headers: headers,
json: body,
While calling fetch, you aren't passing body anywhere, you're passing json instead, which seems like a typo.
Existing code:
fetch(url, {
method: "POST",
headers: headers,
json: body,
}
What it should be instead:
fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(body),
}
I was trying Gmail APIs. Using POSTMAN I have created oAuth 2.0 token and was able to hit the URL https://www.googleapis.com/gmail/v1/users/xyz#gmail.com/profile. But when I was trying same with my node project where I invoked the same using :
app.get('/getMail',getMail); in my index.js where getMail is as follows
exports.getMail = (req, res) => {
request({
url: "https://www.googleapis.com/gmail/v1/users/xyz#gmail.com/profile",
method: "GET",
headers: {
Authorization: 'Bearer token'
},
json: true
}, function(response) {
console.log(JSON.stringify(response, null, 4));
return res.json(response);
});
But I am getting the response as null. Any help would be appreciated.
Please change the callback function to include error. The callbacks are usually error-first callbacks meaning first argument is always error.
exports.getMail = (req, res) => {
request({
url: "https://www.googleapis.com/gmail/v1/users/xyz#gmail.com/profile",
method: "GET",
headers: {
Authorization: 'Bearer token'
},
json: true
// Here -> error
}, function(error, response) {
if (error) throw new Error(error); // Handle the error here.
console.log(JSON.stringify(response, null, 4));
return res.json(response);
});
My problem was to upload the file from local directory to Azure Data Lake Store using Typescript only. I then found very useful REST API solution, I tested the REST API to perform all the required operations through postman and they worked fine, I then moved to Typescript to make these calls from typescript. Here is link to that: https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-data-operations-rest-api
To make REST CALLS through Typescript I'm using request-promise package, that I installed using npm install request-promise command. The documentation of this package is provided in this link:- https://github.com/request/request
But i'm able to perform all operations of the REST API i.e; Service-to-Service authentication, Creating Folder, Listing Folders, Rename File, Read File and so on. But i am not able to perform two operations/REST CALLS i.e; Upload File and Delete File, every time I make this call it gives Run Time Exception and error code 501 saying that this operation has not been implemented though i have tested these operations through Post Man and they work fine that way.
Is there any Access problem or what?
Here is the code of Typescript:
var fs = require('fs');
var request = require('request-promise');
var accessToken;
getAccessToken();
setTimeout(listFolders, 5000);
setTimeout(renameFile, 5000);
setTimeout(uploadData, 5000);
setTimeout(readData, 5000);
function getAccessToken() {
request(
{
method: 'post',
url: 'https://login.microsoftonline.com/067e9632-ea4c-4ed9-9e6d-
e294956e284b/oauth2/token',
form: {
grant_type: 'client_credentials',
resource: 'https://management.core.windows.net/',
client_id: 'dc9a4034-b03f-4974-9760-99541137a31c',
client_secret: 'mJ1Eba+sz0hXQko7gBN3D5WPDVLySCHXg4Mg5F4Ru4s='
},
json: true,
}, function (error, response, body) {
//Print the Response
accessToken = body.access_token;
console.log(accessToken);
});
}
function uploadData() {
fs.createReadStream('E:/accessToken.txt')
.pipe(request({
method: 'post',
url:
'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalytics/abc.txt?
op=CREATE',
json: true,
headers: {
"Authorization": "Bearer " + accessToken,
}
},
function (error, response, body) {
console.log(response.status);
}
));
}
function readData() {
request(
{
method: 'GET',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalyti
cs/readFile1.txt?op=OPEN'
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("\n\nData = "+body);
//console.log(response);
}
);
}
function listFolders() {
request(
{
method: 'GET',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/
iModelAnalytics?op=LISTSTATUS',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("************List Folders*****************\n ");
console.log(body);
}
);
}
function deleteFile() {
request(
{
method: 'PUT',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/
iModelAnalytics/readFile.txt?op=DELETE',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("***************Delete File*****************\n ");
console.log(body);
console.log('Response= \n');
console.log(response);
}
);
}
function renameFile() {
request(
{
method: 'PUT',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/
iModelAnalytics/readFile1.txt?
op=RENAME&destination=/iModelAnalytics/readFile2.txt',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("*************************Delete File*****************\n
");
console.log(body);
console.log('Response= \n');
console.log(response);
}
);
}
This is the error that I get:
Please share any thoughts regarding this.
Thanks a lot in advance.
PUT should be used to upload data whereas DELETE should be used to delete a file.
Append this &write=true to the query string when uploading data via pipe.
Try to change the code to:
function uploadData() {
fs.createReadStream('E:/accessToken.txt').pipe(request({
method: 'put',
url:'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalytics/abc.txt?op=CREATE&write=true',
json: true,
headers: {
"Authorization": "Bearer " + accessToken,
}
}, function (error, response, body) {
console.log(response.status);
}));
}
function deleteFile() {
request({
method: 'delete',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalytics/readFile.txt?op=DELETE',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true
}, function (error, response, body) {
//Print the Response
console.log("***************Delete File*****************\n ");
console.log(body);
console.log('Response= \n');
console.log(response);
});
}
I'm trying to get an individual change event using;
GET
* https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges('query')/item
Reference
http://msdn.microsoft.com/en-us/data/jj246759(v=office.12).aspx
And
http://msdn.microsoft.com/en-us/library/office/jj246759(v=office.15).aspx
I'm unable to get it working, and I can't find any example of this call.
I'm trying something like;
GET
https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges('Add=true,Item=true')/item
https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges(query='Add=true,Item=true')/item
but no luck.
FYI:: I'm not trying to get changelogs with this call. I'm trying to get an individual change item. But since the syntax is like that I put a random query in the those braces. The /getchanges(which is a POST call) works fine.
Any help on this?
There are at least two options how to construct request for a ChangeCollection endpoint:
Option 1
Post ChangeQuery via request body
function getChanges(webUrl,queryOptions,success,failure)
{
var changeQueryPayload = {
'query':{
'__metadata': { 'type': 'SP.ChangeQuery' },
}
};
for(var key in queryOptions) {
changeQueryPayload['query'][key] = queryOptions[key];
}
$.ajax({
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
data: JSON.stringify(changeQueryPayload),
url: webUrl + '/_api/web/getchanges',
success: success,
failure: failure
});
}
Option 2
Pass ChangeQuery expression via query string:
function getChanges(webUrl,queryOptions, success,failure)
{
$.ajax({
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
url: webUrl + '/_api/web/getchanges(#qry)?#qry=' + JSON.stringify(queryOptions) + ,
success: success,
failure: failure
});
}
Example
Retrieve updates for a web:
var queryOptions = {"Update":true,"Web":true};
getChanges(_spPageContextInfo.webAbsoluteUrl,queryOptions,
function(result){
var changes = result.d.results;
//print info
console.log('Found ' + changes.length + ' items');
},
function(error){
console.log(JSON.stringify(error));
});
Regarding requesting a specific change item, it could be retrieved from a results returned from REST service.
There is an example:
http://msdn.microsoft.com/en-us/library/office/dn499819(v=office.15).aspx
executor.executeAsync({
url: "<app web url>/_api/SP.AppContextSite(#target)/web/getchanges?#target='<host web url>'",
method: "POST",
body: "{ 'query': { '__metadata': { 'type': 'SP.ChangeQuery' }, 'Web': true, 'Update': true } }",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: successHandler,
error: errorHandler
});
Please refer https://msdn.microsoft.com/en-us/library/office/dn499819.aspx.
Following code is working for me.
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getchanges",
type: "POST",
data: "{ 'query': { '__metadata': { 'type': 'SP.ChangeQuery' },'Web': true, 'Update': true, 'Add': true } }",
headers: { "accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose",'X-RequestDigest':$('#__REQUESTDIGEST').val() },
success: successHandler,
error: errorHandler
});
function successHandler(data, textStatus, jqXHR ){
alert("successHandler " + "textstatus:" +textStatus + "data: " + data);
}
function errorHandler(xhr, ajaxOptions, thrownError) {
alert('Request failed: ' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
}