0

I have a URL of an API call that returns a JSON object. How do I create a JavaScript function that calls this API, then grabs the JSON response and then lets me retrieve key values?

For example: The API returns a parameter called "Title" and the Value is "Coding 101" - how do I get this "Coding 101"?

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47

2 Answers2

0

If your API is being called through a GET action, then you can make a jquery ajax call to that API endpoint and retrieve the resulting JSON. You can then parse this result using JSON.parse. So you could do something like this :

$.get("APIurl",function(result){
  var resultObject = JSON.parse(result);
  console.log(resultObject.Title); //Writes Coding 101 on console.
});
thispatchofsky
  • 854
  • 6
  • 15
0

You could read this documentation: jQuery.getJSON()

As examples You can use (from this documentation):

$.getJSON( "ajax/test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val + "</li>" );
  });

  $( "<ul/>", {
    "class": "my-new-list",
    html: items.join( "" )
  }).appendTo( "body" );
});

With this You could replace "ajax/test.json" to "ajax/getapi.php?method='method_wich_you_need'" and make ajax/getapi.php like this:

<?php
// curl session initialization
$ch = curl_init();
$method = $_GET['method'];

// set curl options
curl_setopt($ch, CURLOPT_URL, "http://api.com/method/".method."&json");
curl_setopt($ch, CURLOPT_HEADER, 0);

// load page from API
if($result = curl_exec($ch) === false)
{
    echo 'Error: ' . curl_error($ch);
}
else
{
    echo $result;
}

curl_close($ch);
?>