Retrieve Spotify Data from the Spotify API (in PHP)

This is for every programming language there is pretty much but I just happen to do it in PHP. I wanted to utilize the Spotify API today for one of my projects so I thought I would write down the code of how to retrieve data from the API since I thought it was just to create an app and then pass the client and secret. Close, but that was not the way to do it.

The Spotify API documentation

Our goal here is to use retrieve data of an artist by using the search for an item method. See link to the Spotify documentation here and the picture above.

See how you can play around with the parameters there and that we send an bearer token. This is something Spotify provide from their website already. But when we use this separatly on our own, we need to get our own bearer tokens.

First thing we need to do is create a app where we get client and secret keys so that we can be allowed go to the API. We can do that at the developer Spotify page here.

When we got an app. We can now go and get bearer tokens that we will use to pass to the search method. In this post here on gist.github.com provided by ahallora we can see an example of how such call is made. Note that each bearer token have a lifetime of 1 hour. So after that you can not make any calls to the Spotify API methods without getting a new one. I will also enable errors here to see if we do anything completely wrong.

error_reporting(E_ALL);
ini_set('display_errors', 1);

$client_id = 'myclientid'; 
$client_secret = 'myclientsecret';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,            'https://accounts.spotify.com/api/token' );
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Authorization: Basic '.base64_encode($client_id.':'.$client_secret))); 
curl_setopt($ch, CURLOPT_POSTFIELDS,     'grant_type=client_credentials' ); 
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:x.x.x) Gecko/20041107 Firefox/x.x");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$json = curl_exec($ch);
$json = json_decode($json);
curl_close($ch);

echo '<pre>'.print_r($json, true).'</pre>';
echo $json->access_token;

In the end we print out the data and the token. See the result above.

Next step is to pass the token along to the https://api.spotify.com/v1/search with parameters. We can see on the Spotify page how the CURL would look like.

curl -X "GET" "https://api.spotify.com/v1/search?q=Tom%20Petty&amp;type=artist" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer BQBBa_kOUM7Tw757w3bxYHE9y40bJ5M6fT4q8ZtplS-_lHxEO5dCzfVPOyMHzPf6XhAWakhn87DhlDO5tudn4eZX1Lu1zeI0KIB99WZbMudNgiXD5UGSPNi3e9IIXwWWoRJws_sg_nTxZ6UdRrgLCh9OMv9kIByZhZ3w2kt9WFBKY5feDqBYSK7J8Oz8vZiLRrD0UTSPKeNtZhlNnb7nWOfn_MKj7BdZgnoQgA"

It would be something like this, and this should be the same as searching on Spotify on (the artist) “Tom Petty” on artists because we will pass the Artist and the Type parameter.

So remember that $json->access_token? We we will use it like this.

$authorization = "Authorization: Bearer " . $json->access_token;

$artist = 'Tom Petty';

$spotifyURL = 'https://api.spotify.com/v1/search?q='.urlencode($artist).'&amp;type=artist';

$ch2 = curl_init();


