PHP REST Sample Code

View Demo / Source Code

The following code snippets are taken from the Decibel PHP REST API Demo.

PHP Source Code View Online

The code snippets will guide you through some basic use case scenarios of the Decibel REST API.

Calling the API

REST requests are modelled after the way a web browser sends requests to a web server. So, when we use the PHP programming language for REST requests, our PHP scripts mimic the way a web browser interacts with a web server.

PHP, being an extremely flexible and feature-rich language, provides a number of different mechanisms you can choose from to make your REST requests. The ones we recommend are:

Depending on your web server configuration either one of these functions may be more desirable.

cUrl

The PHP extension cURL is widely used for making Web services requests. It must be loaded in your PHP configuration file, called php.ini. Editing this file normally requires administrative privileges on your server. To see whether cURL is installed and active in your PHP build call the phpinfo function and browse the output.

The following code example taken from util.php makes a request using cURL and stores the response.

// Initialize the cURL session with the request URL
$session = curl_init($url);

// Tell cURL to return the request data
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// Set the HTTP request authentication headers
$headers = array(
    'DecibelAppID: ' . $applicationID,
    'DecibelAppKey: ' . $applicationKey,
    'DecibelTimestamp: ' . date('Ymd H:i:s', time())
);
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);

// Execute cURL on the session handle
$response = curl_exec($session);

// Close the cURL session
curl_close($session);

file_get_contents

PHP's file_get_contents function lets you easily fetch a URL and return the contents as a string. Its main drawback is that your PHP installation must have fopen wrappers enabled in order to access URLs. If fopen wrappers is not enabled, you will not be able to use file_get_contents for Web services requests.

The following code example makes a request using file_get_contents and stores the response.

// Set the HTTP request authentication headers
$headers = array(
    'http' => array(
        'method' => "GET",
        'header' => "DecibelAppID: " . $applicationID . "\r\n" .   
                    "DecibelAppKey: " . $applicationKey . "\r\n" .
                    "DecibelTimestamp: " . date('Ymd H:i:s', time()) . "\r\n"
  )
);

// Creates a stream context
$context = stream_context_create($headers);

// Open the URL with the HTTP headers (fopen wrappers must be enabled)
$response = file_get_contents($url, false, $context);

Interpreting XML

The Decibel REST API returns data in two formats XML and JSON. To make it easier to parse the response the data can be interpreted into manageable objects.

SimpleXML is a PHP extension which provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.The simplexml_load_string function takes a well-formed XML string and returns it as an object.

The following code example requests albums by artist name, interprets the XML response and outputs the search results.

include 'util.php';

// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');

// Set the request URL
$url = 'http://api.decibel.net/v1/Albums/?artist=' . urlencode($artistName) . '&format=xml';

// Issue the request to the Decibel Web Service
$response = request($url, $applicationID, $applicationKey);

// Interpret the XML response
$xml = simplexml_load_string($response);

// Get the collection of albums from the result set
$albums = $xml->ResultSet->Album;

// Output the search results
foreach ($albums as $album) {
    echo $album->Name . ' - ' . $album->Artists . '<br/>';
}

Decoding JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is like XML, but without the markup around the actual payload.

The json_decode function takes a JSON encoded string and converts it into a PHP variable.

The following code example requests albums by artist name, decodes the JSON response and outputs the search results.

include 'util.php';
   
// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');  
   
// Set the request URL
$url = 'http://api.decibel.net/v1/Albums/?artist=' . urlencode($artistName) . '&format=json';

// Issue the request to the Decibel Web Service
$response = request($url, $applicationID, $applicationKey);

// Decode the JSON response
$json = json_decode($response);

// Get the collection of albums from the result set
$albums = $json->ResultSet;

// Output the search results
foreach ($albums as $album) {
    echo $album->Name . ' - ' . $album->Artists . '<br/>';
}

Albums: Search for albums by title

include 'util.php';
   
// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');

