i want to download all the reports from service now from api without mentioning the report_id? - rest

https://instance.service-now.com/sys_report_template.do?CSV&jvar_report_id=xxxxx
This URL will only download report for which id is mentioned without mentioning the report_id how can i get all the reports?

This is some rough nodejs code, but should get you started;
var https = require('https');
var username = '';
var password = '';
var url = 'dev32369.service-now.com';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
https.request({
host: url,
port: 443,
path: '/api/now/table/sys_report?sysparm_query=field_listISNOTEMPTY&sysparm_fields=sys_id,title,filter,field,table,field_list&sysparm_limit=2',
method: 'GET',
headers: {
'Authorization': auth,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}, function (reportResponse) {
console.log('STATUS: ' + reportResponse.statusCode);
// console.log('HEADERS: ' + JSON.stringify(res.headers));
var reportResponseBody = '';
reportResponse.setEncoding('utf8');
reportResponse.on('data', function (chunk) {
reportResponseBody += chunk;
// console.log('BODY: ' + chunk);
});
reportResponse.on('end', function () {
var reports = JSON.parse(reportResponseBody).result;
console.log(reports);
if (reports[0].field_list != '') {
for (var x = 0; x < reports.length; x++) {
var report = reports[x];
var path = '';
path += '/api/now/table/' + report.table;
path += '?sysparm_fields=' + report.field_list;
path += '&sysparm_query=' + encodeURIComponent(report.filter);
path += '&sysparm_display_value=true';
path += '&sysparm_exclude_reference_link=true';
// path += '&sysparm_limit=2';
console.log(path);
var optionsCSV = {
host: url,
port: 443,
path: path,
method: 'GET',
headers: {
'Authorization': auth,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
console.log(optionsCSV);
https.request(optionsCSV, function (csvResponse) {
try {
var csvResponseBody = '';
csvResponse.on('data', function (chunk) {
console.log('downloading report[' + report.title + ']...');
csvResponseBody += chunk;
});
csvResponse.on('end', function () {
//console.log(csvResponseBody);
var csvResponseObj = JSON.parse(csvResponseBody).result;
console.log(csvResponseObj);
//this is a json obj but you can rewriet is csv here
});
csvResponse.on('error', function (err) {
console.log(err);
});
} catch (e) {
console.log(e);
}
}).end();
}
}
});
}).end();

Related

Sharepoint list item using Api Rest

I need to get a list's items, so I created this function
export function retrieveSPItems(spToken, alias) {
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/ItemCount`;
var myHeaders = new Headers({
Accept: "application/json;odata=nometadata",
Authorization: spToken,
});
return fetch(url, {
method: "get",
headers: myHeaders,
}).then((response) => response.json());
}
As a output I get 3000.
when I change the url to
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/Items`;
I get an empty list!
PS :
It's work in Postman with no problem
The token is generated by adaljs :
Get Token
authContext.acquireToken(SP_BASE_URL, function (error, token){....})
Adal config
export const adalConfig = {
tenant: CURRENT_TENANT,
clientId: CURRENT_APP_ID,
endpoints: {
api: CURRENT_APP_ID,
graph: GRAPH_BASE_URL,
sharepoint: SP_BASE_URL,
},
cacheLocation: "localStorage",
validateAuthority: true,
};
So I need to know :
what the reason fot this issue?
How can I fix it?
It's too general information, you need debug and figure out the detailed error information.
My test demo:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="Scripts/adal.js"></script>
<script type="text/javascript">
var authContext = null;
var user = null;
(function () {
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: 'xxx.onmicrosoft.com',
clientId: '9afc37cb-x-x-x-xxx',
postLogoutRedirectUri: window.location.origin,
endpoints: {
graphApiUri: "https://graph.microsoft.com",
sharePointUri: "https://xxx.sharepoint.com/",
},
cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
};
authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
//$errorMessage.html(authContext.getLoginError());
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
user = authContext.getCachedUser();
if (!user) {
authContext.login();
}
//authContext.acquireToken(window.config.clientId, function (error, token) {
// console.log('---');
//})
authContext.acquireToken(window.config.endpoints.sharePointUri, function (error, token) {
alert(token);
if (error || !token) {
console.log("ADAL error occurred: " + error);
return;
}
else {
var listUri = window.config.endpoints.sharePointUri + "sites/lee/_api/web/lists/GetByTitle('mylist')/items?$select=Title";
$.ajax({
type: "GET",
url: listUri,
headers: {
"Authorization": "Bearer " + token,
"accept": "application/json;odata=verbose"
}
}).done(function (response) {
console.log("Successfully fetched list from SharePoint.");
var items = response.d.results;
for (var i = 0; i < items.length; i++) {
console.log(items[i].Title);
$("#SharePoint").append("<li>" + items[i].Title + "</li>");
}
}).fail(function () {
console.log("Fetching list from SharePoint failed.");
})
}
})
}());
</script>

How to insert file to a shared drive using REST on Apps Script?

Is there a way that we can upload files to shared drive using POST Method? I don't know how to call the Drive ID of the shared drive and target it to the URL fetch function, is this possible?
This is my code:
var DriveScope = 'https://www.googleapis.com/auth/drive';
var ServiceAccountPrivateKey ="-----BEGIN PRIVATE KEY----"
var ServiceAccountEmail = "drive-uploads#xxxxxxx.com";
function testinRest(){
var service = getDriveService();
var driveID = "XXXXXXXX";
var APIKey = "XXXXXXXXXXXXX";
var resumeBlob = Utilities.newBlob('Hire me!', 'text/plain', 'resume.txt');
var formData = {
'name': 'Bob Smith',
'email': 'bob#example.com',
'resume': resumeBlob
};
var url = 'https://www.googleapis.com/drive/v3/drives';
var output = UrlFetchApp.fetch(url, {
method: 'get',
headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
contentType: 'application/json'
}).getContentText();
var response= JSON.parse(output);
for(var i=0; i < response.drives.length; i++){
if(driveID == response.drives[i].id){
service.reset()
if (service.hasAccess()) {
var newPresentationName = "RJ POGI";
var url = 'https://www.googleapis.com/upload/drive/v3/files?supportsAllDrives=true&key=' + APIKey;
var body = {
"name": newPresentationName,
"parents": [driveID]
};
var params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken(),
Referer:'https://explorer.apis.google.com'
},
method: 'post',
payload: formData,//JSON.stringify(body),
contentType: 'application/json',
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, params).getContentText();
Logger.log('response: ' + response);
var id = JSON.parse(response).id;
return id;
}
}
}
}
function getDriveService(){
var service = OAuth2.createService('drive').setTokenUrl('https://accounts.google.com/o/oauth2/token').setPrivateKey(ServiceAccountPrivateKey).setClientId(ServiceAccountEmail).setPropertyStore(PropertiesService.getUserProperties()).setScope(DriveScope);
//console.log("Service::" + service);
//console.log('Service Has Access::' + service.hasAccess());
if (!service.hasAccess()) {
Logger.log('Authentication error: %s', service.getLastError());
return;
}else{
return service;
}
}
function reset() {
var service = getDriveService();
service.reset();
}
On this example, I want the resumeBlob to be inserted on the targeted DriveID. Any help will be appreciated. Thanks!
Your problem needs to be divided in three steps:
Create a file on the drive with UrlFetchApp
Pass a content to the file
Insert the file into a shared drive
Now, you original question - 3. is easy to solve, you just need to specify in your requestsupportsTeamDrives=true.
More difficult is the combination of 1. and 2..
The Files: create method offers either an URI for media upload only requests, or for metadata-only.
The workaround would be to perform a resumable Upload, which allows you to post the metadata first, and add the file contents later.
The URI you need to use would be "https://www.googleapis.com/upload/drive/v3/files?supportsTeamDrives=true&uploadType=resumable".
Sample:
function uploadToSharedDrive(){
var url = "https://www.googleapis.com/upload/drive/v3/files?supportsTeamDrives=true&uploadType=resumable";
var resumeBlob = Utilities.newBlob('Hire me!');
var formData = {
'name': 'Bob Smith',
'mimeType': 'text/plain',
'parents': [
"ID of the shared drive"
]
};
params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
contentType: 'application/json',
method: 'post',
payload: JSON.stringify(formData),
}
var response = UrlFetchApp.fetch(url, params);
Logger.log(response.getContentText());
data = resumeBlob.getBytes();
var params2 = {
method: "put",
payload: data,
muteHttpExceptions: true,
};
var location = response.getHeaders().Location;
var response = UrlFetchApp.fetch(location, params2);
Logger.log(response.getContentText())
}

