Thursday, March 4, 2010

JSON Flickr Feed from Username

I needed to find a way to show flickr pictures for a Portal, and chose to hide the username in a hidden field to retrieve once it was given in registration. It's simple to use a JSON feed to retrieve a user's items if you know the User ID, but it's an extra step to acquire the User ID from the Username.

Solution: the Flickr findByUsername function
The first method requires a Flickr API Key. You can get this by going to: The App Garden. After you have signed up for an API, you can then proceed.

First, in the body, I created a hidden field called 'flickrUsername'. Then, i created a div called 'photoResults' to house the data.

Next, the jquery script:

$(function(){

var name = $('#hiddenFieldID');
if (name == ""){
$("#photoResults").html("Missing Flickr Username!");
}
else {
var userID;
$.getJSON("http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&username=" + name + "&api_key=fa70b734cfb2cd4858f509230aba0328&format=json&jsoncallback=?", function(data) {
userID = data.user.id;
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=" + userID + "&lang=en-us&format=json&jsoncallback=?", function(data) {
$.each(data.items, function(i, item) {
$("<img/>").attr("src", item.media.m).appendTo("#photoResults");
});
});
});
}

This will then display an array of that particular user's images.

0 comments: