Samuel Aubin
Samuel Aubin

Reputation: 1923

Use API's URL to receive json

I am accessing the api of world weather online. I have configured the url and it is displayed below-

http://api.worldweatheronline.com/premium/v1/marine.ashx?key=XXXXXXXXXXXXXXXX&q=-34.48,150.92&format=json

Note: my API key is displayed as XXXXXXXXXXXX and this is returning the following:

{
  "data": {
    "request": [],
    "weather": [
    {
      "date": "2016-11-20",
      "astronomy": [],
      "maxtempC": "27",
      "maxtempF": "80",
      "mintempC": "15",
      "mintempF": "58",
      "hourly": [
      {
        "time": "0",
        "tempC": "15",
  ...

I want to GET this json in JS and then log the value of TempC.

How can this be done?

Upvotes: 0

Views: 48

Answers (1)

Julian
Julian

Reputation: 2822

The simplest way would be using request. You can install it with npm install request

const request = require('request')
const apiKey = 'XXXXXXXX'

let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx'
let qs = { 
  q: '-34.48,150.92',
  format: 'json',
  key: apiKey
}
request({ url, qs }, (err, response, body) => {
  if (err)
    return console.error(err)
  if (response.statusCode != 200)
    return console.error('status:', response.statusCode, body)
  body = JSON.parse(body)
  console.log(body.data.weather[0].hourly[0].tempC)
})

Upvotes: 2

Related Questions