Javascript - How to make REST API Calls - javascript

I am trying to access Firebase Database using REST API. Using cURL i am able to retrive data. I am unable to do the same in javascript.
cURL
curl 'https://testproject123.firebaseio.com/subscription.json?auth=aabbccddeeff123'
Javascript
var request = require('request');
var options = {
url: 'https://testproject123.firebaseio.com/subscription.json?auth=aabbccddeeff123' };
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
} }
request(options, callback);
Note: The above code i am trying to run on Bluemix/OpenWhisk.
Kindly let me know how to fix this.

The structure of your action is a bit off for OpenWhisk. Javascript actions need to have a main method and you'll have to use whisk.async() and whisk.done() to make your (asynchronous) REST API call work as you'd expect it.
An example of how to call an external API using a Javascript action in OpenWhisk can be found here.

Related

How to access data from "Passthrough" object returned after API call?

I am sending a fetch request with node-fetch to the following url: http://fantasy.premierleague.com/api/bootstrap-static/ in order to get back some JSON-data. Accessing the URL in the browser, or sending a get-request with postman both returns the expected JSON data.
However, when i send the request from node, I get back an object that I do not know how to extract the data from (pics below).
I am not very experienced with node but I have made successful API calls before. Usually parsing the response with response.json() or JSON.parse(response) or response.body or response.toString() or some combinations of those have worked for me. I am half familiar with buffers and streams, but not confident and the solution might be related to those, however I cannot seem to figure it out.
I get som different errors and objects depending on what I try. I have tried using fetch and just plain http requests from node.
This call:
Returns this:
If I do JSON.parse(response) i get the following error:
Response.body looks like this:
Fetch returns a response stream as mentioned here in the answer to a similar question
You can read data in chunks and add the chunk to array and then do whatever you need to do with that data. A simpler approach would be to use npm request package. Here's an example.
const request = require('request');
let options = {json: true};
const url = 'http://fantasy.premierleague.com/api/bootstrap-static/'
request(url, options, (error, res, body) => {
if (error) {
return console.log(error)
};
if (!error && res.statusCode == 200) {
console.log(body);
// do something with JSON, using the 'body' variable
};
});

how to call webapi at server startup in NodeJS

I have created a get web api that i want to hit at my server startup for some specific task. I have used this method
var request = require('request');
request('http://localhost:3000/api/jobs/asd', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the google web page.
}
}
)
But i am getting status code as 403. So i am not able to access my API at serve startup. Please suggest me the proper solution for the same.
thanks in adv.
You can place your code inside http callback like so :
http.createServer(app).listen(3000, () => {
//your code here
});

How to GET JSON Object from URL in Node.js/Express

I should preface my post by saying that I am a beginner and this is my first time using Node.js and Express in a real project.
I have a simple Node.js/Express project and I want to read a JSON object from a URL. Afterwards, I intend to build another url that displays html from an external website using iframe.
I read about the 'request' module online and know that I need to do something along these lines:
var express = require('express');
var router = express.Router();
var request = require('request');
// Urls for App Center REST functions
var url = 'https://someserver.com/appserver/portal/api/1.0/results/recent';
/* GET list of recent reports */
router.get('/testapi', function(req, res, next) {
res.render('testapi', { title: 'List Recent Reports' });
});
/* TEST: function to GET report list */
router.get('/recentreports', function(req, res){
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the json response
}
})
});
I have tried to define a function /recentreports which is called in the testapi.jade view, however nothing is printed in the console when I load the page and I suspect I am doing something horribly wrong.
My questions are:
How do I read the JSON into my app and where does this code go (index.js, app.js, testview.jade etc...?)
How do I export the URL I construct from wherever that code lives to my .jade view?
There was nothing logged to the browser console because no response was sent from your server. The response was only logged to the server's console.
You'll need to refactor the code for the 'recentreports' route to send data. You could use a simple res.send call:
...
function (error, response, body) {
if (!error && response.statusCode === 200) {
res.send(body) // Send the response to the client
}
}
...
This response will be received by testapi.jade via an AJAX call to the '/recentreports' route. The AJAX call can be defined in a Javascript file sourced by the testapi.jade file.
The constructed URL would not need to be exported as it exists within the same testapi.jade file (after you've formed it from the results from the AJAX call).

Setting Language of API in NodeJS

I am trying to implement the DuckDuckGo Instant Answer Api into my NodeJS application.
For that I request data from the Api using Node Request.
var request = require('request');
request('http://api.duckduckgo.com/?q=Hamburg&format=json&pretty=1', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.parse(body));
}
})
This gives me the result in English, but I would like to have it in German. In my browser it is in German. How can I change my code so I can get the data in German in NodeJS?
Thank you!
You can add the kad key with a proper locale.
As so:
http://api.duckduckgo.com/?q=Hamburg&format=json&pretty=1&kad=de_DE

Simple API Calls with Node.js and Express

I'm just getting started with Node, APIs, and web applications.
I understand the basic workings of Node.js and Express, but now I want to start making calls to other service's APIs and to do stuff with their data.
Can you outline basic HTTP requests and how to grab/parse the responses in Node? I'm also interested in adding specific headers to my request (initially I'm using the http://www.getharvest.com API to crunch my time sheet data).
P.S. This seems simple, but a lot of searching didn't turn up anything that answered my question. If this is dupe, let me know and I'll delete.
Thanks!
You cannot fetch stuff with Express, you should use Mikeal's request library for that specific purpose.
Installation: npm install request
The API for that library is very simple:
const request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the google web page.
}
})
Edit: You're better of using this library instead of the http default one because it has a much nicer API and some more advanced features (it even supports cookies).
UPDATE: request has been deprecated, but there are some nice alternatives still such as 'got' or 'superagent' (look them up on npm).
You can use the http client:
var http = require('http');
var client = http.createClient(3000, 'localhost');
var request = client.request('PUT', '/users/1');
request.write("stuff");
request.end();
request.on("response", function (response) {
// handle the response
});
Also, you can set headers as described in the api documentation:
client.request(method='GET', path, [request_headers])
Required install two package.
npm install ejs
npm install request
server.js
var request = require('request');
app.get('/users', function(req, res) {
request('https://jsonplaceholder.typicode.com/users', function(error, response, body) {
res.json(body)
});
});
index.ejs
$.ajax({
type: "GET",
url: 'http://127.0.0.1:3000/posts',
dataType: "json",
success: function(res) {
var res_data = JSON.parse(res);
console.log(res_data);
}
});
Output

Categories