Sunday, April 20, 2008

Amazon Web Services (AWS)

it's been recommended to me by some friends to start a blog on code snippets since i'm not just into music and literature, but also spend a considerable amount of time on the computer trying to figure out how i can make a script work that i've seen somewhere or whatever the case may be. i guess first i gotta go through a short and sweet amount of history on how i teach myself:

when i started off in 2001 someone showed me how to figure out the source code by clicking view --> view source code on the Netscape 4.7 browser at the time. first i created mostly pages with links of websites i liked and which i'd visit regularly, but which could also be of interested to others on a particular subject. in one such case i created a webpage for a friend of mine and she asked me to insert the right-click JavaScript.

<script language="JavaScript" type="text/javascript">
<!--
var message="You can't have this, but you can print it out or contact us for 
permission to borrow something. Have a great day and thanks for visiting us!";

function click(e) {
if (document.all) {
if (event.button == 2) {
alert(message);
return false;
}
}

if (document.layers) {
if (e.which == 3) {
alert(message);
return false;
}
}
}
if (document.layers) {

document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;
//-->
</script>

that was the code i used in my page; i found that code snippet on the internet; she used a different code at the time and i noticed it wasn't working in Netscape, so i asked "what code are you talking about?" well, and that's how i got started using JavaScript.

in one of my more complicated examples i created a page with 4 framesets, whereby if one moves the cursor over a link to a music album, the album cover changes accordingly in the other frame. that was a nightmare which took me about 8 hours to resolve. here again i searched around on the internet to find a suitable code snippet.

<frameset cols="313,*" border="0" framespacing="0" frameborder="0">
<frameset rows="434,*" border="0" framespacing="0" frameborder="0">
<frame src="AppleBobDylan.html" scrolling="auto" name="Think different.">
<frame src="DylanAlbumImages.html"  scrolling="auto" name="DylanAlbumImages">
</frameset>
<frameset rows="9%,*" border="0" framespacing="0" frameborder="0">
<frame src="DylanAlbumHeader.html" scrolling="auto" name="DylanAlbumHeader">
<frame src="DylanAlbumLinks.html" scrolling="auto" name="DylanAlbumLinks">
</frameset>
</frameset>
<noframes>
<body>
</body>
</noframes>


the code snippet that would have to be used with the link would be:


onmouseover="parent.DylanAlbumImages.document.albumcover.src='CURRENT_COVER.jpg'"
onmouseout="parent.DylanAlbumImages.document.albumcover.src='DEFAULT_IMAGE.jpg'"


CURRENT_COVER is here only sort of a variable for the image related to the current cover. those have been preloaded at the head of the script in the .html file that contains the links.

but what am i writing about? you thought this article would be about Amazon Web Services; well it is, we're slowly getting there.

before i get into that i should mention a few books that may be essential to the cause:


Programming PHP


Web Database Applications with PHP & MySQL


Learning Perl


Programming Perl


and of course my main guide: the AWS Book titled: The Web Developer's Guide To Amazon E-Commerce Service: Developing Web Applications Using Amazon Web Services And PHP

this last book not only helps you to learn php but also apply it already in reallife applications. example scripts can be seen as well as downloaded from www.awsbook.com.

i could go more into details about books, Ajax Hacks, Amazon Hacks (now somewhat outdated due to the termination of Amazon Web Services 3.0) and Google Hacks or any other from the Hacks series.

enough of this! now let me give an example of how i sometimes work. you can find already lots of usable code related to Amazon Web Services on the internet, you don't have to write your own. but you should at least have a fundamental knowledge of how Amazon Web Services works:

Step 1: you formulate your request url
Step 2: you send that request to Amazon's server (using your browser)
Step 3: Amazon returns a document with a XML structure related to your request, if neccessary with an error message which tells you what parameter was wrong.
Step 4: you write some kind of script that can turn the XML document into something more sensible to the visitors of your website.

the start of your url will always look like this:
http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]
http://ecs.amazonaws.co.uk/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]
http://ecs.amazonaws.ca/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]
http://ecs.amazonaws.de/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]
http://ecs.amazonaws.fr/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]
http://ecs.amazonaws.jp/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[YOUR ID]

you obtain the AWSAccessKeyId from Amazon and it's the same for all these locales.

