Using the Flickr API on your WebMatrix website

Flickr is a free, popular online photo sharing and photo management website. Flickr offers a large development community with user created API Applications. Any person with a Flickr account can use Flickr's rich API to add content to their website, blog, or social media sites as well as create their own Flickr Application. This article will show how easy it is to get starting using Flickr's RESTful API.

Create a website with WebMatrix

In this article, we will be using WebMatrix. WebMatrix is a free tool that allows you to create, customize, and publish webpages. It gives a number of different ways that you can create websites. One of the features is providing existing open sources applications such as WordPress, Joomla, DotNetNuke or Umbraco. WebMatrix can be downloaded for free at microsoft.com/Web/WebMatrix .

If you need help downloading and installing WebMatrix, it may be a good idea to read Getting Started with WebMatrix. The article provides step by step instructions on installing WebMatrix

Let's get started creating a new webpage with WebMatrix.

After WebMatrix is finished installing, open it. Click "Site from Template" on the WebMatrix welcome screen.

For this example we will use is an Empty Site template. This template is a full-featured HTML5 site. Click Empty site and hit ok.

Clicking ok will take you to your WebMatrix workspace. This contains information about your local host as well a provides resources on developing your site.

You’ll notice that WebMatrix allows you to move between different workspaces by selecting the buttons on the left hand side. At present the Site button is selected which gives you details on your web site, such as the URL of the site, and other tools that you can use such as monitoring your site requests. You can look into this workspaces as you work but for this article, we will be working with our Files workspace. To get to your Files workspace, click the "Files" tab on the lower left hand of WebMatrix.

Once in your Files workspace you can see all your files. Since we chose the Empty Site template, we do not have any files. Let's create a new file for our website. Click the new button on the menu ribbon.

Here you can see all the different types of files you can make. Choose the .cshtml file, give it a name and hit ok.

We now have an empty, HTML5 valid website waiting for us to add code. You may be wondering why we created a .cshtml file instead of a traditional .html file. A .cshtml file is a new, special file type for WebMatrix. This type of file can contain the usual contents of a webpage including HTML and JavaScript code but, what sets it apart from a regular .html file is that it can also contain code for programming webpages. .cshtml files let you embed ASP.NET code into your HTML page using the new Razor syntax (which is most commonly denoted using @ - similar to PHP's $).

Razor code can go anywhere on your webpage. Blocks of code (written between @{ }), single line statements, and even single variables can be put anywhere, just make sure you have the correct syntax! If you want a more in-depth introduction to WebMatrix, you can find numerous resources on the subject including the asp.net website.

We'll look at how to add a Flickr RESTful request to our webpage but first, we must create a Flickr account. If you already have a Flickr account, you can skip the next section.

Create a Flickr account

If you're not familiar with Flickr, you can actually link one of several accounts to create a Flickr account. Flickr allows users to link their Yahoo, Facebook, or Google accounts. Chances are, you probably already have one of these accounts.

Choose which account you want to link to your Flickr account and log in using that username and password. If you're already logged into one of these account, all you'll have to do is re-enter your password.

To finish linking your account to Flickr, all you must do is choose a Flickr screen name.

Once you're done, you will be logged in and taken to your Flickr homepage.

Now we can begin adding our Flickr API.

Adding the Flickr API

head to the Flickr API website now. To get starting using the Flickr API, Flickr has laid out some simple steps to getting started.

First thing we need to do is request an API key. You will be unable to make API calls without a API key. You can request an API key through your Flickr homepage or through the developer page. You can also begin creating your API key here.

Once you get started you will be asked if your Flickr application will be used to commercial or non-commercial use. Choose whichever option applies to you and click the "apply" button.

You will be asked to provide an application name and description. You will also have to agree to their terms.

After you've submitted your information, you will be directed to a page where your API key and secret will be visible. Anytime you need your API key information, you can return to your Flickr homepage.

Now we can get started adding our Flickr API to our webpage. Flickr offers a great developer guide. You may want to look this over before you continue working through this article.

On the API page, all of the methods are listed.

Clicking on a method will take you to the method's page which contains information about the method and it's parameters. It also provides you with example responses that your API call would receive. This is helpful to note.

One of the best resources Flickr provides is called the API Explorer. A link to this page can be found at the bottom of every method's page. For this article we will be using the getPublicList method for a user's favorite photos. The API Explorer method can be found here. The API explorer allows you to input the method's parameters and generates the REST web request for you.

The getPublicList method only requires one parameter, your user id. Your id is visible on the right side. All you must do is enter the id and click the "send" box. You must also choose how you wish to send the request, signed with full permissions, signed with no permission, or unsigned. For this example we will be using unsigned calls but you may choose whichever you prefer. When you're done click the "call method" button. A text box will appear below with the XML response that will be returned to you. Below the text box is the url for the method call. This is important to note because we will use this url that the api has generated for you. Keep this page open because you may want to reference it later.

Let's add our api call to our webpage. Head back to WebMatrix and make sure your .cshtml page that you created is open.

If you have had experience with web requests you may have noticed that the Flickr API uses the RESTful format. This means that your webpage will make a request and you will receive a response with the information you requested. You can then do something with the requested information on your webpage. Because our response will be in XML, we can use the XMLTextReader class to parse our web response. To do that, we must define some directives. This must be done first thing on the page. At the very top of your .cshtml file, add:

@using System.Xml;
@using System.IO;
@using System.Text;

Now we're ready to add our web request. Firstly, we need to add our request uri - this is the method call that was at the bottom of the api explorer page. Anywhere in your .cshtml (if must be *after the code we added earlier) add your method call:

string uri = 
"http://api.flickr.com/services/rest/?method=flickr.favorites.getPublicList&api_key={your-api-key}&user_id={your-user-id}";   

Note that you must replace your-api-key and your-user-id with your correct information. If you're going to copy the request from the webpage all you must do is set it as the variable uri's value. Also, remember that blocks of Razor code must be between { }. Make sure all your code will between these brackets.

We now need to make our web request. Add below your uri:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);     
WebResponse response = request.GetResponse();
Stream strm = response.GetResponseStream();
XmlTextReader reader = new XmlTextReader(strm); 