function beginAlbumSearch($albumTitle, $applicationID, $applicationKey)
{
    // Set the request URL
    $url = 'http://api.decibel.net/v1/Albums/?albumTitle=' . urlencode($albumTitle) . '&format=xml';

    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Interpret the XML response
    $result = simplexml_load_string($response);

    // Return the collection of album objects
    return $result->ResultSet->Album;
}

// Search for albums by title
$result = beginAlbumSearch($albumTitle, $applicationID, $applicationKey);

// Output the search results
foreach ($result as $album) {
    echo $album->Name . ' - ' . $album->Artists . '<br/>';
}

Albums: Retrieve Albums with Track information

include 'util.php';

// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');
   
function beginAlbumRetrieve($albumID, $applicationID, $applicationKey)
{
    // Set the request URL
    $depth = 'Tracks;ImageThumbnail;Media;Names;Publications;Performances;';
    $url = 'http://api.decibel.net/v1/Albums/?depth=' . $depth . '&id=' . $albumID . '&format=xml';

    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Interpret the XML response
    $result = simplexml_load_string($response);
   
    // Return the album object
    return $result->ResultSet->Album;
}

// Retrieve album with track information
$result = beginAlbumRetrieve($albumID, $applicationID, $applicationKey);

// Output the result
echo 'Name - ' . $result->Name . '<br/>';
echo 'Artists - ' . $result->Artists . '<br/>';
echo 'Disc Count - ' . $result->DiscCount . '<br/>';
echo 'Track Count - ' . $result->TrackCount . '<br/>';
echo 'Duration - ' . formatTime($result->TotalSeconds) . '<br/>';

if(isset($result->Discs[0]->Disc->MusicMedium->Name)) {
    echo 'Format - ' . $result->Discs[0]->Disc->MusicMedium->Name . '<br/>';
}

if(isset($result->ExternalIdentifiers->ExternalIdentifier)) {
    foreach ($result->ExternalIdentifiers->ExternalIdentifier as $externalIdentifier) {
        if($externalIdentifier->ExternalDatabase->Name == 'UPC Barcode')
            echo 'Barcode - ' . $externalIdentifier->Identifier . '<br/>';
    }  
}

if(isset($result->Genres)) {
    $genres = '';
    foreach ($result->Genres->GenreValue as $genreValue) {
        $genres .= $genreValue->Genre->Name . ',';
    }
    echo 'Genres - ' . rtrim($genres, ',') . '<br/>';
}

echo '<br/>Track List:<br/>';
if(isset($result->Tracks)) {
    foreach($result->Tracks->Track as $track) {
        echo $track->SequenceNo . ') ' . $track->Name . ' (' . formatTime($track->TotalSeconds) . ')<br/>';
    }
}

Albums: Get Album Cover Art

include 'util.php';

function beginAlbumArtRetrieve($albumID, $applicationID, $applicationKey)
{
    // Set the request URL
    $url = 'http://api.decibel.net/v1/Albums/' . $albumID . '/Image';

    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Return the base64 encoded image
    return base64_encode($response);
}

$result = beginAlbumArtRetrieve($albumID, $applicationID, $applicationKey);
echo '<img src="data:image/jpeg;base64,' . $result . '"/>';

AutoComplete: Request autocomplete suggestions (jQuery)

autocomplete.php

include 'util.php';

// Retrieve the autocomplete dictionary to search
$dictionary = trim(strip_tags($_GET['dictionary']));

// Retrieve the search term that jQuery autocomplete sends
$term = trim(strip_tags($_GET['term']));
   
// Set the request URL
$url = 'http://api.decibel.net/v1/Autocomplete?text=' . urlencode($term) .
        '&dictionary=' . $dictionary . '&limit=5&format=json';

// Issue the request to the Decibel Web Service
$response = request($url, 'Your Application ID', 'Your Application Key');

// Decode the JSON response
$result = json_decode($response);

// Build an array of suggestions in jQuery Autocomplete format
$suggestions = $result->$dictionary;
foreach ($suggestions as $suggestion) {
    $row['value'] = stripslashes($suggestion->SuggestionValue);
    $row['id'] = (int)$suggestion->ItemID;
    $row_set[] = $row;
}

