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

Calling the API

The WebClient class in the System.Net namespace provides methods for receiving data from a resource identified by a URI.

The Rest API is stateless, which means you need to identify yourself with each call.

The WebClient instance does not send optional HTTP headers by default. On each call to the API you will need an Application ID, Application Key and Timestamp included in your HTTP request header. To make this easier a function called SetDecibelRequestHeaders(WebClient, AppID, AppKey) is defined in the Util.cs class.

The following code example sets the WebClient request headers.

WebClient client = new WebClient();
client.Headers.Add("DecibelAppID", {Your Application ID});
client.Headers.Add("DecibelAppKey", {Your Application Key});
client.Headers.Add("DecibelTimestamp", DateTime.Now.ToString("yyyyMMdd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture));

By default, the Decibel REST API returns results as JSON. You can ask for XML instead by adding the following header to your request

client.Headers.Add("accept", "application/xml");

The DownloadStringAsync(Uri) method downloads a String from a resource, without blocking the calling thread. This enables the application to continue doing useful work while the method call runs.

The DownloadStringCompleted event is raised each time an asynchronous operation to download a resource as a string completes. The DownloadStringCompletedEventArgs class provides the event handler with event data.

The following code example requests albums by artist name and stores the XML response.

WebClient client = new WebClient();
Util.SetDecibelRequestHeaders(client, "<Your Application ID>", "<Your Application Key>");
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri("http://rest.decibel.net/v2/albums?artistName=fleetwood%20mac"));
 
private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    string result;
    if(e.Error == null)
        result = e.Result;
}

Deserialization

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

To deserialize the Decibel REST API responses you will need to add the Decibel Object Model file to your project. This file contains the class definitions for the different types of objects which can be requested from the API.

  • Right click on the project name in the Solution Explorer
  • Download the DecibelObject.dll class (Right click and select Save link as...)
  • Right click on the references in your project and select Add Reference...
  • Click browse, navigate to the location you saved DecibelObject.dll and select add

XML Deserialization

The XmlSerializer class in the System.Xml.Serialization namespace enables you to deserialize XML documents into objects of a specified type. It should be constructed with the type of the object that will be deserialized. The typeof operator is used to obtain the System.Type object for a type.

The following code example deserializes the XML response from a Albums API call to a AlbumQueryResult object.

private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        AlbumQueryResult queryResult;
        XmlSerializer serializer = new XmlSerializer(typeof(AlbumQueryResult));
        using (TextReader reader = new StringReader(e.Result))
        {
            queryResult = (AlbumQueryResult)(serializer.Deserialize(reader));
        }
    }
}

To make it easier to deserialize the different types of XML response objects a generic function is defined in the Util.cs class included with the sample project.

The following example code deserializes a Albums API call to a AlbumQueryResult object.

AlbumQueryResult queryResult = Util.DeserializeXmlString<AlbumQueryResult>(e.Result);

Albums: Search for albums by title

private void BeginAlbumSearch(string albumTitle, string applicationID, string applicationKey)
{
    // Construct the WebClient and set the request headers
    WebClient client = new WebClient();
    Util.SetDecibelRequestHeaders(client, applicationID, applicationKey);
    client.Headers.Add("accept", "application/xml");
 
    // Set the callback function which is invoked when the download of the resource completes
    client.DownloadStringCompleted += client_AlbumSearchCompleted;
 
    // Issue the request to the Decibel Web Service
    string depth = "Recordings;Identifiers;Works;Participations;Genres;ArtistDetails";
    client.DownloadStringAsync(new Uri("http://rest.decibel.net/v2/Albums?title=" + albumTitle + "&depth=" + depth));         
}
 
private void client_AlbumSearchCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null) 
    {
        // Deserialize the response
        AlbumQueryResult queryResult = Util.DeserializeXmlString<AlbumQueryResult>(e.Result);
 
        // Display the results in a grid
        dtgResults.ItemsSource = queryResult.ResultSet;
    }
    else
    {
        MessageBox.Show("The Decibel Web Service request was not successful due to the following error:" + 
            Environment.NewLine + e.Error.ToString());
    }
}

Albums: Retrieve Albums with Track information

private void BeginAlbumRetrieve(string albumID, string applicationID, string applicationKey)
{
    // Construct the WebClient and set the request headers
    WebClient client = new WebClient();
    Util.SetDecibelRequestHeaders(client, applicationID, applicationKey);
    client.Headers.Add("accept", "application/xml");
 
    // Set the callback function which is invoked when the download of the resource completes
    client.DownloadStringCompleted += client_AlbumRetrieveCompleted;
 
    // Issue the request to the Decibel Web Service
    string depth = "Recordings;Identifiers;Works;Participations;Genres;ArtistDetails";
    client.DownloadStringAsync(new Uri("http://rest.decibel.net/v2/Album?id=" + albumID + "&depth=" + depth));
}
 
private void client_AlbumRetrieveCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        // Deserialize the response
        SingleAlbumQueryResult queryResult = Util.DeserializeXmlString<SingleAlbumQueryResult>(e.Result);
 
        // Display the album information
        var album = queryResult.Result;
        txtName.Text = album.Title.ToString();
        txtArtists.Text = album.ArtistsLiteral;
        txtReleaseDate.Text = album.OriginalReleaseDate;
        // Display the number of recordings on the album
        if (album.Recordings != null)
        {
            txtTrackCount.Text = album.Recordings.Length.ToString();
        }
        // Display a list of all genres that apply to the album
        if ((album.Genres != null) && (album.Genres.Length > 0))
        {
            foreach (Genre genreValue in album.Genres)
            {
                txtGenres.Text += genreValue.Name + ", ";
            }
        }
                
        // Add the tracks to a list
        if ((album.Recordings != null) && (album.Recordings.Length > 0))
        {
            foreach (Recording track in album.Recordings)
            {
                string trackInfo = track.Title;
                if (track.Duration > 0)
                {
                    trackInfo += " (" + Util.FormatTime(Convert.ToInt32(track.Duration)) + ")";
                }
                lstTracks.Items.Add(trackInfo);
            }
        }
 
        // Add the participants to the list
        if ((album.Participations != null) && (album.Participations.Length > 0))
        {
            foreach (Participation participant in album.Participations)
            {
                lstParticipations.Items.Add(participant.ArtistsLiteral + " - " + participant.ActivityLiteral);
            }
        }
    }
    else
    {
        MessageBox.Show("The Decibel Web Service request was not successful due to the following error:" + 
            Environment.NewLine + e.Error.ToString());
    }
}

Albums: Get Album Cover Art

Note: You will first need to obtain the album's ImageUrl or ThumbnailUrl using one of the requests above.

private void BeginAlbumArtRetrieve(string artUrl, string applicationID, string applicationKey)
{
    // Construct the WebClient and set the request headers
    WebClient client = new WebClient();
    Util.SetDecibelRequestHeaders(client, applicationID, applicationKey);
            
    // Set the callback function which is invoked when the download of the resource completes
    client.DownloadDataCompleted += client_AlbumArtRetrieveCompleted;
 
    // Issue the request to the Decibel Web Service
    client.DownloadDataAsync(new Uri(artUrl));
}
 
private void client_AlbumArtRetrieveCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    if (e.Error == null)
    {
        if (e.Result == null)
        {
            MessageBox.Show(string.Format("Covert Art for Album with ID '{0}' could not be found.", e.UserState));
            return;
        }
 
        // Successfully retrieved the album cover art - display it on screen
        imgAlbumArt.Source = Util.GetImageSourceFromByteArray(e.Result);
    }
    else
    {
        MessageBox.Show("The Decibel Web Service request was not successful due to the following error:" + 
            Environment.NewLine + e.Error.ToString());
    }
}

Artists: Search for artists by name

