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} ’.replace(“{0}”, obj.track_name);
html += ‘<a href=”{0}” target=”_blank”>Preview</a> ’.replace(“{0}”, item.previewUrl);
html += ‘<a href=”{0}” target=”_blank”>Full Song</a> ’.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.
Thank you Rahul. This is exactly what I am looking for. I really appreciate your responsiveness and exceptionally clear explanation.
Kind regards,
Donovan
This is really helpful. If I were to use this form to do an app search I assume I would initially replace & add the relevant parameters. But how would I know what to put as the attributes present in the array objects?
Any help would be much appreciated – thanks.
Thanks for the example.
the limit:20 we can get the first 20 search result. but how we can get the next 20 result?
Thanks.
Great stuff! I used the code in the attachment and there seems to be an extra encodeURI on the term, which ends up replacing %20 with %2520. Just a note to anyone that may have any problems with using spaces in their search query. Thanks again, Tbone
Hi,
Firstly, thank you for the overview, something Apple should really provide themselves on their API pages. It was very helpful 🙂
Note however that the url has changed, it’s now:
http://itunes.apple.com/search?your-params-here
Just in case anyone else runs up against any issues.
Hello – I’m searching and searching the internet for something a little simpler than this. I need to use iTunes Search API (Lookup) to simply return a given app’s icon and current price while automatically including my affiliate link. I need it all to be in code, no search box. Where can I find a script that will do this?
Thank you, Rahul! That’s the direction I needed to know about! I got a freelancer who is working on my script now.
Thank you!
Thanks a lot. I have been stuck in this for a day…
Hi Rahul!
thanks a lot for this.
I’m working with a team on building a music app and we’re using itunes’ API to search the database. We’re also giving the user the choice of picking what kind of genre of music he wants to be displayed. Our problem starts here: the genres that apple describes in http://www.apple.com/itunes/affiliates/resources/documentation/genre-mapping.html
do not match the actual api, is there a way for me to 1)search actual keywords in for the primary genre to see if there are any results (basically search for trip pop and see if there is a genre called that
or 2) get a list of ALL the primary genres on the database?
Thanks!!!
Richard