// Encode the array and output the result
echo json_encode($row_set);

autocomplete.html

<html>
<head>
    <link href="css/redmond/jquery-ui-1.9.2.custom.min.css" rel="stylesheet">
    <script src="js/jquery-1.8.3.min.js"></script>
    <script src="js/jquery-ui-1.9.2.custom.min.js"></script>
    <script>   
    $(function() {
        $("#album-name")
            .autocomplete({
                source: "autocomplete.php?dictionary=Albums",
                delay: 0,
                select: function(event, ui){
                    alert(ui.item.value);
                }      
            });
    });
    </script>
</head>

<body>
    <label for="album-name">Album Name</label>
    <input id="album-name" size="50" />
</body>

</html>

Download required jQuery libraries

Participants: Search for participants by name

include 'util.php';
   
// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');

function beginParticipantSearch($participantName, $applicationID, $applicationKey)
{
    // Set the request URL
    $url = 'http://api.decibel.net/v1/Participants/?name=' . urlencode($participantName) . '&format=xml';

    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);
   
    // Interpret the XML response
    $result = simplexml_load_string($response);

    // Return the collection of participant objects
    return $result->ResultSet->Participant;
}

// Search for participants by name
$result = beginParticipantSearch($participantName, $applicationID, $applicationKey);

// Output the search results
foreach ($result as $participant) {
    echo $participant->Name . '-' . $participant->Gender . '<br/>';
}

Participants: Retrieve participant with associations and track appearances

include 'util.php';

// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');

function beginParticipantRetrieve($participantID, $applicationID, $applicationKey)
{
    // Set the request URL
    $depth = 'Names;GroupMembers;Nationalities;GeographicAreas;Annotations;ChartsAwards;Relationships;';
    $url = 'http://api.decibel.net/v1/Participants/?depth=' . $depth . '&id=' . $participantID . '&format=xml';

    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Interpret the XML response
    $result = simplexml_load_string($response);
   
    // Return the album object
    return $result->ResultSet->Participant;
}

function beginParticipantAssociates($participantID, $applicationID, $applicationKey)
{
    // Set the request URL
    $depth = 'Names;GroupMembers;Nationalities;GeographicAreas;Annotations;ChartsAwards;Relationships;';
    $url = 'http://api.decibel.net/v1/Participants/' . $participantID . '/Associates?depth=' . $depth . '&format=xml';
   
    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Interpret the XML response
    $result = simplexml_load_string($response);

    // Return the collection of participant associate objects
    return $result->ResultSet->ParticipantAssociate;
}

function beginParticipantTrackAppearances($participantID, $applicationID, $applicationKey)
{
    // Set the request URL
    $depth = 'Names;GroupMembers;Nationalities;GeographicAreas;Annotations;ChartsAwards;Relationships;';
    $url = 'http://api.decibel.net/v1/Participants/' . $participantID . '/Tracks?depth=' . $depth . '&format=xml';
   
    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Interpret the XML response
    $result = simplexml_load_string($response);
   
    // Return the collection of track appearance objects
    return $result->ResultSet->TrackAppearance;
}

// Retreive participant with associations and track appearances
$result = beginParticipantRetrieve($participantID, $applicationID, $applicationKey);
echo 'Participant Name - ' . $result->Name . '<br/>';

$result = beginParticipantAssociates($participantID, $applicationID, $applicationKey);
echo '<br/>Associates:<br/>';
foreach ($result as $associate) {
    echo $associate->Participant->Name . '<br/>';
}

$result = beginParticipantTrackAppearances($participantID, $applicationID, $applicationKey);
echo '<br/>Track appearances:<br/>';
foreach ($result as $trackAppearance) {
    echo $trackAppearance->TrackName . ' - ' . $trackAppearance->AlbumName . '<br/>';
}

Tracks: Search for tracks by title

include 'util.php';
   
// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');