private void BeginArtistSearch(string artistName, string applicationID, string applicationKey)
{
    // Construct the WebClient and set the request headers
    WebClient client = new WebClient();
    Util.SetDecibelRequestHeaders(client, applicationID, applicationKey);
    client.Headers.Add("accept", "application/xml");
 
    // Set the callback function which is invoked when the download of the resource completes
    client.DownloadStringCompleted += client_ArtistSearchCompleted;
 
    // Issue the request to the Decibel Web Service
    string depth = "Identifiers;BiographySnippet;Biography;Members;Dates;Genres;Urls";
    client.DownloadStringAsync(new Uri("http://rest.decibel.net/v2/artists?name=" + artistName + "&depth=" + depth));
}
 
private void client_ArtistSearchCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null) 
    {
        // Store the query result
        ArtistQueryResult queryResult = Util.DeserializeXmlString<ArtistQueryResult>(e.Result);
        // Display the results in a grid
        dtgResults.ItemsSource = queryResult.ResultSet;
    }
    else
    {
        MessageBox.Show("The Decibel Web Service request was not successful due to the following error:" + 
            Environment.NewLine + e.Error.ToString());
    }
}

Artists: Retrieve artist with biography

private void BeginArtistRetrieve(string artistID, string applicationID, string applicationKey)
{
    //Construct the WebClient and set the request headers
    WebClient client = new WebClient();
    Util.SetDecibelRequestHeaders(client, applicationID, applicationKey);
    client.Headers.Add("accept", "application/xml");
 
    //Set the callback function which is invoked when the download of the resource completes
    client.DownloadStringCompleted += client_ArtistRetrieveCompleted;
 
    //Issue the request to the Decibel Web Service
    string depth = "Identifiers;BiographySnippet;Biography;Members;Dates;Genres;Urls";
    client.DownloadStringAsync(new Uri("http://rest.decibel.net/v2/artist?id=" + artistID + "&depth=" + depth));
}
 
private void client_ArtistRetrieveCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        // Deserialize the response
        SingleArtistQueryResult queryResult = Util.DeserializeXmlString<SingleArtistQueryResult>(e.Result);
 
        // Display the artist information
        var artist = queryResult.Result;
        txtName.Text = artist.Name;
        txtDateBorn.Text = artist.BirthDate;
        txtDateDied.Text = artist.DeathDate;
        txtPlaceBorn.Text = artist.BirthPlace;
        txtPlaceDied.Text = artist.DeathPlace;
        if (artist.Gender != null)
        {
            txtGender.Text = artist.Gender.ToString();
        }
        // Check fictional box if artist is fictional
        if (artist.IsFictional)
        {
            chkIsFictional.IsChecked = true;
        }
        else
        {
            chkIsFictional.IsChecked = false;
        }
 
        // Find and display any biography text
        if ((artist.Annotations != null) && (artist.Annotations.Length > 0))
        {
            foreach (Annotation annotation in artist.Annotations)
            {
                txtBio.Text = txtBio.Text + annotation.Text + "\n";
            }
        }
 
        // Add artist's website links to a list
        if ((artist.Urls != null) && (artist.Urls.Length > 0))
        {
            foreach (Url website in artist.Urls)
            {
                txtWebsites.Text = website.Address + "\n";
            }
        }
    }
    else
    {
        MessageBox.Show("The Decibel Web Service request was not successful due to the following error:" + 
            Environment.NewLine + e.Error.ToString());
    }
}

Recordings: Search for recordings by title

private void BeginRecordingSearch(string trackTitle, string applicationID, string applicationKey)
{
    // Construct the WebClient and set the request headers
    WebClient client = new WebClient();
    Util.SetDecibelRequestHeaders(client, applicationID, applicationKey);
    client.Headers.Add("accept", "application/xml");
 
    // Set the callback function which is invoked when the download of the resource completes
    client.DownloadStringCompleted += client_RecordingSearchCompleted;
 
    // Issue the request to the Decibel Web Service
    string depth = "Participations;ArtistDetails;Authors;Genres;Identifiers";
    client.DownloadStringAsync(new Uri("http://rest.decibel.net/v2/Recordings?title=" + trackTitle + "&depth=" + depth));    
}
 
