Okay this is a blog post on specific request. My earlier post on Generating Signed Urls for Amazon’s Product Advertising in PHP got a comment today requesting help in regards to executing an iTunes Store search via iTunes API. Now I really wonder whether the user landed on that post in context of Amazon’s API and saw the (very) brief mention for iTunes search integration, or did he stumble upon that page looking for iTunes search help only. But so much for the introduction, let’s jump into the actual blog content and a quick example.

For the beginners, here’s the official Apple page detailing all the request options and response format for the iTunes Search API. Next here’s an example demostrating searching iTunes store completely in javascript:

 

 

Please try entering a search term above and then click the Search button. It can take a second or two for the results to arrive. You might want to show a user some wait notification during the search. For the purpose of this blog post, I assembled the example very quickly and left out all unnecessary tweaks.

Now let’s come over to the code. Here’s the method that is called when you click the Search button:

 

{syntaxhighlighter brush: jscript;fontsize: 100; first-line: 1; }function performSearch() {
var params = {
term: jQuery(‘#search-keyword’).val(),
country: ‘US’,
media: ‘music’,
entity: ‘musicTrack’,
//attribute: ‘artistTerm,albumTerm,songTerm,musicTrackTerm’,
limit: 20,
callback: ‘handleTunesSearchResults’
};
var params = urlEncode(params);

var url = ‘http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch?’ + params;
var html = ‘<script src=”‘ + url + ‘”><\/script>’;
jQuery(‘head’).append(html);
}{/syntaxhighlighter}

You would see it’s pretty simple code. We first prepare the parameters for the search, where term and country are the required parameters. Because you would be executing a cross-site search, callback also becomes mandatory (for the record, iTunes API uses JSONP for delivering data back to your code). Please note that callback should be a javascript method name accessible from the global window context (and not a function reference or a locally defined function).

There are specific valid combinations of media, entity and attributes parameters that are allowed and you can see the details on the above referenced Apple page.

The result is a JSON object or a JSON array depending upon your search parameters. If you search by an id which is expected to return only a single result, then its a json object, else an array.

In our case, because we are searching on a keyword, the result would be an array (the attributes present in the array objects would depend upon your search media, entity and attribute parameters). For the above example, here’s the method that parses the search result and produces displayable html from it:

 

{syntaxhighlighter brush: jscript;fontsize: 100; first-line: 1; }function handleTunesSearchResults(arg) {
var results = arg.results;
var html = ”;
for (var i = 0; i < results.length; i++) {
var item = results[i];
var obj = {
source: 0,
track_id: item.trackId,
track_name: item.trackCensoredName,
track_url: item.trackViewUrl,
artist_name: item.artistName,
artist_url: item.artistViewUrl,
collection_name: item.collectionCensoredName,
collection_url: item.collectionViewUrl,
genre: item.primaryGenreName
};
results[i] = obj;

html += ‘<div class=”songs-search-result”>’;

html += ‘<span class=”label”>Track:</span>{0}&nbsp;&nbsp;’.replace(“{0}”, obj.track_name);
html += ‘<a href=”{0}” target=”_blank”>Preview</a>&nbsp;&nbsp;’.replace(“{0}”, item.previewUrl);
html += ‘<a href=”{0}” target=”_blank”>Full Song</a>&nbsp;&nbsp;’.replace(“{0}”, obj.track_url);
html += ‘<span class=”label”>Track Price:</span>{0} {1}<br />’.replace(“{0}”, item.trackPrice).replace(“{1}”, item.currency);
html += ‘<span class=”label”>Artist:</span><a href=”{0}” target=”_blank”>{1}</a><br />’.replace(“{0}”, obj.artist_url).replace(“{1}”, obj.artist_name);
html += ‘<span class=”label”>Collection:</span><a href=”{0}” target=”_blank”>{1}</a><br />’.replace(“{0}”, obj.collection_url).replace(“{1}”, obj.collection_name);
html += ‘<span class=”label”>Collection Price:</span>{0} {1}<br />’.replace(“{0}”, item.collectionPrice).replace(“{1}”, item.currency);
html += ‘<span class=”label”>Primary Genre:</span>{0}<br />’.replace(“{0}”, obj.genre);

html += ‘</div>’;
}
jQuery(‘#itunes-results’).html(html);
} {/syntaxhighlighter}

Simple isn’t it. I am sure once you get the hang of things, you would find it very easy to create elaborate iTunes API based custom front-ends for your site.

One last thing, more often than not, if you are using iTunes Search API on your website, then you would want to sign-up for Apple’s Affiliate Program and pass your Affiliate ID in the search parameters, as each sale via such a search fetches you commissions. I have not put in an Affilifate ID in the above example, but if I had, then when you search and clicked on a link to buy a song, I would have received a commission from Apple.

You can find the code for the above example attached below with the blog post. In case of any questions, please feel free to use the comment form.