Facebook authentication with nodejs

I'm trying to authenticate user in facebook:
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');
getCookies(function(cookies){
logIn(cookies);
});
function logIn(cookies) {
var post_data = querystring.stringify({
'email': 'email#domain',
'pass': 'password'
});
var post_options = {
host: 'www.facebook.com',
port: '80',
path: '/login.php?login_attempt=1',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length,
'user-agent': 'Mozilla/5.0',
'set-cookie': cookies[0]
}
};
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
console.log(res.statusCode);
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
fs.writeFile("C:\\Users\\user\\Desktop\\fb.html", data, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
});
post_req.write(post_data);
post_req.end();
}
function getCookies(callback){
var get_options = {
host: 'www.facebook.com',
port: '80',
path: '/',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'user-agent': 'Mozilla/5.0'
}
};
var get_req = http.request(get_options, function(res) {
var cookies = res.headers['set-cookie'];
res.on('end', function (chunk) {
callback(cookies);
});
});
get_req.write('');
get_req.end();
}
But the response is that cookies in my browser are not enabled. Please don't suggest using existing libraries for connecting to facebook, I'm learning... Thanks for help in advance
Facebook uses OAuth authentication to authenticate an user. I have used oAuth module to get access to the Linkedin APIs at http://nabaruns.blogspot.in/2013/01/linkedin-api-call-using-nodejs-oauth.html. You can try the same and see if you can call graph facebook apis.
Hope this helps

