Leveraging the Flickr API from the .NET Framework

Introduction

I think any developer would agree: If it doesn't have an API, it ain't Web 2.0. And although the big guys often don't provide managed code interfaces for the .NET developer, there's always someone out there who will take the time to wrap their API and provide easy access for the rest of us.

Flickr, of course, is among the original Web 2.0 applications. Like Gmail, and a few others, Flickr was Web 2.0 before anyone called it Web 2.0. By now, Flickr's ability to host your vacation shots or your fine art photography and its rich supporting functionality is the standard by which all the others measure. And, fortunately, Flickr hasn't neglected its API. The API regularly keeps pace as new features are added to the site. There's very complete support in the API, for example, for using a photo's geographical location (the GPS information on where the photo was shot).

In this piece, I'd like to introduce you to the Flickr API, point out some highlights and write an application that retrieves and displays a user's photos.

Wrap and Roll

You could use the Flickr API directly, but since it's written in unmanaged code, you'd have to use COM-access techniques. It's not difficult, but it's not that pretty either. And it's a hassle you'd have to deal with throughout your application. The easier approach is to leverage a wrapper that's done all of that for you. Fortunately, just such a wrapper is available on Codeplex (Microsoft's open-source library for cool, free .NET applications and source code). Go to: http://flickrnet.codeplex.com/

Click the big green Download button on the top right of the page and that will get you the DLL you need. (No need to download the source code unless you are curious.) Unzip the download someplace and you'll find two folders - Debug and Release. If you're not using the source code, you'll use the DLL in the Release folder.

Big kudos go to Sam Judson for his great work in creating this Flickr wrapper and making it available to the .NET community.

Getting Keyed In

Flickr wants to know who is calling their API. So to use it they require that you get a key and then reference that key when you make calls to the Flickr functions. There's no way to avoid this. Fortunately the process is simple and instantaneous. Go here: http://www.flickr.com/services/apps/create/. Click the Request an API Key link. On the next page click the big blue box that says Apply for a Non-Commercial Key. Finally, there's a form asking you to identify and describe your application. Fill in the form and click Submit. Two giant numbers will be displayed: a key and a secret. Copy them both and paste them someplace safe where you can reference them later in your code. For this example application, you'll only need the key.

Fumbling with Flickr

So what's next? How do I know what functions to call? The Documentation page for the Flickr wrapper on Codeplex begins "Ha Ha Ha Ha! No but seriously..." This doesn't bode well. Fortunately, you don't really need a lot of documentation because the wrapper closely mirrors the API of Flickr itself. And documentation for that is fairly complete: http://www.flickr.com/services/api/. Plus I'll show you how to get started in the next few sections.

Fire it Up

