David Kitchen

Avatar

Just another SharePoint developer blogging

I’m in love with the Flickr API now they’ve added JSON

The Flickr web services were great, but just a little annoying in that to make them work in a web page I would always have to create wrappers on the server to perform the web service calls. I had to do this as if you’re in JavaScript you have no permission to perform a cross-domain XmlHttp call, and because if you’re not doing it in JavaScript you were on the server anyway.

The two biggest reasons I disliked this are that it added load to my server, and it added a dependency on the responsiveness of my server on the responsiveness of the Flickr servers.

That is now a thing of the past.

JSON is JavaScript Object Notation. It is a way of encapsulating within JavaScript a hierarchical object model and of populating that with properties, values and content.

It is documented here: http://www.json.org/ and is simply a joy to use.

All you need do is add a HTML script tag to your page with the SRC of that being the JSON web service that you wish to call, once the web service returns you have a JavaScript object that you can act on.

Because you can pull in JavaScript from across domains, this works across domains.

So I played around with it for half an hour last night and knocked out a demo. What the demo does is takes a username of a Flickr user (I’m “the boy on the bike”), looks up their Flickr Id, and then queries the most recent public photographs for that user and renders the thumbnails of them.

Here is a demonstration (right click to download the source).

Here is the code that I used, remember to change the flickApiKey to use it on your site:

<html>
<head>
</head>
<body>
<script type="text/javascript">
var totalThumbs = 16;
var thumbsPerRow = 4;
var flickrApiKey = '73cd571dac7cb8390a8e848ed7ab5c09';
var flickrUsername = '';
function jsonFlickrApi(rsp) {
	if (rsp.stat != "ok") {
		document.getElementById('flickrContainer').appendChild(
			document.createTextNode('Flickr Error: ' + rsp.message)
		);
		return;
	} else if (rsp.user) {
		var flickrPhotoScript = document.createElement('script');
		flickrPhotoScript.type = 'text/javascript';
		flickrPhotoScript.src =
			'http://www.flickr.com/services/rest/?format=json&api_key=' + flickrApiKey +
				'&method=flickr.people.getPublicPhotos&per_page=' + totalThumbs +
				'&user_id=' + rsp.user.id;
		flickrUsername = rsp.user.username._content;
		document.getElementById('flickrContainer').appendChild(flickrPhotoScript);
	} else if (rsp.photos) {
		for (var ii = 0; ii < rsp.photos.photo.length; ii++) {
			var photo = rsp.photos.photo[ii];
			if (!ii) {
				var userAnchor = document.createElement('a');
				userAnchor.href = 'http://www.flickr.com/photos/' + photo.owner + '/';
				userAnchor.appendChild(document.createTextNode(flickrUsername));
				document.getElementById('flickrContainer').appendChild(
					document.createTextNode(totalThumbs + ' Most recent photos from ')
				);
				document.getElementById('flickrContainer').appendChild(userAnchor);
				document.getElementById('flickrContainer').appendChild(
					document.createTextNode('.')
				);
				document.getElementById('flickrContainer').appendChild(
					document.createElement('br')
				);
			}
			var anchor = document.createElement('a');
			anchor.href = 'http://www.flickr.com/photos/' + photo.owner + '/' + photo.id + '/';
			var img = document.createElement('img');
			img.height = 75;
			img.width = 75;
			img.border = 0;
			img.alt = photo.title;
			img.src = 'http://static.flickr.com/' + photo.server + '/' + photo.id + '_' + photo.secret + '_s.jpg';
			anchor.appendChild(img);
			document.getElementById('flickrContainer').appendChild(anchor);
			if (ii % thumbsPerRow == thumbsPerRow - 1) {
				document.getElementById('flickrContainer').appendChild(
					document.createElement('br')
				);
			}
		}
	}
}
function flickrLoad() {
	var flickrUserScript = document.createElement('script');
	flickrUserScript.type = 'text/javascript';
	flickrUserScript.src = 'http://www.flickr.com/services/rest/?format=json&api_key=' + flickrApiKey +
		'&method=flickr.people.findByUsername&username=' + escape('the boy on the bike');
	document.getElementById('flickrContainer').appendChild(flickrUserScript);
}
if (document.attachEvent) {
	window.attachEvent('onload', flickrLoad);
} else if (document.addEventListener) {
	window.addEventListener('load', flickrLoad, false);
}
</script>
<div id='flickrContainer' class='smallfont'></div>
</body>
</html>

15 Comments, Comment or Ping

  1. Nice little script, I borrowed it – thanks :-)

  2. kil

    It’s a good job. Excellent widget! I’ve just installed in my blog. It looks really nice.

    Many thanks.

  3. Hi

    Excellent work, David.

    i’m a newbie with javascript but i try to customize your widget with elements seen on this page (http://www.flickr.com/services/api/misc.urls.html). I want to make a direct link to the original photo, none to the flickr photo page, because i use the lightbox script.

    Flickr show us how direct url is coded here
    http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)

    but i can’t translate this into your code. I make some tries, and no one works.
    Can you help me, please ?

    Thanks a lot

  4. Sure thing, what script are you using, and how do you want mine to fit into yours?

  5. OK. Thanks for your response.
    Here is an example of lightbox 2 :
    http://www.huddletogether.com/projects/lightbox2/

    I have to add “rel” attribute into the anchor and make a direct link to the picture like that image #1

    My problem is not to embed the “rel” attribute, but to make a direct link to the picture

    Example, your scirpt make a link to this page
    http://www.flickr.com/photos/punktitude/2983513071/
    and i want to make the link to this picture
    http://farm4.static.flickr.com/3282/2983513071_d2485b74cb_o.jpg

    flickr give me that code format http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)

    So i have to embed 2 more vars in your code :
    “farm-id” and “o-secret”

    i don’t know how to code them, in the same way than yours
    i.e. {server-id} become photo.server, {id} become photo.id, etc.

  6. OK, well I’m at a conference so it’s hard to go through all of the code. Flickr do not give me the farm id in the API, but through the getSizes call on the photos API I can get the source url.

    The only problem with this is that if you show 16 thumbnails, I’d need to do 16 calls to getSizes.

    I’ll email you an example of the code above adjusted to include this… and you can display the image at the point of the window.open call that I’ve currently got.

    I’m not sure lightbox 2 will support event driven opening of the lightbox, it seems to want to know early which photos are there to be lightboxed.

  7. « I’m not sure lightbox 2 will support event driven opening of the lightbox, it seems to want to know early which photos are there to be lightboxed. »

    You’re right. I try your original code with little changes to test lightbox (clicked link have to display the little size)

    var anchor = document.createElement(‘a’);
    anchor.href = ‘http://farm4.static.flickr.com/’ photo.server ‘/’ photo.id ‘_’ photo.secret ‘_m.jpg’;
    anchor.rel = ‘lightbox[occicant]‘;
    var img = document.createElement(‘img’);

    The link is OK, but the lightbox effect doesn’t work.

    Anyway, thanks a lot for your patience and your help.

    Cheers

    Steph

  8. I’ve just emailed you the latest version… it now works with Lightbox 2.

    You do have to make one modification to the lightbox.js so that the Lightbox instance is named and accessible, but that’s pretty simple.

    There is only one restriction, you cannot use the grouping functionality. I get the full Url for the ‘Medium’ size image using a separate AJAX call, and as such I don’t want to do 16 additional HTTP calls for a 16 thumbnail grid… so instead I only do that call per image once the user clicks the image. This is only ever done once, so if they click it again it uses the old information.

    Cheers

    David

  9. David, you are bsolutely amazing !

    I try it with the label Large (you use Medium) and it works too ! Then I say myself that perhaps there is a supernatural trick in your script, so i try it with the Original label and it’s completed.

    And at this step, I am very impressed !

    I’ve been pleased to keep your mind awake and very creative.

    I’ll embed all that stuff in my blogger. I’ll send you a mail to show you the final result.

    Thanks a lot !

    Cheers

    Steph

  10. Hello David. Forgive me for my ignorance but I’ve only just started to edit code and can’t seem to figure out where to insert this one. I think I’ve made the proper adjustments to it (ie changing the user name and entering my Flickr API), but the blog editor continues to reject the script. Any thoughts?

    Thanks a million!

    Best,
    Pablo

  11. xa

    Hello !

    After trying many unconvincing flickr widgets for blogger, I finally found this article and have to say yours is by far the most customizable / easy to setup one.
    Thanks a lot !

  12. Using this. it’s great.
    Any chance of helping me set up an auto refresh for the div?

    so it’s updating the feed?

    I wish this had the option of grabbing tags of sets from a group.

    This is really great and helps me learn some JSON.
    thanks for helping!

  13. Amber B.

    This works great! Thanks for sharing. Do you have any idea how to modify this so it pulls the image description from Flickr as well?

    I’m working on a site for someone who wants the image description to appear underneath each photo so they can just update it in Flickr and it will automatically show on their site.

    Any help is appreciated, thanks!

  14. You’ll be wanting to check out this method:
    http://www.flickr.com/services/api/flickr.photos.getInfo.html

    Just follow the example above in implementing it.

  15. RAKHI

    Could you please give some hints on how to do a flickr search dynamically using latitude and logitude location of a clicked location on google map in flickr and google maps mashup?

Reply to “I’m in love with the Flickr API now they’ve added JSON”