How to post to facebook serverside with Node.js

As per the question title, I am trying to post to facebook serverside with node.js
Unfortunately there is something wrong with how I am doing it...
I am getting the error
{ [Error: socket hang up] code: 'ECONNRESET' }
app.post('/post/:id?', function(req, res)
{
var id = req.route.params.id;
var token = tokens[id].token;
var path = '/' + id + '/feed?access_token=' + token;
var message = "server side post to facebook";
console.log("post.id = " + req.route.params.id);
var jsonobject = JSON.stringify(
{
'message' : message
});
var options = {
host: 'graph.facebook.com',
port: 443,
path: path,
method: 'post',
headers: {
'content-type': 'application/json',
'content-length': jsonobject.length()
}
};
var req = https.request(options, function(res) {
console.log("statuscode: ", res.statuscode);
console.log("headers: ", res.headers);
res.setencoding('utf8');
res.on('data', function(d) {
process.stdout.write(d);
});
res.on('end', function(){ // see http nodejs documentation to see end
console.log("finished posting message");
});
});
req.on('error', function(e) {
console.error(e);
});
req.write(jsonobject);
req.end();
});
I am not sure exactly what I did, but after lots of hacking it seems to work...
So for anyone who is interested:
app.post('/post/:id?', function(req, res)
{
var id = req.route.params.id;
var token = tokens[id].token;
var path = '/' + id + '/feed?access_token=' + token;
var strToPost = "server side post to facebook";
console.log("post.id = " + req.route.params.id);
var post_data = querystring.stringify({
'message' : 'testing server side post'
});
var options = {
host: 'graph.facebook.com',
port: 443,
path: path,
method: 'POST',
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length' : post_data.length
}
};
var req = https.request(options, function(res) {
console.log("statuscode: ", res.statuscode);
console.log("headers: ", res.headers);
res.setEncoding('utf8');
res.on('data', function(d) {
console.log("res.on data");
process.stdout.write(d);
});
res.on('end', function(){ // see http nodejs documentation to see end
console.log("\nfinished posting message");
});
});
req.on('error', function(e) {
console.log("\nProblem with facebook post request");
console.error(e);
});
req.write(post_data);
req.end();
});

How to send facebook api batch request with node.js

How do I send facebook api batch request with node.js?
FB's examples do not work.
but I finally got danwong/restler.js to work like this:
exports.updateUserFriends = function (userData, next) {
var TOKEN = userData[1];
var fbID = userData[3].id;
var batchreq = {};
batchreq.batch = [];
batchreq.batch.push({"method":"GET", "relative_url":fbID+"/"});
batchreq.batch.push({"method": "GET", "relative_url":fbID+"/friends?limit=50"});
restler.post('https://graph.facebook.com?access_token='+TOKEN,
{data:"batch="+JSON.stringify(batchreq.batch)})
.on('complete', function(data) {
console.log(data);
return next;
});
};
So I thought I'd post this to save someone else a bit of frustration.
First thing to note is that, "Only POST is allowed for batch requests" in FB Api.
var https = require('https');
var url = '/?access_token='+ YOUR_ACCESS_TOKEN_HERE,
batch=[{
"method":"GET",
"relative_url":page + "/insights"
}, {
"method": "GET",
"relative_url":page
}];
url = url + '&batch=' + JSON.stringify(batch);
console.log(url);
var options = {
host:'graph.facebook.com',
path:url,
method: 'POST'
};
var req =https.request(options, function(res){
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
var body='';
res.on('data', function(chunk){
// console.log("body:" + chunk);
body += chunk;
});
res.on('end', function(){
var fbRes = JSON.parse(body);
console.log(fbRes);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();