Search Contacts with SendGrid API - node.js

https://sendgrid.api-docs.io/v3.0/contacts/search-contacts
I'm attempting to search for a contact as shown in SendGrids docs above. In the body section below I'd like to change the hard coded "andrew#gmail.com" to be a variable. Such as email = req.user.email; What is the correct way to do that? Just setting the variable and dropping in 'email' does not work.
var request = require("request");
var options = { method: 'POST',
url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
headers:
{ 'content-type': 'application/json',
authorization: 'Bearer SG.key' },
body: { query: 'email LIKE \'andrew#gmail.com\' AND CONTAINS(list_ids, \'6bcc2d0c-ea17-41ba-a4a1-962badsasdas1\')' },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

Twilio SendGrid developer evangelist here.
Try using string interpolation using back ticks (which, as an added bonus, means you don't have to escape your single quotes), like below:
const email = req.user.email;
const body = `email LIKE '${email}' AND CONTAINS(list_ids, '6bcc2d0c-ea17-41ba-a4a1-962badsasdas1')`;
const options = {
method: 'POST',
url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
headers: {
'content-type': 'application/json',
authorization: 'Bearer SG.key'
},
body: { query: query },
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

Related

How to do a GET request with node.js passing a JWT token in header

I have been trying to do a GET request to my server which has is running locally on port 4000.
I generate a JWT token and pass it in the header as follows
var request = require('request');
var options = {
'method': 'GET',
'url': 'localhost:4000',
'headers': {
'JWT': '<JWT PASTED HERE>',
'Content-Type': 'application/json'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
But I keep getting
{"errors":[{"title":"invalid_request","id":"Requesting stuff","meta":{"server-time":1591980353},"errorCode":"bad-request","status":400,"detail":"This JWT has invalid path parameter"}],"error_description":"This JWT has invalid path parameter","error":"invalid_request"}
My JWT is correctly created, I verified it in https://jwt.io/
Is it because 'request' module is deprecated in node.js?
Is there another way I can achieve the below?
Try this one
var request = require('request');
var options = {
'method': 'GET',
'url': 'localhost:4000',
'headers': {
'Authorization': 'Bearer <JWT PASTED HERE>',
'Content-Type': 'application/json'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
or
var options = {
'method': 'GET',
'url': 'localhost:4000',
'headers': {
'Authorization': 'JWT <JWT PASTED HERE>',
'Content-Type': 'application/json'
}
};
Bearer or JWT depends how it is defined in backend

Getting error "Image file or image_id string must be include", Am i missing something? ETSY Image Upload

Trying to upload Listing image using ETSY Listing Image API
I am fetching "image_id" & "image" from front-end part.
var request = require("request");
var options = { method: 'POST',
url: 'https://openapi.etsy.com/v2/listings/724108136/images',
qs: { oauth_consumer_key: '*********************',
oauth_token: '****************',
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: '**********',
oauth_nonce: '*************',
oauth_version: '1.0',
oauth_signature: '*********************'
},
headers:{
'Content-Type': 'multipart/form-data'
},
encoding: null,
responseType: 'buffer',
data:{
image_id:req.body.image_id,
image:req.files.image
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body) // Image file or image_id string must be included
});
I think that there is a few things wrong with this.
It looks like you're passing the OAuth info via in the querystring and not in the headers.
You might want to bump up your request version. I have confirmed this is working with "request": "^2.88.2",
`
const request = require("request");
let options = {
'method': 'POST',
'url': 'https://openapi.etsy.com/v2/listings/724108136/images',
'headers': {
'Authorization': 'OAuth oauth_consumer_key="********",oauth_token="***********",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1585021862",oauth_nonce="*******",oauth_version="1.0",oauth_signature="********"',
'Content-Type': 'multipart/form-data'
},
formData: {
'image': {
'value': fs.createReadStream('./temp/abc123.jpg'),
'options': {
'filename': 'my-shirt.jpg',
'contentType': null
}
}
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body)
});
`

How to upload File to Azure Data Lake through Typescript REST CALLS

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);
});
}

csrf token validation fail in post request while calling sap odata service

var Array = require('node-array');
var request = require("request");
username = "user24",
password = "",
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var options = { method: 'GET',
url: "http://207.188.73.88:8000/sap/opu/odata/sap/ZTEE_SUGGEST_SRV/ZteeSuggestSet?$filter=Number eq 5 and Date eq datetime'2014-03-11T00%3A00%3A00'&$format=json",
headers:
{
i am fetching xcsrf token here
'x-csrf-token': 'fetch',
'content-type': 'application/json',
authorization: auth } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
// console.log(response.headers['x-csrf-token']);
var token="'";
token+=response.headers['x-csrf-token'];
token+="'";
//console.log(token);
var options = { method: 'POST',
url: 'http://207.188.73.88:8000/sap/opu/odata/sap/ZTEE_TIME_SRV/ZTEERESERVESet',
and setting the csrf token here but it give me error that scrf token required or invalid
headers:
{
authorization: auth,
'x-csrf-token': token,
'content-type': 'application/json' },
body:
{ Time: 'time\'PT11H00M00S\'',
Date: 'datetime\'2014-03-11T00%3A00%3A00\'',
Location: 'AAJ',
Number: 3 },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
// console.log(body);
here it shows that token rrequired but i am already setting that in header
console.log(response.headers['x-csrf-token']);
});
});
I had faced similar situation while working with SAP WEBIDE.
I had disabled the request for token and i was able to establish the connection with Odata services. I did something like this code snippet in my component.js file.
var oModel = new sap.ui.model.odata.ODataModel(this.getMetadata().getConfig().serviceUrl);
oModel.disableHeadRequestForToken = true;
serviceURL contained the URL to Odata Service.
You can try to disable the CSRF token request and check.

How to properly use putAsync

I searched here and there and ended up with no finding regarding putAsync method of promisified request by bluebird.
var request = require('request');
var Promise = require('bluebird');
Promise.promisifyAll(require("request"));
request.putAsync({
uri: buApiUrl,
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
name: BU,
workstations: formattedWorkStaions[BU]
})
}).spread(function (response, body) {
debugHelper.log(body);
}).catch(function (err) {
debugHelper.error(err);
});
Above is the code snippet that is in my program. And it does not send put request. While using postAsync, if will send post request successfully.
Your code seems fine to me.
Example
var request = require('request');
var Promise = require('bluebird');
Promise.promisifyAll(require("request"));
request.putAsync({
uri: 'https://httpbin.org/put',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
name: 'anon'
})
}).spread(function (response, body) {
console.log(body);
}).catch(function (err) {
console.error(err);
});
OR you can just pass JSON body like this -
request.putAsync({
uri: 'https://httpbin.org/put',
json: { name: 'anon' }
})
....
Make sure the API end-point is taking PUT requests and the variables BU,formattedWorkStaions[BU] are properly defined. I guess formattedWorkStaions should be formattedWorkStations?

Resources