Start Microsoft Visual Studio. You can use the Flickr wrapper with either Visual Studio 2005 or Visual Studio Pro 2008 (I haven't tried it out yet on Visual Studio 2010, but there's no reason it shouldn't work there, too.).

Create a new application. You can access Flickr from a Windows Forms application, but the example for this article is ASP.NET. Now right-click your project and choose Add Reference. Navigate to the location where you unzipped the .NET wrapper you downloaded and select ...\Release\FlickrNet.dll. The DLL is copied to your project and you are ready to go.

Also, to make your coding a bit simpler, go to the project properties window, References section, and in the bottom listbox, scroll down to FlickrNet and check it off. That will import the namespace for all the pages in your application.

Avatars (No, Not the Blue People)

This example application will provide a page for the user to upload a picture to use as their avatar on your site (on a discussion forum, for example). They can either choose to upload the picture from their local computer or they can provide a Flickr account name and use one of their photos from there. The local upload option leverages the standard FileUpload server control. I'll focus on the implementation of the Flickr option in this article.

Figure 1 shows the UI I created, in design mode. The controls are arranged in a 2x2 table where the cells in the second column have been merged. I created a generic icon to be used in the image until the user selects their own. My image control is 128x128.


Figure 1. The Select an Avatar page in Microsoft Visual Studio

If the user chooses to select a picture from Flickr, they must first enter their Flickr account user name and then click Get Photos. They are not required to enter a password because this application will not be logging in to their account. The username will simply be used to search for the right pictures--so only the publicly accessible ones will be available (There are a set of functions to allow your application to actually log in with the user's credentials. The first time your application tries to do so, the user is required to confirm that your application should have access. From then on your application has full access to everything on their account.).

If the username is valid and there are pictures for that user, the listbox under the Get Photos button will be filled with the list of photo titles. The user can then click on a title to see the corresponding picture displayed in the image, as in Figure 2. Once they've found the one they want, they can click Use This One.


Figure 2. The user selects a title in the listbox and the photo is displayed with the image control.

Instantiation is the Key

Got that Flickr key ready to use? You only have to specify it once when you instantiate the Flickr API class and the wrapper handles passing it whenever it is needed. Listing 1 is from the Click event of the Get Photos button.

        If FlickrUsername.Text = "" Then
            FlickrStatus.Text = "You must enter a Flickr username"
            Return
        End If

        Dim myFlickr As New Flickr("AAAbbbCCC111222333DDDeeeFFF")

Listing 1. The first part of the GetPhotos_Click event.

After verifying that the user entered something for the username, the Flickr class is instantiated, passing the key you copied earlier (replace the bogus key above with your own).

The instantiated Flickr object (myFlickr above) is your entry point into the API. There are a number of classes that you can access within it. Among them:

  • People
    • Contacts
    • Blogs
    • Galleries
    • Activity
    • Authorization
  • Photos
    • Comments
    • Geographical Information
    • Tags
    • Licenses
    • Notes
  • Groups
  • Group Pools
  • Places
  • URLs

As you can begin to see, virtually every feature available on the site is available in the API.

Chasing Down the User

The next step is to get a reference to the user we want based on the username typed in. A handy function named PeopleFindByUsername does just that. In Listing 2, I call this function and receive the reference back. The data type of the reference variable is FoundUser--a type provided by the Flickr wrapper.

       Dim userRef As New FoundUser

        Try
            userRef = myFlickr.PeopleFindByUsername(FlickrUsername.Text)
        Catch ex As FlickrException
            FlickrStatus.Text = ex.Message
            Return
        End Try

Listing 2. The second part of the GetPhotos_Click event

The function is wrapped in a Try/Catch so that if the user is not found (or some other error occurs), the user is informed via the FlickrStatus label.

Retrieving the List of Photo

To retrieve the list of photos for the user, I use the PhotoSearch function. PhotoSearch accepts one argument of type PhotoSearchOptions. An instance of this class is used to fill in all the possible options you might want to use in a photo search. And there are a lot of possible options. For this application, however, I only need the UserId. UserId here is not the same as the username. It's a unique number that's used to identify users in functions like this one.

        Dim searchOptions As New PhotoSearchOptions
        Dim photoList As New Photos
        Dim currentPhoto As New Photo

        searchOptions.UserId = userRef.UserId
        photoList = myFlickr.PhotosSearch(searchOptions)

        FlickrPicsList.Visible = True

        For Each currentPhoto In photoList.PhotoCollection
            FlickrPicsList.Items.Add(New ListItem(currentPhoto.Title, _
            currentPhoto.SmallUrl))
        Next

Listing 3. The third and final part of the GetPhotos_Click event

Next the listbox is made visible and each of the photos in the collection returned is added to the listbox. For each item, a text and a value is set. The text (which is displayed) is the photo's title. The value (which is not displayed) is the URL needed to directly access the photo.

Showing Off

The user now has a list of their photos available. However all they see for each is its title. And not all Flickr users are careful to set their titles individually. So to make it easy for the user to identify the photo they've selected, the listbox's SelectedIndexChanged event is used to display the photo using the image control.

        Dim selectedPhotoUrl As String

        selectedPhotoUrl = FlickrPicsList.SelectedItem.Value
        PhotoDisplay.ImageUrl = selectedPhotoUrl

Listing 4. The FlickrPicsList_SelectedIndexChanged event

After the Flickr class is instantiated, I retrieve the value (not the text) of the listbox's currently selected item. You'll remember that this is the URL necessary to reference the photo directly. Since this was saved in the value for each listbox item, I don't need to do another query to Flickr to get the photo. I can just set the ImageUrl directly.

Conclusion

Of course this article only begins to demonstrate the possibilities available with the Flickr API, but I hope it whets your appetite for Flickr integration and gives the knowledge you need to launch into it more deeply.



About the Author

Bill Hatfield

Bill Hatfield is the best-selling author of numerous books for developers, including ASP.NET For Dummies, Active Server Pages For Dummies (on Classic ASP) and Visual InterDev For Dummies. He is also the editor of Visual Studio .NET Developer, a monthly technical journal from Pinnacle. He's an experienced corporate trainer and works in Indianapolis, IN where he also co-founded the local .NET group, the Indianapolis .NET Developers Association.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Where the business performance of their mobile app portfolios are concerned, most companies are flying blind. While traditional application portfolios are held to all kinds of ROI measure, the investment plan for mobile apps -- increasingly the more crucial bet -- is made by guesswork and dart-throwing. This interactive e-book investigates how mobile is driving the need for app and portfolio measures unlike any we saw in the days of web. Good mobile analytics must deliver leading indicators of user experience …

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds