Cascading two scripted API requests togethor - javascript

I am trying to check endpoint availability by cascading two api requests and passing first request's response(token) into another in authorization header field. Although the token is getting generated, the second api is not capturing the correct token in the 'token' variable. Let me know scripting error am making. Is there a way to print my authorization field value?
Output of the script is as below:
{
"error": "Invalid token."
}
401
AssertionError [ERR_ASSERTION]: Expected 200 response
Code:
var assert = require('assert');
var request = require('request');
var options2,token,info;
var options = {
'method': 'POST',
'url': '1',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'client_id': '*',
'client_secret': '**',
'grant_type': 'client_credentials'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
info = JSON.parse(response.body);
console.log(info.access_token);
token=info.access_token;
});
var request = require('request');
var options2 = {
'method': 'GET',
'url': '***',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
}
};
request(options2, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
console.log(response.statusCode);
assert.ok(response.statusCode == 200, 'Expected 200 response');
});

Move the call
request(options2, function (error, response),
inside the callback function of request 1, along with options2.
Since request 1 call (token one) can take some time your request 2 will be fired while you still haven't received response for token call. You can also use Async/Await to make it more clear, since callbacks makes things hard to read.

Related

Why is POST request showing undefined? Node JS

I am receiving a request response in the console.log, however when I try to post to Mastodon (similar site to Twitter), it posts as 'undefined'.
bot.js:
require('dotenv').config();
const Mastodon = require('mastodon-api');
var request = require('request');
console.log("Mastodon Bot starting...");
const M = new Mastodon({
access_token: process.env.ACCESS_TOKEN,
client_key: process.env.CLIENT_KEY,
client_secret: process.env.CLIENT_SECRET,
timeout_ms: 60*1000,
api_url: 'https://botsin.space/api/v1/',
})
const options = {
method: 'GET',
url: 'https://apisite.com/steps',
qs: {count: '3'},
headers: {
'X-RapidAPI-Key': 'secret-api-key',
'X-RapidAPI-Host': 'site-host',
useQueryString: true,
},
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(JSON.parse(body, undefined, 5));
});
const params = {
status: request
}
M.post('/statuses', params, (error, params) => {
if (error) {
console.log(error);
}
else {
console.log(params.request);
}
});
This posts "Mastodon bot is starting...", then the results of the API GET request to the console (the response body).
However, it does not post the response body to /statuses in Mastodon itself, it just posts 'undefined'.
How can I post the response body that I get in the console, to Mastodon?

Node.js - POST request won't execute until end of script

I'm trying to perform multiple POST requests in my code however the POST request will only occur when the script terminates. So far I've loaded the below code in via a function and imported the function as a module with no success.
I'm relatively new to node.js so I may be missing something obvious here. Does anyone have any ideas?
var request = require('request');
var options = {
'method': 'POST',
'url': 'https://XXXXXXXXXX.com/Example',
'headers': {
'Authorization': 'Basic SuperSecretPassword',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'To': Receiver,
'From': Sender,
'Parameters': '{"Flag":"1","Duration":"5"}'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
console.log(options);

get value from previous request and pass to another request in nodejs

I have a scenario where I am trying to get the parsed json response of the variable from the below POST request which I want to store in a variable and pass again to the next GET request in the headers. The approach that I am trying now doesn not give the expected results, Is there anything wrong here how should be my approach here to get the expected results, any help is appreciated.
PS : I am new to nodejs
var request = require('request');
var headers = {
'Accept': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Basic Y2Y6',
'Connection': 'keep-alive',
'Content-Length': '95',
'User-Agent': 'python-requests/2.22.0',
'content-type': 'application/x-www-form-urlencoded'
};
var dataString = 'grant_type=password&username=userpp&password=Password';
var options = {
url: 'https://testurl/oauth/token',
method: 'POST',
headers: headers,
body: dataString
};
let ab;
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(body);
var parsedBody = JSON.parse(body)
//console.log(parsedBody["access_token"])
ab = parsedBody["access_token"];
}
}
request(options, callback);
var headers1 = {
'Accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded',
'Authorization': `'bearer ' ${ab}`
};
var options1 = {
url: 'https://testurl1.com?getdata=user',
method: 'GET',
headers: headers1
};
function callback1(error1, response1, body1) {
if (!error1 && response1.statusCode == 200) {
console.log(body1);
}
}
request(options1, callback1);
The problem here is that you're running asynchronous code but treating it synchronously
You see, when you call request(options, callback); and then request(options1, callback1); inline like that, by the time the second request runs, the first callback hasn't happened yet
One way to get around this: put the second request INSIDE the first callback function.
Big brain time: use the request-promise library and learn how to make requests using promises and chaining .then() callbacks.
Humungous brain time: learn how to use async/await features as another nicer way to interact with promises

how to pass value in api body in protractor while requesting the api

