Weather API with curl?

I was working on weather app and found the mashape api for weather data. However, it provides the endpoint as a URL (ok, I understand that), but the sample it provides is in curl (see below). I’m stuck trying to figure out how to convert this into something like the examples we saw here in FCC using $.getJSON like first section below. However, it gets an error that application key is missing. Any suggestions on my potentially obvious noobiness issue?

=====MY JSON JavaScript attempt==========
function getWeather() {
$("#weatherContent").html(’’);
$.getJSON(“https://simple-weather.p.mashape.com/weatherdata?lat=1.0&lng=1.0&X-Mashape-Key=9OeNI1Ztu3mshtAHIYTSI6Q6CYbMp1ZkQ4QjsnMozBMMkKgGJX”, function(weatherResponse) {
})
}

======The CURL example provided=======================
curl --get --include ‘https://simple-weather.p.mashape.com/weatherdata?lat=1.0&lng=1.0
-H ‘X-Mashape-Key: 9OeNI1Ztu3mshtAHIYTSI6Q6CYbMp1ZkQ4QjsnMozBMMkKgGJX’
-H ‘Accept: application/json’

Thanks in advance.

Tom

According to the documentation:

$.ajax({
    url: 'https://simple-weather.p.mashape.com/weatherdata', // The URL to the API. You can get this in the API page of the API you intend to consume
    type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
    data: {
      "lat": "51.87",
      "lng": "4.6"
    }, // Additional parameters here
    dataType: 'json',
    success: function(data) { console.log(data) },
    error: function(err) { console.log(err); },
    beforeSend: function(xhr) {
      xhr.setRequestHeader("X-Mashape-Authorization", "9OeNI1Ztu3mshtAHIYTSI6Q6CYbMp1ZkQ4QjsnMozBMMkKgGJX"); // Enter here your Mashape key
    }
});
2 Likes

edit: Didn’t see BenGitter’s response, which is also good.

I think the only way to do this with the jQuery helpers is to use jQuery.ajax. cURL’s -H option is specifying a header value, so if your API requires the key to be sent in the header, it won’t know that you’ve sent it in the URL. $.ajax takes a configuration object that allows you to specify headers.

var config = {
    headers: {
        'Accept': 'application/json',
        'X-Mashape-Key': <your key>
};
$.ajax(url, config)
    .then(function(data) {
        // do stuff with data
    })
    .catch(function(error) {
        // handle error
    })

I haven’t tested this code or anything, but I’m at least partially certain that it will work.

2 Likes

Thank, Ben. I missed that page somehow. It was very helpful and now have it working.