Using the Metro API – a guide for newbies

I’m going to show you how to use the Metro API.

This post is aimed at javascript beginners but i recommend you try out this fun interactive introduction first – http://www.codecademy.com/

Step One. Create a  file on your computer. Call it something like “metro.html”.

Step Two. Copy the HTML below into it. Open the file in a browser and it should say “My metro articles”. (Not very exciting yet, i know).

<html>
<body>
<div id="myElement">My metro articles</div>
</body>
</html>

Step Three. Use the Metro API. You can see what the API looks like here.

Copy the following code before the </body> tag…

<script>
// This function will process the data
function init(apiData) {
  // Init variables
  var myHtml = '';
  var article;

  // Loop through each article in the feed, generating html as we go
  for (var i = 0; i < apiData.entries.length; i++) {
    article = apiData.entries[i]; // Get the relevant article
    myHtml  = myHtml  + "<a href=" + article.alternateLink + ">" + article.title + "</a></br>";
  }

  // Insert our html into the page
  document.getElementById('myElement').innerHTML = myHtml;
}
</script>

<script type="text/javascript" src="http://www.metro.co.uk/api/articles/?page=news&callback=init"></script>

That’s it!

Refresh your browser and you should see a list of metro links. If you have any problems (and there usually are)…  just shout. To experiment more try our API Explorer (beta).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s