You are hereBlogs / rahul's blog / iTunes - Performing iTunes store search in javascript

iTunes - Performing iTunes store search in javascript


rahul's picture

By rahul - Posted on 18 August 2011

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:

 

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);
}

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:

 

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);
}		

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.

 

AttachmentSize
itunes-music-search.htm3.22 KB

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.

rahul's picture

Hi Rory, you can set the media for Search API to software, and further choose entity to be one or more from "software, iPadSoftware, macSoftware" (Please see the API details).

softwareDeveloper is listed as the only valid attribute for software search. You can analyze the results to see what all information is returned.

Also you can generate custom RSS feeds for yourself that you can parse and more detailed documentation is available for Affiliates I believe.

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.

rahul's picture

Hi Jin, iTunes Search API docs does not mention any "start" parameter or something like that. All it mentions is "limit" whose max value is 200. So I guess the best you can do is to fetch 200 records and then implement manualy sorting (in let's say page-size of 20) for them giving you a maximum of 10 pages.

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

rahul's picture

Oops yes, the encodeURIComponent call in line 34 needs to be removed. Thanks for pointing that out 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.

rahul's picture

Thanks Jean for providing the update. The old api url still seems to be functioning as I am able to perform a search using the above sample form.

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?

rahul's picture

Hi Shane, I am running utterly short on time to be able to try writing a script for you. I hope the sample code in this blog post together with Apple Affiliate docs should help you fulfil your needs. Maybe you can try cooking something up and then share it here if it has problems and I can have a look at it to provide my feedback.

Rahul, thanks for your comment. I can understand if you're short on time.

I don't code, so your scripts are totally foreign to me. Can you direct me to someone who can write me a script or tell me where to turn?

Thanks for your time!

rahul's picture

Hi Shane, you can try finding a freelancer on one of the online freelancing sites. There are so many of them (peopleperhour.com, elance.com etc).

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!

rahul's picture

Great, thanks for letting me know!!

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-map...

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

rahul's picture

Hi Richard, I haven't really tried genre mapping for api earlier myself and usually run short on time to be doing now. So, I don't have answer to both of your questions and I advise you try to search or seek help on Apple forums/stack exchange etc.

Post new comment

The content of this field is kept private and will not be shown publicly.
Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.

Recent comments