next you need an Operation (no no, don't panik, not at the hospital! you should remember that these terms are case-sensitive!) for instance Operation=ItemSearch. you find those in the documentation from Amazon. i don't want to get into those details too much here.

certain Operations (like ItemSearch) require certain parameters that are a must. in this case for instance a SearchIndex is required. a SearchIndex is something like Books, DVD or VHS. the SearchIndex values vary from country to country (locale to locale); for instance, MusicalInstruments you get only under the US locale whereas Hobbies you will only find under the JP locale (for Japan). apropos Japan: i did not make a mistake with the url above, it is .jp and not .co.jp in this case.

now what are we searching for? one can search for a particular Author under Books, or Artist under Music, Actor or Director among DVD and VHS. the simplest would be the Keywords search (one can also use a BrowseNode, but who knows those offhand?).

we're almost there. we could add a Sort parameter or even which Version of Amazon Web Services we'd prefer to use in our request, but those will be returned as default parameters and we don't have to worry about that for now.

i almost forgot about the ResponseGroup: the information you're about to get depends on the ResponseGroup, Small, Medium or Large are the basic ones.

we got everything? let's give it a try, shall we?

http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=[where's your id?]&Operation=ItemSearch&SearchIndex=Books&Keywords=Bob%20Dylan&ResponseGroup=Large

O.K. that work's after a number of false starts (i hate links that don't work!)

now that we've had the basics i will show an example i found on the internet and changed it to suit my own purposes. nothing spectacular!

i found this code snippet in the Ajax Community:


<?php
class aws {
    function 
aws($aki$asin) {
        
$fs=fopen("http://ecs.amazonaws.de/onca/xml?Service=AWSECommerceService&AWSAccessKeyId="$aki ."&AssociateTag=22&Version=2006-09-11&Operation=ItemLookup&ItemId="$asin ."&ResponseGroup=Medium,Offers","r");                
        
$this->responseXML=simplexml_load_string(fgets($fs));
    }
    
    function 
getValue($pValue) {    
        
$myValue '';
        eval (  
'$myValue = $this->responseXML->'.$pValue.';' );
        if(empty(
$myValue)) $myValue='n.V.' ;                            
        return 
$myValue;
    }
}

$produkt = new aws('AccessKeyId''Produkt ASIN');
$preis =  $produkt->getValue('Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice');
$bild  =  $produkt->getValue('Items->Item->LargeImage->URL');

echo 
'<img src="'.$bild.'" />';
echo 
'Preis: '$preis;
?>


and this is what i made of it:

<?php
class aws {
function 
aws($aki$affid$asin) {
        
$aki '1BZ9VRA5AKNBPYJM6YR2';
        
$affid 'downinthefl04-21';
        
$asin '3100744314';
        
$fs=fopen("http://ecs.amazonaws.de/onca/xml?Service=AWSECommerceService&AWSAccessKeyId="$aki ."&AssociateTag="$affid ."&Version=2006-09-11&Operation=ItemLookup&ItemId="$asin ."&ResponseGroup=Medium,Offers","r");                
        
$this->responseXML=simplexml_load_string(fgets($fs));
    }
    
    function 
getValue($pValue) {    
        
$myValue '';
        eval (  
'$myValue = $this->responseXML->'.$pValue.';' );
        if(empty(
$myValue)) $myValue='n.V.' ;                            
        return 
$myValue;
    }
}

$produkt = new aws('AccessKeyId''AffiliateId''Produkt ASIN');
$preis =  $produkt->getValue('Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice');
$bild  =  $produkt->getValue('Items->Item->LargeImage->URL');
$link  =  $produkt->getValue('Items->Item->DetailPageURL');
$titel =  $produkt->getValue('Items->Item->ItemAttributes->Title');
echo 
'<img src="'.$bild.'" /><br />'."\n";
echo 
'<a href="'.$link.'" target="new">'.$titel.'</a><br />'."\n";
echo 
'<a href="http://ecs.amazonaws.de/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=1BZ9VRA5AKNBPYJM6YR2&AssociateTag=downinthefl04-21&Version=2006-09-11&Operation=ItemLookup&ItemId=3100744314&ResponseGroup=Medium,Offers" target="new">XML Dokument</a><br />'."\n";
echo 
'Preis: 'str_replace('EUR','&#128;',$preis);
?>


i added my affiliate id and i display a link below the large image, as well as a link to the request i made. i always do this as an easy reference in case nothing shows up. the script is written in php5 which you can easily recognize by the use of the simplexml_load_string function.

writing this all up has now taken me a considerable amount of time; so i'm gonna knock off with a last link to the PHP: Documentation where the reader will find the simplexml_load_string as well as the simplexml_load_file functions explained in greater detail together with examples from other users. for some resource links on Amazon Web Services you can also visit my documentary.

Cheers for now!

tom.paine


No comments: