PHP - Call RESTful service

By xngo on September 12, 2019

In this tutorial, I will show you how to use PHP to call a RESTful service. More specifically, we will use cURL to query GitHub's REST API.

For this example, I’m interested in getting all repositories with more than 90k stars and 20k followers. The query that we pass should be ?q=stars:>=90000+followers:>=20000&sort=stars&order=desc.

Here is the complete code in PHP.

<?php
 
$query = '?q=stars:>=90000+followers:>=20000&sort=stars&order=desc';
$url = 'https://api.github.com/search/repositories' . $query;
$user_agent = 'Chrome/76.0.3809.132';   // Github requires a user_agent.
 
$curl = curl_init();
 
curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_USERAGENT => $user_agent,
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache"
        ),
));
 
$response = curl_exec($curl);
$err = curl_error($curl);
 
curl_close($curl);
 
// Print JSON data.
$json_obj = json_decode($response);
print_r($json_obj);
 
?>

Output

stdClass Object
(
    [total_count] => 355
    [incomplete_results] => 
    [items] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 28457823
                    [node_id] => MDEwOlJlcG9zaXRvcnkyODQ1NzgyMw==
                    [name] => freeCodeCamp
                    [full_name] => freeCodeCamp/freeCodeCamp
                    [private] => 
                    [owner] => stdClass Object
                        (
                            [login] => freeCodeCamp
                            [id] => 9892522
                            [node_id] => MDEyOk9yZ2FuaXphdGlvbjk4OTI1MjI=
                            [avatar_url] => https://avatars0.githubusercontent.com/u/9892522?v=4
            ...

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.