function beginTrackSearch($trackTitle, $applicationID, $applicationKey)
{
    // Set the request URL
    $url = 'http://api.decibel.net/v1/Tracks/?trackTitle=' . urlencode($trackTitle) . '&format=xml';

    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Interpret the XML response
    $result = simplexml_load_string($response);

    // Return the collection of track objects
    return $result->ResultSet->Track;
}

// Search for tracks by title
$result = beginTrackSearch($trackTitle, $applicationID, $applicationKey);

// Output the search results
foreach ($result as $track) {
    echo $track->Name . ' - ' . $track->Artists . '<br/>';
}

Tracks: Retrieve track with participations

include 'util.php';

// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');
   
function beginTrackRetrieve($trackID, $applicationID, $applicationKey)
{
    // Set the request URL
    $depth = 'Names;Participations;ExternalIdentifiers;Genres;Performances;';
    $url = 'http://api.decibel.net/v1/Tracks/?depth=' . $depth . '&id=' . $trackID . '&format=xml';
   
    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Interpret the XML response
    $result = simplexml_load_string($response);
   
    // Return the track object
    return $result->ResultSet->Track;
}

// Retrieve track with participations
$result = beginTrackRetrieve($trackID, $applicationID, $applicationKey);

// Output the result
echo 'Name - ' . $result->Name . '<br/>';
echo 'Artists - ' . $result->Artists . '<br/>';
echo 'Track Number - ' . $result->TrackNumber . '<br/>';
echo 'Disc Number - ' . $result->DiscNumber . '<br/>';
echo 'Total Seconds - ' . formatTime($result->TotalSeconds) . '<br/>';

echo '<br/>Participations:<br/>';
if(isset($result->Participations)) {
    foreach ($result->Participations->Participation as $participation) {
        echo $participation->Participant->Name . ' - ' . $participation->Name . '<br/>';
    }  
}

Works: Search for works by name

include 'util.php';
   
// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');

function beginWorkSearch($workName, $applicationID, $applicationKey)
{
    // Set the request URL
    $url = 'http://api.decibel.net/v1/Works/?name=' . urlencode($workName) . '&format=xml';
   
    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Interpret the XML response
    $result = simplexml_load_string($response);

    // Return the collection of work objects
    return $result->ResultSet->Work;
}

$result = beginWorkSearch($workName, $applicationID, $applicationKey);

// Output the search results
foreach ($result as $work) {
    echo $work->Name . ' - ' . $work->Composers . '<br/>';
}

Works: Retrieve work with track appearances

include 'util.php';

// Set the character encoding to UTF-8
header('Content-Type: text/html; charset=utf-8');
   
function beginWorkRetrieve($workID, $applicationID, $applicationKey)
{
    // Set the request URL
    $depth = 'Annotations;ChartsAwards;Genres;Movements;Names;Nationalities;Publications;Publishers;';
    $url = 'http://api.decibel.net/v1/Works/?depth=' . $depth . '&id=' . $workID . '&format=xml';
   
    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Interpret the XML response
    $result = simplexml_load_string($response);
   
    // Return the track object
    return $result->ResultSet->Work;
}

function beginWorkTrackAppearances($workID, $applicationID, $applicationKey)
{
    // Set the request URL
    $depth = 'Annotations;ChartsAwards;Genres;Movements;Names;Nationalities;Publications;Publishers;';
    $url = 'http://api.decibel.net/v1/Works/' . $workID . '/Tracks' . '?depth=' . $depth . '&format=xml';

    // Issue the request to the Decibel Web Service
    $response = request($url, $applicationID, $applicationKey);

    // Interpret the XML response
    $result = simplexml_load_string($response);
   
    // Return the track object
    return $result->ResultSet->TrackAppearance;
}

// Retrieve work with track appearances
$result = beginWorkRetrieve($workID, $applicationID, $applicationKey);

echo 'Name - ' . $result->Name . '<br/>';
echo 'Composers - ' . $result->Composers . '<br/>';
echo 'Catalogue - ' . $result->Catalogue . '<br/>';

$result = beginWorkTrackAppearances($workID, $applicationID, $applicationKey);
foreach ($result as $trackAppearance) {
    echo $trackAppearance->TrackName . ' - ' . $trackAppearance->TrackArtistName . '<br/>';
}

