Pradyoth Kalavagunta
Pradyoth Kalavagunta

Reputation: 11

Cannot access Zomato APIs JSON object

I am working on a project in Udacity's web development Nanodegree course. I decided to use restaurant information and generated my API key. However, when I use it in an AJAX object to get data, dev tools shows me an 'Invalid API' error. The API, though, is correct. Please help.

Here's my code:

$(document).ready(function(){
$("button").click(function(){
    $.get("https://developers.zomato.com/api/v2.1/restaurant?res_id=MY_RES_ID", { "Accept": "application/json", "user-key": 'MY_API_KEY' }, function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

});

Here is Zomato's documentation:

Curl:

curl -X GET --header "Accept: application/json" --header "user-key: MY_API" "https://developers.zomato.com/api/v2.1/restaurant?res_id=MY_RES_ID"

URL:

https://developers.zomato.com/api/v2.1/restaurant?res_id=MY_RES_ID

Please note that the Restaurant ID and API I used were correct. I don't know much of PHP so I don't know what curl means.

Upvotes: 1

Views: 1171

Answers (1)

Rohit Chandna
Rohit Chandna

Reputation: 251

Please try the below piece of code:

$(document).ready(function(){
  $("button").click(function(){
    $.get("https://developers.zomato.com/api/v2.1/restaurant?res_id=MY_RES_ID&apikey=MY_API_KEY", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
  });
});

However, the above method is discouraged due to security issues. You can access the Zomato API using server to server calls in PHP by writing a handler on your server end which can be called from the button click event as an ajax call. Here is the sample PHP handler:

$curl_channel = curl_init('https://developers.zomato.com/api/v2.1/restaurant?res_id=MY_RES_ID&apikey=MY_API_KEY');
curl_setopt($curl_channel, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl_channel);
curl_close($curl_channel);
//Convert output to object
$curl_output = json_decode($curl_response);

Upvotes: 3

Related Questions