question

newuser-e7dd118c-f137-4191-a7a6-a4d85f3414c1 avatar image

Use a different API in City Guide Example - Instagram

I'm new to developing and I'm trying to modify the City Guide Example. I want to make a get request to Instagram to tell how many users follow the account. The link and api key is working correctly, I can put this in the browser and get the response, but nothing is being added to the body variable when this function is run.

function httpGet(callback) {
    console.log("/n QUERY: "+query);


    var options = {
        //https://api.instagram.com/v1/users/self/?access_token=ACCESS-TOKEN
        host: 'api.instagram.com',
        path: 'v1/users/self/?access_token=' + APIKey,
        method: 'GET'
    };


    var req = http.request(options, (res) => {
        var body = '';
        res.on('data', (d) => {
        body += d;
        });

        res.on('end', function () {
            callback(body);
        });
    });
    req.end();

    req.on('error', (e) => {
        console.log("Bad URL");
});

An example of the expected return is this.

{"data": {"id": "13217928", "username": "codywalters", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/13129823_1070343653004719_1646319572_a.jpg", "full_name": "Cody Walters", "bio": "Producer/DP in Seattle, Washington", "website": "http://codywaltersvideo.com", "counts": {"media": 233, "follows": 148, "followed_by": 163}}, "meta": {"code": 200}}
how-toapi
10 |5000

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

Nick Gardner avatar image
Nick Gardner answered

You need to structure your callbacks differently for this to work. Since you call req.end() right after your http call, it doesn't know to wait for that request to return before enting it. If you put req.end() in the res.on('end') section things should work.

10 |5000

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.