We now have our web request and stored our web response in a stream. We have also created our XMLTextReader which we will use to parse through our response.

Now we need to parse through our response. Remember how our response was given to us on the api explorer page. This is helpful to go back and review. You will know exactly how your response will be structured which makes it much easier to parse through with our XMLTextReader. Looking at our response, we will want information about the photos so we can display these photos on our page. But, you may notice a problem. The image urls aren't given to us, this means that we can't display the images on our page. We will have to map our photo response to their correct urls. Luckily, Flickr has a webpage that shows us how to do that. Go here to see the url format of images.

You may notice that there are several different formats we could use. For this example, we will use the simplest: http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpg. Notice that there are 4 elements that we must add to the url - farm-id, server-id, photo id, and the secret. All of this information can be found as an attribute of the <photo> elements we received in our web response.

Now we know that we must retrieve these attribute values and add them to the url string in order to display the user's favorite images on our page. Let's make variables for these attribute values. Add to your page:

    string serverID = String.Empty;
    string imageID = String.Empty;
    string secret = String.Empty;
    string farmID = String.Empty;
    string imageURL = String.Empty;

Now that we have our web request, our web response, and our variable, we are ready to parse through our response. Since we want our images displayed on our webpage, we can parse through our response within the <body> of our page. As noted earlier, Razor code can go anywhere on your page!

Add between <body< and </body>:

@{
    while (reader.Read()){
        if (reader.Name == "photo") {
            imageID = reader.GetAttribute("id");
            secret = reader.GetAttribute("secret");
            serverID = reader.GetAttribute("server");
            farmID = reader.GetAttribute("farm");
            imageURL = "http://farm" + @farmID + ".static.flickr.com/" + 
@serverID + "/" + @imageID + "_" + @secret + ".jpg";
            <p><img src="@imageURL" /></p>
        }                       
    }
}

In our code we read through our web response. If we come across an element called photo we set the values of it's attributes into our variables. Once we've gotten all the information we need, we create our image url string by adding the info from our variables. Once this is done we display the images on our webpage.

Your entire code should be similar to this:

@using System.Xml;
@using System.IO;
@using System.Text;
@{
    string serverID = String.Empty;
    string imageID = String.Empty;
    string secret = String.Empty;
    string farmID = String.Empty;
    string imageURL = String.Empty;
    string uri = 
"http://api.flickr.com/services/rest/?method=flickr.favorites.getPublicList&api_key={your-api-key}&user_id={your-user_id}";   
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);     
    WebResponse response = request.GetResponse();
    Stream strm = response.GetResponseStream();
    XmlTextReader reader = new XmlTextReader(strm); 
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <h1>My Favorite Photos from Flickr</h1>
        @{
            while (reader.Read()){
                if (reader.Name == "photo") {
                    imageID = reader.GetAttribute("id");
                    secret = reader.GetAttribute("secret");
                    serverID = reader.GetAttribute("server");
                    farmID = reader.GetAttribute("farm");
                    imageURL = 
"http://farm" + @farmID + ".static.flickr.com/" + @serverID + "/" + @imageID + "_" + @secret + ".jpg";
                    <p><img src="@imageURL" /></p>
                }                       
            }
        }
    </body>
</html>

We can now run our webpage to see our favorite images displayed. Run your file by clicking "run" on the menu ribbon.

Your webpage will open in your default browser.

If you want to use other method calls, you can simply use the API Explorer to have Flickr generate the method calls for you.

This was just a quick example to get you started using the Flickr API.

Additional Resources

Download WebMatrix http://www.microsoft.com/web/webmatrix/

Learn how to Download and Install WebMatrix http://www.microsoft.com/web/post/web-development-101-part-1-getting-started-with-webmatrix

Learn more http://www.microsoft.com/web/post/Web-Development-101-using-WebMatrix

Create a website with a WebMatrix site template http://www.microsoft.com/web/post/create-a-website-from-a-webmatrix-site-template

Publish your website http://www.microsoft.com/web/post/how-to-publish-a-web-application-using-webmatrix

Learn to download, edit and republish your website http://www.microsoft.com/web/post/download-edit-and-republish-your-website-with-webmatrix

You can discuss this article using the adjacent Facebook talkback.

For technical questions please visit our discussion forums, where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to answer your questions!