X

Working with APIs in PHP

Let us say that we want to use the OpenWeatherMap API to display the weather in an arbitrary city. We could achieve this in the following way:

$data = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=" . urlencode($city) . "&APPID=YOURAPPID&units=metric");



$data = json_decode($data);



$out = $city . ":\nWeather Condition:  *" . $data->weather[0]->main . "*\nCurrent Temperature: *" . $data->main->temp . "* degrees\n";

If we want to get the latest photos for a certain user in Instagram, choose a random one, and print the URL to it we could again do the following:

 $media = @file_get_contents("https://www.instagram.com/" . trim($theUser) . "/media/");



 $media = json_decode($media);



 $randomImage = $media->items[mt_rand(0, count($media->items) - 1)]->images->standard_resolution->url;



 echo $randomImage;

Those APIs are simple enough in that it lets us make a simple GET request, passing some parameters, JSON decode their output and display or process the data in any way we want and file_get_contents is enough to achieve the desired communication.

Something more complicated would be to make a GET request to an API that actually returns a redirect to an image (with cat gifs) when we actually want to get is the redirection URL. Instead of file_get_contents, we can use curl in the following way for that purpose:

function kittens() {



    $ch = curl_init();



    curl_setopt($ch, CURLOPT_URL, "http://thecatapi.com/api/images/get?format=src&type=gif");



    curl_setopt($ch, CURLOPT_HEADER, true);



    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);



    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);



    curl_exec($ch);



    $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);



    echo json_encode(array("text" => $url));



}

Many APIs implement OAuth authorization to work with them, such as Facebook. Therefore, they have made their own pieces of libraries that facilitate interaction with them. Here is how to use the Facebook PHP SDK to post to a page:

First, we get an access token that we use to identify ourselves to Facebook and perform actions on behalf of a certain entity.

$app_secret = FB_APP_SECRET;



                        FacebookSession::setDefaultApplication(FB_APP_ID, $app_secret);



                        $access_token = FB_ACCESS_TOKEN;



                        $session = new FacebookSession($access_token);



                        FacebookSession::enableAppSecretProof(false);



                        $page_id = FB_PAGE_ID;



                        $access_token = (new FacebookRequest($session, 'GET', '/' . $page_id, array('fields' => 'access_token')))



                                        ->execute()->getGraphObject()->asArray();

Thereafter, we use the SDK to make a POST request, sending the $message variable as a status in the Facebook page, corresponding to the $page_id in the URL of the endpoint.

 $access_token = $access_token['access_token'];



                        $request = (new FacebookRequest(



                                $session, 'POST', '/' . $page_id . '/feed', array(



                            'access_token' => $access_token,



                            'message' => $message



                        )));



                        $response = $request->execute();



                        $graphObject = $response->getGraphObject();

Many APIs rely on Oauth besides Facebook, and the communication resembles the following pattern.

APIs have great value as they can help programmers save time by not starting everything from scratch and by outsourcing certain side-needs of their applications. There are numerous websites that list available APIs with which you can do cool things, one which I like to browse is: https://market.mashape.com/explore

Ivan Dimov: Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter