I have this problem, i have been trying 2 days to solve it.
My Javascript code:
const request = require('request');
var req = {
url: 'https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql',
method: 'POST',
headers: { "Content-Type": "application/graphql" },
body: `{
stop(id: "HSL:1122441") {
stoptimesWithoutPatterns(numberOfDepartures: 1) {
realtimeArrival,
scheduledArrival,
realtime,
serviceDay,
headsign,
}
}
}`
};
request(req, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.stringify(JSON.parse(body), null, 4));
}
I want to get the data what the api sends back, into variables or somekind of thing, so i can call them anywhere in the script. The json data what comes back:
{
"data": {
"stop": {
"stoptimesWithoutPatterns": [
{
"realtimeArrival": 60065,
"scheduledArrival": 60000,
"realtime": true,
"serviceDay": 1547676000,
"headsign": "Olympiaterminaali via Kallio"
}
]
}
}
}
but when i use something about like this;
let stoptimesWithoutPatterns = body['stop'].stoptimesWithoutPatterns
it gives me error as
TypeError: Cannot read property 'stoptimesWithoutPatterns' of undefined
As im very new to coding coding, i dont know very tehnical stuff. It would be cool if somebody could help me :) as i wanted to have my own website or app based around this if i can get this to work! Thank you!
By using this i accomplished what i wanted, thank you guys who commented! :) This gives me the value of realtimeArrival! :)
const request = require('request');
var req = {
url: 'https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql',
method: 'POST',
headers: { "Content-Type": "application/graphql" },
body: `{
stop(id: "HSL:1122441") {
stoptimesWithoutPatterns(numberOfDepartures: 1) {
realtimeArrival,
scheduledArrival,
realtime,
serviceDay,
headsign,
}
}
}`
};
request(req, function (error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(JSON.parse(body));
//console.log(JSON.stringify(JSON.parse(body), null, 4));
let Parsed = JSON.parse(body);
let stoptimesWithoutPatterns = Parsed.data.stop.stoptimesWithoutPatterns[0]['realtimeArrival'];
console.log(stoptimesWithoutPatterns)
}
});
Related
I'm trying to develop a currency converter using node.js. I'm using 'request' to make HTTP requests.
Currently in my code, the query strings (q=1, from=USD, to=LKR) are hard coded in the url.
I want to know how to pass those strings as arguments in order to make it dynamic and get as many currency formats as I want.
var request = require('request');
const options = {
url : "https://currency-exchange.p.rapidapi.com/exchange?q=1&from=USD&to=GBP",
headers: {
'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
}
}
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(response.body);
}
}
request(options, callback);
You can use the qs parameter in the request library when performing a new request.
As specified here https://stackoverflow.com/a/16903926/7088387
You could use this:
const params = {
q: 1,
from: 'USD',
to: 'GBP'
};
const options = {
url : "https://currency-exchange.p.rapidapi.com/exchange",
headers: {
'x-rapidapi-host': 'currency-exchange.p.rapidapi.com',
'x-rapidapi-key': 'b13c4f3d67msh8143a7f1298de7bp1e8586jsn4453f885a4e7'
},
qs: params
}
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(response.body);
}
}
request(options, callback);
You could have a variable that stores those:
var currencies = ['USD', 'GBP'];
And then just put those variable values into your request string:
url : "https://currency-exchange.p.rapidapi.com/exchange?q=1&from=" + currencies[0] + "&to=" + currencies[1]
You could also use template literals using backticks like so:
url : `https://currency-exchange.p.rapidapi.com/exchange?q=1&from=${currencies[0]}&to=${currencies[1]}`
I'm trying to log into a loopback API I'm running on a web server using the standard POST login request. However every time I run it I get:
{"error":{"statusCode":400,"name":"Error","message":"username or email is required","code":"USERNAME_EMAIL_REQUIRED"}}
I've tried logging in two ways. firstly:
var userDetails = {
"email": "foo%40bar.com",
"password": "test"
}
const requestOptions = {
url: "APIURL/api/Users/login?email="+userDetails.email+"&password="+userDetails.password
};
request.post(requestOptions, function (error, response, body) {
console.log(body);
});
And:
var userDetails = {
"email": "foo%40bar.com",
"password": "test"
}
const requestOptions = {
url: "https://temp-243314.appspot.com/api/Users/login",
header: {
"email": userDetails.email,
"password": userDetails.password
}
};
request.post(requestOptions, function (error, response, body) {
console.log(body);
});
Where both return the same error.
I like it when I see ; at the end of declarations :/. your var declarations need a lil ; :D
I'm 99% sure they are going to want that in the body. Those headers that you show in your 2nd attempt are non-standard so they would be stripped from most inbound servers (As is standard for most ingest servers like NGINX) If they wanted a custom header, they probably would have noted it like, "X-email" or something weird.
IF you're going to send those elements in the "body", they probably want it in JSON format, in which case you need to designate json=true in the request function.
If sent in the body, don't url encode with the %40 in replacement of the #
5.
const request = require('request');
let options = {
uri: 'APIURL/api/Users/login',
method: 'POST',
json: {
"email":"foo#bar.com",
"password":"¡¡¡¡¡¡¡¡UNHACKABLE!!!!!!!!!"
}
};
request(options, function (err, resp, body) {
let isHTTPSuccess;
try {
isHTTPSuccess = resp.statusCode + '';
isHTTPSuccess = isHTTPSuccess[0];
if (isHTTPSuccess === '2'){
isHTTPSuccess = true;
} else {
isHTTPSuccess = false;
}
} catch(parseError){
console.error(parseError);
console.error(err);
return;
}
if (err || !isHTTPSuccess){
console.error(body);
return;
}
console.log('WOWZER, THE CODE ABOVE IS A BIT MUCH NO? ANYWAY... HERE IS THE BODY: ', body);
return;
});
Good Luck!
Your request should be like:
var userDetails = {
"email": "foo#bar.com",
"password": "test"
}
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.
For a homework (in Signavio Workflow Accelerator) I need to add users to an organization on Github using the GitHub-API v3. The Code has to be written in JavaScript which i a language I'm not very familiar with.
At the moment I get the following error code: "SyntaxError: Unexpected token o in JSON at position 1 at Request._callback". So I have the feeling that there might be a problem with the parsing.
var link = 'https://api.github.com/orgs/myorganization/memberships/' + githubUser
var token = 'mytoken'
request({url: link, method: 'put', headers: {'User-Agent': 'request'}, auth: {username: token}, JSON: true},
function (response, body) {
console.log(body)
if(body !== undefined){
body = JSON.parse(body)
body['state'][0]['main']
status = body['main']['state']
status = body.main.state
}
else{
status = 'error'
}
})
I don't know if this might be helpful, but if I perform this put request using cURL it works and the answer starts with:
{
"url": "https://api.github.com/orgs/myorganization/memberships/githubUser",
"state": "pending",
...}
So this "state" is the value I want to read in the code above.
Already thanks for helping!
I worked together with a friend of mine and together we found a working solution. So if anyone else is having the same struggle: This piece of code does the magic!
var link = 'https://api.github.com/orgs/myorganization/memberships/' + githubUser
var token = 'mytoken'
const options = {
url: link,
method: 'put',
headers: {'User-Agent': 'request'}, auth: {username: token}
}
function callback(error, response, body) {
console.log(error)
if(!error && response.statusCode == 200){
const info = JSON.parse(body)
status = info['state'][0]['main']
console.log(status)
status = info['state']
status = info.state
}
console.log(body)
}
request(options, callback)
I created a small api to generate test data on the fly. Each call creates a fresh user and returns the created data.
To load the data I use the package request:
var flow = protractor.promise.controlFlow();
var result = flow.execute(function() {
var defer = protractor.promise.defer();
request('http://localhost/test/recipe/person', function (error, response, body) {
if (!error && response.statusCode === 200) {
defer.fulfill(JSON.parse(body));
}
});
return defer.promise;
});
To make any use of the retrieved data I have to resolve the promise and proceed the test script inside a callback:
result.then(function(data) {
element(by.model('username')).sendKeys(data.person.email);
element(by.model('password')).sendKeys('test');
$('button[type="submit"]').click();
});
I don't like this callback handling and the possible hell it will lead to. Besides that, Protractor is so good in hiding this messy callback handling thingy. So, the question is:
How to use the result of an async call?
At the end I would like to perform code like the following:
var flow = protractor.promise.controlFlow();
var result = flow.execute(function() {...});
element(by.model('username')).sendKeys(result.person.email);
//...
Any ideas?
You can either make the http request synchronous - In most cases that's a bad thing to do.
Or, you can insert the callback into the execute function:
var flow = protractor.promise.controlFlow();
var result = flow.execute(function() {
var defer = protractor.promise.defer();
request('http://localhost/test/recipe/person', function (error, response, body) {
if (!error && response.statusCode === 200) {
defer.fulfill(JSON.parse(body));
}
});
defer.promise.then(function(data) {
element(by.model('username')).sendKeys(data.person.email);
element(by.model('password')).sendKeys('test');
$('button[type="submit"]').click();
});
return defer.promise;
});
but result will stay a promise.
It worked for me:
var request = require('request');
var options = {
method: 'POST',
url: 'http://testurl.com/endpoint/test/',
headers: {'id': 'ABCD',
'sessionid': 'dummyId',
'Accept': 'application/json',
'Accept-Language': 'en-us'
},
body: '{ "pay_load": [] }'
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(body);
console.log(info);
}
}
request(options, callback);