Calling a JSON API with Node.Js

Calling a JSON API with Node.js

The res argument in the http.get() callback is not the body, but rather an http.ClientResponse object. You need to assemble the body:

var url = 'http://graph.facebook.com/517267866/?fields=picture';

http.get(url, function(res){
var body = '';

res.on('data', function(chunk){
body += chunk;
});

res.on('end', function(){
var fbResponse = JSON.parse(body);
console.log("Got a response: ", fbResponse.picture);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});

Calling an existing API using Express passing json body

You don't necessarily need to pipe the req object to the request call in this case, you could just make a request.post call, you can still pipe the output from this, I think it will give you the result you wish:

let json = {"id": "", "name" : ""};

app.get('/createProduct/:product_id', function (req, res) {
let url = 'https://somewebsite/api/products';
// Create headers for outgoing call.
let headers = {
token: getToken(),
timestamp: getTimeStamp()
}
// Populate the json.id value.
json.id = req.params.product_id;
request.post({ url, headers, body: json, json: true }).pipe(res);
});

Also for testing purposes, I suggest you create a POST listener to see what you're passing to the service, you can easily do this in express:

app.post("/post_test", bodyParser.json(), (req, res) => {
console.info("/post_test: headers:", req.headers);
console.info("/post_test: body:", req.body);
res.status(201).send("All good");
})

To use this simply change the url in the app.get call to:

http://localhost:<port>/post_test

And remember to change back !

How to get multiple JSON APIs into a single page [Nodejs]

You need to make both API calls FIRST and then call res.render() when you have the combined results. The most modern way to do that would be to use promises and you can use the request-promise library for that which is a promisified version of the request library you are currently using:

const rp = require("request-promise");

app.get('/users', function (req, res) {

var url = apiUrl + '/users' + apiKey,
url_test = apiUrl + '/projects' + apiKey;

Promise.all([rp({uri: url, json:true}), rp({uri: url_test, json:true})]).then(([apiData, apiData-test]) => {
res.render('index', {apiData, apiData-test});
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
});

The json: true option will automatically parse the JSON for you.


In case you didn't know, the request() library and its derivatives are now in maintenance mode and will not be receiving any new features. There is a list of alternatives here. The one I am using is got() and your code using that would be this:

const got = require('got');

app.get('/users', function (req, res) {

var url = apiUrl + '/users' + apiKey,
url_test = apiUrl + '/projects' + apiKey;

Promise.all([got(url).json(), got(url_test).json()]).then(([apiData, apiData-test]) => {
res.render('index', {apiData, apiData-test});
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
});

How to Pass JSON Data into Express REST API

const jsonDoc = require('../Desktop/jsonDoc.json');// top of file...

router.get('/endpoint_get', function(req, res) {
try{
let jsonObj = JSON.parse(jsonDoc) /*{ "1": { "car_model": "Ferrari", "color": "Silver" }, "2": { "car_model": "Porsche", "color": "Green" }, "3": { "car_model": "Camry", "color": "Blue" } }*/
console.log(jsonObj)

res.json({
message: 'hooray! welcome to our api!',
jsonDoc:JSON.stringify(jsonObj)
});
/* returns {
"message": "hooray! welcome to our api!",
"jsonDoc": { "1": { "car_model": "Ferrari", "color": "Silver" }, "2": { "car_model": "Porsche", "color": "Green" }, "3": { "car_model": "Camry", "color": "Blue" } }
}*/

}catch(error){ /* now if anything above fails a error code can be returned to the caller and debug info can be sent to the developer*/
console.trace(error);// trace out the error.
res.sendStatus(500)// return error code to user.
}
});

Make a GET request to JSON API in Node.js?

var request = require('request');
request('<API Call>', function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body)
}
})

This will make an HTTP request to the API and upon success parse the response into JSON.

As far as getting the response onto a Jade page do you wish to do an API call (to your own server) and then use AngularJS/ jQuery/ another framework to fill in the information?

If you wish to add this to your own route consider embedding it like such:

var express = require('express');
var cors = require('cors');
var request = require('request');
var app = express();
app.use(express.bodyParser());
app.use(cors());
app.get('<Your Route>', function(req, res){
request('<API Call>', function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body)
// do more stuff
res.send(info);
}
})
});
app.listen(3000);
console.log("The server is now running on port 3000.");


Related Topics



Leave a reply



Submit