curl_setopt($ch2, CURLOPT_URL, $spotifyURL);
curl_setopt($ch2,  CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization));
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch2, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:x.x.x) Gecko/20041107 Firefox/x.x");
curl_setopt($ch2, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
$json2 = curl_exec($ch2);
$json2 = json_decode($json2);
curl_close($ch2);

echo '<pre>'.print_r($json2, true).'</pre>';

Result will look like this

stdClass Object
(
    [artists] => stdClass Object
        (
            [href] => https://api.spotify.com/v1/search?query=Tom+Petty&amp;type=artist&amp;offset=0&amp;limit=20
            [items] => Array
                (
                    [0] => stdClass Object
                        (
                            [external_urls] => stdClass Object
                                (
                                    [spotify] => https://open.spotify.com/artist/2UZMlIwnkgAEDBsw1Rejkn
                                )

                            [followers] => stdClass Object
                                (
                                    [href] => 
                                    [total] => 1367609
                                )

                            [genres] => Array
                                (
                                    [0] => album rock
                                    [1] => classic rock
                                    [2] => country rock
                                    [3] => folk rock
                                    [4] => heartland rock
                                    [5] => mellow gold
                                    [6] => pop rock
                                    [7] => rock
                                    [8] => roots rock
                                    [9] => singer-songwriter
                                    [10] => soft rock
                                )

                            [href] => https://api.spotify.com/v1/artists/2UZMlIwnkgAEDBsw1Rejkn
                            [id] => 2UZMlIwnkgAEDBsw1Rejkn
                            [images] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [height] => 1000
                                            [url] => https://i.scdn.co/image/334e67339c294b6e99a35082cc4bee39bfd3db1c
                                            [width] => 1000
                                        )

                                    [1] => stdClass Object
                                        (
                                            [height] => 640
                                            [url] => https://i.scdn.co/image/7b84f8beb988f9364037a2d49220bb8fac329f0a
                                            [width] => 640
                                        )

                                    [2] => stdClass Object
                                        (
                                            [height] => 200
                                            [url] => https://i.scdn.co/image/cecb245e01e18e738b321a31ee3f801e21ff91ce
                                            [width] => 200
                                        )

                                    [3] => stdClass Object
                                        (
                                            [height] => 64
                                            [url] => https://i.scdn.co/image/078ab9acd664d4f467ca8c2d59da6524d66f59bd
                                            [width] => 64
                                        )

                                )

                            [name] => Tom Petty
                            [popularity] => 74
                            [type] => artist
                            [uri] => spotify:artist:2UZMlIwnkgAEDBsw1Rejkn
                        )

                    [1] => stdClass Object
                        (
                            [external_urls] => stdClass Object
                                (
                                    [spotify] => https://open.spotify.com/artist/4tX2TplrkIP4v05BNC903e
                                )

                            [followers] => stdClass Object
                                (
                                    [href] => 
                                    [total] => 1521962
                                )

                            [genres] => Array
                                (
                                    [0] => album rock
                                    [1] => classic rock
                                    [2] => country rock
                                    [3] => folk rock
                                    [4] => hard rock
                                    [5] => heartland rock
                                    [6] => mellow gold
                                    [7] => pop rock
                                    [8] => psychedelic rock
                                    [9] => rock
                                    [10] => roots rock
                                    [11] => soft rock
                                )

                            [href] => https://api.spotify.com/v1/artists/4tX2TplrkIP4v05BNC903e
                            [id] => 4tX2TplrkIP4v05BNC903e
                            [images] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [height] => 562
                                            [url] => https://i.scdn.co/image/b3c930705d502022b13f9c7134db8ae84a8ae71f
                                            [width] => 999
                                        )

                                    [1] => stdClass Object
                                        (
                                            [height] => 360
                                            [url] => https://i.scdn.co/image/92f0e0ba27c2cf2d9942311d657f5ebd4f8b1980
                                            [width] => 640
                                        )

                                    [2] => stdClass Object
                                        (
                                            [height] => 112
                                            [url] => https://i.scdn.co/image/5aefcb44f5ecd17a120c5d1cb0f6e4109d09739d
                                            [width] => 199
                                        )

                                    [3] => stdClass Object
                                        (
                                            [height] => 36
                                            [url] => https://i.scdn.co/image/784a0acc0d04c0481a50381c649613dfd4c10dce
                                            [width] => 64
                                        )

                                )

                            [name] => Tom Petty and the Heartbreakers
                            [popularity] => 73
                            [type] => artist
                            [uri] => spotify:artist:4tX2TplrkIP4v05BNC903e
                        )

                    [2] => stdClass Object
                        (
                            [external_urls] => stdClass Object
                                (
                                    [spotify] => https://open.spotify.com/artist/3wGfX8HmtxkqVHH37PgKug
                                )

                            [followers] => stdClass Object
                                (
                                    [href] => 
                                    [total] => 566
                                )

                            [genres] => Array
                                (
                                )

                            [href] => https://api.spotify.com/v1/artists/3wGfX8HmtxkqVHH37PgKug
                            [id] => 3wGfX8HmtxkqVHH37PgKug
                            [images] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [height] => 640
                                            [url] => https://i.scdn.co/image/ab67616d0000b273f8917dea3f241e4975248320
                                            [width] => 640
                                        )

                                    [1] => stdClass Object
                                        (
                                            [height] => 300
                                            [url] => https://i.scdn.co/image/ab67616d00001e02f8917dea3f241e4975248320
                                            [width] => 300
                                        )

                                    [2] => stdClass Object
                                        (
                                            [height] => 64
                                            [url] => https://i.scdn.co/image/ab67616d00004851f8917dea3f241e4975248320
                                            [width] => 64
                                        )

                                )

                            [name] => The Sounds Of Tom Petty
                            [popularity] => 7
                            [type] => artist
                            [uri] => spotify:artist:3wGfX8HmtxkqVHH37PgKug
                        )

                )

            [limit] => 20
            [next] => 
            [offset] => 0
            [previous] => 
            [total] => 3
        )

)

And there we go! We just made a successful call to the Spotify API to grab some data just like we would do when we search on an artist on Spotify. We actually got 3 results in our array that matches Tom Petty it seems, first one is the Artist himself, next up are Tom Petty and the Heartbreakers and The Sounds Of Tom Petty.

Here is the code all together.

error_reporting(E_ALL);
ini_set('display_errors', 1);

$client_id = 'myclientid'; 
$client_secret = 'myclientsecret';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,            'https://accounts.spotify.com/api/token' );
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Authorization: Basic '.base64_encode($client_id.':'.$client_secret))); 
curl_setopt($ch, CURLOPT_POSTFIELDS,     'grant_type=client_credentials' ); 
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:x.x.x) Gecko/20041107 Firefox/x.x");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$json = curl_exec($ch);
$json = json_decode($json);
curl_close($ch);

echo '<pre>'.print_r($json, true).'</pre>';
echo $json->access_token;

////////////////////////////// SECOND CALL!
$authorization = "Authorization: Bearer " . $json->access_token;

$artist = 'Tom Petty';

$spotifyURL = 'https://api.spotify.com/v1/search?q='.urlencode($artist).'&amp;type=artist';

$ch2 = curl_init();


curl_setopt($ch2, CURLOPT_URL, $spotifyURL);
curl_setopt($ch2,  CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization));
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch2, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:x.x.x) Gecko/20041107 Firefox/x.x");
curl_setopt($ch2, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
$json2 = curl_exec($ch2);
$json2 = json_decode($json2);
curl_close($ch2);

echo '<pre>'.print_r($json2, true).'</pre>';

Leave a comment

Your email address will not be published. Required fields are marked *