Flexigrid: Display search results in a data grid with paging (jQuery)

flexigrid.php

include 'util.php';
   
// Set the content type to JSON
header("Content-type: application/json");

// Get the results per page
$rp = trim($_GET['rp']);

// Get the current page
$page = trim($_GET['page']);

// Get the url
$url = ltrim(http_build_query($_GET), 'url=');
$url = urldecode($url);
$url = str_replace(' ', '%20', $url);

// Set the page size parameter
$url .= '&pageSize=' . $rp;

// Start a session
session_start();

// Construct the search URL with page number
if($page != 1) {
    $url = 'http://decibel-rest-jazz.cloudapp.net/v1/Albums/Pages/' .
            $_SESSION['queryResultID'] . '?pageNumber=' . ($page-1);
}

// Issue the request to the Decibel Web Service
$response = request($url, 'Your Application ID', 'Your Application Key');

// Interpret the XML response
$xml = simplexml_load_string($response);

// Set the result count
$resultCount = $xml->ResultCount;  

// If this is the first page of results store the QueryResultID
if($page == 1) {
    $_SESSION['queryResultID'] = stripslashes($xml->QueryResultID);
}
   
// Close and write session
session_write_close();

// Store the collection of album objects
$albums = $xml->ResultSet->Album;

// Construct the Flexigrid JSON data array
$jsonData = array('page'=>$page, 'total'=>stripslashes($resultCount), 'rows'=>array());

// Construct the data rows
$count = 1;
foreach ($albums as $album) {
    $entry = array('id'=>(int)$count,
        'cell'=>array(
                'id'=>stripslashes($album->ID),
                'index'=>(int)$count,
                'name'=>stripslashes($album->Name),
                'artists'=>stripslashes($album->Artists),
                'length'=>stripslashes(formatTime($album->TotalSeconds)),
                'trackCount'=>stripslashes($album->TrackCount)
        ),
    );
    $jsonData['rows'][] = $entry;
    $count++;
}

// Encode the array
echo json_encode($jsonData);

flexigrid.html

<html>
<head>
    <link rel="stylesheet" type="text/css" href="css/flexigrid.css"/>
    <script src="js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="js/flexigrid.js"></script>
    <script>   
    $(function() {
        $(".album-results").flexigrid({
            url : 'flexigrid.php?url=http://decibel-rest-jazz.cloudapp.net/v1/Albums/?genre=jazz&depth=Publications',
            dataType : 'json',
            colModel : [ {
                display : 'ID',
                name : 'id',
                width : 50,
                hide: true
            }, {
                display : 'Index',
                name : 'index',
                width : 50,
            }, {
                display : 'Name',
                name : 'name',
                width : 300,
            }, {
                display : 'Artists',
                name : 'artists',
                width : 300,
            }, {
                display : 'Length',
                name : 'length',
                width : 140,
            }, {               
                display : 'Track Count',
                name : 'trackCount',
                width : 140,
            } ],
            sortname : "iso",
            sortorder : "asc",
            showToggleBtn : false,
            usepager : true,
            useRp : true,
            nohresize : true,
            resizable: false,
            onDragCol: false,
            rp : 15,
            method : "GET",
            width : 1024,
            height : 300,
            singleSelect: true,
        })
       
        $(".album-results").click(function(){
            $('.trSelected', this).each( function(){
                console.log(
                        '  id: ' + $('td[abbr="id"] >div', this).html() +
                        '  index: ' + $('td[abbr="index"] >div', this).html() +
                        '  name: ' + $('td[abbr="name"] >div', this).html() +
                        '  artists: ' + $('td[abbr="artists"] >div', this).html() +
                        '  length: ' + $('td[abbr="length"] >div', this).html() +
                        '  trackCount: ' + $('td[abbr="trackCount"] >div', this).html()
                    );
            });
        });            
    });
    </script>
</head>

<body>
    <table class="album-results" style="display: none"></table>
</body>

</html>

Download required jQuery / Flexigrid libraries