ResMar ResMar - 4 months ago 22
JSON Question

Accessing an API endpoint on the same website using D3.JS

I am putting together a D3.JS visualization, as a part of which I have created a MongoDB database and exposed it via an API endpoint on my webservice. I am using Python

Flask
to do this.

I've validated that the data emitted is in valid JSON format and I've made sure to set the MIME type to
application/json
. However, while in visiting the URL in question everything is fine, when I try to call into that URL using
d3.json
:

d3.json("http://127.0.0.1:5000/citibike-api/bike-inbounds/id/72", function (data, error) {
if(error) throw error;
console.log(data);
});


Console yells at me:

uncaught exception: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]


Are there other things that I need to do to make this request work?

Do I need something with
JSONP
to do this?

Answer

Swap data with error. Instead of:

d3.json("http://127.0.0.1:5000/citibike-api/bike-inbounds/id/72", function (data, error) {
    if(error) throw error;
    console.log(data);
});

It should be:

d3.json("http://127.0.0.1:5000/citibike-api/bike-inbounds/id/72", function (error, data) {
    if(error) throw error;
    console.log(data);
});

Explanation

According to the API, in d3.json...

...the callback is invoked with two arguments: the error, if any, and the parsed JSON

The argument error is optional. You can just write:

function (data){

But, if you use the argument error, the sequence has to be:

function (error, data){