How to interface with web XML/JSON APIs?
I'm learning php/xml/json and everything else on my own and I was going through API's for certain things. They have documentations but I still don't get how API's work. They give you a GET link and API key, I know that you're supposed to put the API key inside the request link
How do I call this link开发者_如何学Python? And what does it mean when it gives you a sample response?
Is the response supposed to come out if you got the request correct?
I'm a bit clueluess?
Thank you
In PHP you might have something like this:
// EDIT: only need to use urlencode() on user supplied variables
//$url = urlencode("http://xyz.com/api?apikey=foo&v1=bar&v2=baz");
$url = "http://xyz.com/api?apikey=foo&v1=bar&v2=baz";
$response = file_get_contents($url);
The $response
will contain a string of whatever xyz.com
outputted when you accessed $url
(it's what you would see if you visited $url
directly).
Your next job would be to parse $response
based on its data structure (e.g XML, JSON, etc) so that it's usable by the rest of your code.
There are several PHP libraries for parsing XML or JSON. Personally, I prefer to use SimpleXMLElement
and json_decode()
which is included with PHP 5 >= 5.2.0.
Depending on the API, it will probably send you some sort of error code/response structure if it doesn't understand the request $url
which you could check for after you parse the response.
If $response
returns false, then typically there was some error communicating with the $url
.
I found that an intuitive way to think about these XHR
requests is that you're passing arguments (GET
parameters) to a function (API URL). And the response from the API URL is like the return statement from a function.
UPDATE:
API example for Groupon as suggested by OP in comments:
$apikey = "client_id=abcd1234567890";
$division = "division_id=chicago";
$url = "http://api.groupon.com/v2/deals?" . implode("&", array($apikey, $division));
$response = file_get_contents($url);
$deals = json_decode($response, true);
foreach($deals['deals'] as $deal){
$format = 'Deal: <a href="%s">%s</a><br/>';
echo sprintf( $format, $deal['dealURL'], $deal['announcementTitle']);
}
The above code would print out a listing of all deal titles and urls for the Chicago area. If you look at the Sample JSON Response
sections on the Groupon API page, it will give you the entire data structure that would be mapped to the associative array $deals
.
If any of the GET
parameters to the API are provided by the user (e.g. from a web form), you will want to do something like $division = "division_id=" . urlencode($user_input);
.
精彩评论