I want to pass the value in API request body.
I tried below code for that
var options = { method: 'POST',
url: 'https://ssgpreprod.serviceurl.in/gonogo-api/atm/tw/cro-approval',
headers:
{ 'Postman-Token': '9d6a0ad1-c3a1-402f-b845-b6416f49df6b',
'cache-control': 'no-cache',
'Content-Type': 'application/json' },
body:
{ oHeader:
{ sReqType: 'application/json',
sAppSource: 'WEB 2.02.01',
sSourceID: 'GONOGO_HDBFS',
sAppID: 610961419000670,
dtSubmit: '',
sCroId: 'HDB_TW_CRO#cell.com',
sDsaId: 'default',
sInstID: 4019,
sUserName: 'CHDBTWCRO',
sProduct: 'TW',
sDealerId: '61096' },
sRefID:testData.twPreIpa.twReferenceId,
sAppStat: testData.twCroDetails.twCroDecision,
aCroJustification: [ { sRemark: testData.twCroDetails.twRemark, sSubTo: testData.twCroDetails.twSubjectTo} ],
bApprAmtExist: true,
dApprAmt: testData.twApplyDetails.twLoanAmount,
dItrRt: testData.twCroDetails.twRoi,
dLtv: testData.twCroDetails.twLtv,
aDedupeRefID: [] },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
browser.logger.info(JSON.stringify(body));
browser.logger.info(JSON.stringify(response));
browser.logger.info('status code is : ' + response.statusCode);
expect(response.statusCode).toBe(200).then(function () {
browser.logger.info('case is approved');
this.logOut(testData);
})
});
I am passing value from xlsx file i.e testData.twPreIpa.twReferenceId but I am getting 422 status code and below output
[2019-05-28 15:42:10.403] [INFO] : - {"title":"Conversion Failed","status":422,"detail":"The content you've sent is probably malformed."}
Also, when I add - browser.logger.info('approved'); above var options it prints on console.. but when I add - browser.logger.info(testData.twPreIpa.twReferenceId);
It gives me error .. ouput displayed -
Failed: Cannot read property 'twReferenceId' of undefined
TypeError: Cannot read property 'twReferenceId' of undefined
While this may not directly answer your question it should be helpful to you.
I worked on a similar framework to what (I assume) yours looks like,some api and some UI validations.
I had a separate class for my API calls which returned some value, sometimes the entire response body. I allowed myself the ability to pass in whatever body I needed as a parameter.
This is an example of the approach I took.
module.exports = class Endpoints {
addSomethingToUser(bearerToken, userId, JSONbody) {
//Function will preform a POST request and return the status code if successful
//Else if will return the body of the response
let endpoint = 'http://myApp.com:9090/api/users/' + userId;
return new Promise((resolve, reject) => {
let options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
body: JSON.stringify(JSONbody),
};
request(
endpoint,
options ,
function (error, response, body) {
if (!error && (response.statusCode >= 200 && response.statusCode < 300)) {
resolve(response.statusCode);
} else {
console.log('error:', error, response && response.statusCode);
reject(JSON.stringify(response, undefined, 2));
};
}
);
});
};
}
It is called like
let apiCallsFile = require('../apiCalls/restCalls');
let apiCalls = new apiCallsFile();
it('simple test', async function(){
let requiredBody = {
"NAME": "Test Name",
"GENDER": "MALE",
};
let apiResult = await apiCalls.addSomethingToUser(bearerToken, userId, requiredBody );
expect(apiResult).toBe('201');
}
Your issue seems to be related to the actual values you are using from excel. You should attempt to print out your values before attempting to send the request to ensure they are all present and in the format you expect.

Request keeps on getting Error code: 400 - can someone please have a look on what I'm doing wrong?

Spent a few hours trying to solve this but keep on getting 400 errors. I think my payload is incorrect but not sure what I need to do.
I've tried the same request in POSTMAN with great success, and also have tried different combinations on formatting my payload (body).
I've also tried the following: var body = {"document":{"type":"PLAIN_TEXT", "content":"This is great!!"}};
function main(){
// Set the headers
var headers = {
'Authorization': 'Bearer ya29.GlyvBPhT4Y502Yo4NZ6sKI001AYlVU6om5ytXrzf2vjfEYERrsdMSBu-2ZkKir83jjj06-ewqYuBvvrx8mKfuTW1YjjlmtPmRdlK0I0Gjx',
'Content-Type': 'application/json',
'User-Agent': 'Untitled browser'
}
var uri = 'https://language.googleapis.com/v1/documents'+encodeURI(':analyzeSentiment');
var form = JSON.stringify({"document":{"type":"PLAIN_TEXT", "content":"This is great!!"}});
// Configure the request
var options = {
url: uri,
method: 'POST',
headers: headers,
form: form
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
console.log(body)
}
else{
console.log('Error code: '+response.statusCode)
}
})
}
main();
Update - this is how it works in POSTMAN
Header is the same too:
Solved!
Need to post as body rather than form

Categories