private void client_RecordingSearchCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        // Store the query result
        RecordingQueryResult queryResult = Util.DeserializeXmlString<RecordingQueryResult>(e.Result);
 
        // Display the results in a grid
        dtgResults.ItemsSource = queryResult.ResultSet;
    }
    else
    {
        MessageBox.Show("The Decibel Web Service request was not successful due to the following error:" + 
            Environment.NewLine + e.Error.ToString());
    }
}

Recordings: Retrieve recording with artists and genres

private void BeginRecordingRetrieve(string recordingID, string applicationID, string applicationKey)
{
    // Construct the WebClient and set the request headers
    WebClient client = new WebClient();
    Util.SetDecibelRequestHeaders(client, applicationID, applicationKey);
    client.Headers.Add("accept", "application/xml");
 
    // Set the callback function which is invoked when the download of the resource completes
    client.DownloadStringCompleted += client_RecordingRetrieveCompleted;
 
    // Issue the request to the Decibel Web Service
    string depth = "Participations;ArtistDetails;Works;Genres;Identifiers;SessionInfo";
    client.DownloadStringAsync(new Uri("http://rest.decibel.net/v2/Recording?id=" + recordingID + "&depth=" + depth));
}
 
private void client_RecordingRetrieveCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        // Deserialize the response
        SingleRecordingQueryResult queryResult = Util.DeserializeXmlString<SingleRecordingQueryResult>(e.Result);
 
        // Display the recording information
        var recording = queryResult.Result;
        txtName.Text = recording.Title.ToString();
        txtArtists.Text = recording.MainArtistsLiteral;
        txtTotalSeconds.Text = Util.FormatTime(Convert.ToInt32(recording.Duration));
        if (recording.AlbumSequence != null)
        {
            txtTrackNumber.Text = recording.AlbumSequence.ToString();
        }
        if (recording.MusicalKeys != null)
        {
            txtKey.Text = recording.MusicalKeys.ToString();
        }
        if (recording.BeatsPerMinute != null)
        {
            txtBPM.Text = recording.BeatsPerMinute.ToString();
        }
 
        // Check boxes if recording is live or in concert
        if (recording.IsLive == true)
        {
            chkIsLive.IsChecked = true;
        }
        if (recording.IsConcert == true)
        {
            chkIsConcert.IsChecked = true;
        }
 
        // add the recording's genres to the text box
        if (recording.Genres != null)
        {
            foreach (Genre genreValue in recording.Genres)
            {
                if (genreValue.Name.ToString().Length > 0)
                {
                    txtGenres.Text += genreValue.Name + ", ";
                }
            }
        }
 
        // Add the recording participants to the ListBox
        if (recording.Participations != null && recording.Participations.Length > 0)
        {
            foreach (Participation participation in recording.Participations)
            {
                lstParticipants.Items.Add(participation.ArtistsLiteral + " - " + participation.ActivityLiteral);
            }
        }
 
        // Add the identifiers to the list
        if (recording.Identifiers != null)
        {
            foreach (Identifier identifier in recording.Identifiers)
            {
                lstIdentifiers.Items.Add(identifier.IdentifierType + " - " + identifier.Value);
            }
        }
 
        // Add the production events to the list
        if (recording.ProductionEvents != null && recording.ProductionEvents.Length > 0)
        {
            foreach (ProductionEvent productionEvent in recording.ProductionEvents)
            {
                lstEvents.Items.Add(productionEvent.Date + " - " + productionEvent.Location);
            }
        }
    }
    else
    {
        MessageBox.Show("The Decibel Web Service request was not successful due to the following error:" + 
            Environment.NewLine + e.Error.ToString());
    }
}