63

I'm trying to make a server-side API call using a RESTful protocol with a JSON response. I've read up on both the API documentation and this SO post.

The API that I'm trying to pull from tracks busses and returns data in a JSON output. I'm confused on how to make a HTTP GET request with all parameters and options in the actual URL. The API and it's response can even be accessed through a browser or using the 'curl' command. http://developer.cumtd.com/api/v2.2/json/GetStop?key=d99803c970a04223998cabd90a741633&stop_id=it

How do I write Node server-side code to make GET requests to a resource with options in the URL and interpret the JSON response?

starball
  • 20,030
  • 7
  • 43
  • 238
CaliCoder
  • 663
  • 2
  • 6
  • 6

1 Answers1

134

request is now deprecated. It is recommended you use an alternative:

Stats comparision Some code examples

Original answer:

The request module makes this really easy. Install request into your package from npm, and then you can make a get request.

var request = require("request")

var url = "http://developer.cumtd.com/api/v2.2/json/GetStop?" +
    "key=d99803c970a04223998cabd90a741633" +
    "&stop_id=it"

request({
    url: url,
    json: true
}, function (error, response, body) {

    if (!error && response.statusCode === 200) {
        console.log(body) // Print the json response
    }
})

You can find documentation for request on npm: https://npmjs.org/package/request

Rodrigo Graça
  • 1,985
  • 3
  • 17
  • 24
Matt Esch
  • 22,661
  • 8
  • 53
  • 51
  • 1
    Thanks for the quick reply @matt-esch! I read up on the examples on the 'request' npm page and they mention that the response stored by a way similar to "var resp = request(...)" but when I try to parse the result using "var parsed = JSON.parse(resp)" I get an error "SyntaxError: Unexpected token o". I've tried searching for an answer but nothing really seems to work. Thanks! – CaliCoder Dec 02 '13 at 05:19
  • 2
    In my example, setting `json` to `true` returns the parsed JSON as the body. The examples show that the return value of resp is a stream, not a value you can parse. The result is returned asynchronously either way. – Matt Esch Dec 02 '13 at 11:14
  • Just wondering, for the code you provided, how do i know what request is it? i.e. post, get, delete or put? I don't see the code specify it... Thanks – munmunbb Mar 14 '17 at 19:40