Javascript example using flickr api to fetch random images with tags
To add semi-random images from flickr to websites, you can call javascript code from flickr that returns a list of images according to selection criteria that you provide.
Getting images that have certain tags
In this first bit of code we specify the function 'jsonFlickrApi' that will be called by the flickr API to process the list of images that we queried it for. The function we specify here picks a random image from the list of images returned by flickr and asks the browser to display it.
<script type="text/javascript" language="javascript"> function jsonFlickrApi(rsp) { if (rsp.stat != "ok"){ return; } var s = ""; var i = Math.random(); i = i * 100; i = Math.ceil(i); photo = rsp.photos.photo[ i ]; t_url = "http://farm" + photo.farm + ".static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_" + "m.jpg"; p_url = "http://www.flickr.com/photos/" + photo.owner + "/" + photo.id; s = '<img alt="'+ photo.title + '"src="' + t_url + '"/>' ; document.writeln(s); //this tells the JavaScript to write //everything in variable "s" onto the page } </script>
The code below calls the flickr API to fetch the images. The important parameters here are : tags, tag_mode and api_key.
- tags contains a list of comma separated tags.
- The tag_mode parameter specifies how to use tags. If tags_mode is set to all, then flickr will return a list of images that have all the tags specified by the tags attribute. If tags_mode is set to any, flickr will return images that have any of the tags indicated by the tags attribute.
- The api_key field, indicates an authentication key provided by flickr that you can obtain from here.
<script type="text/javascript" language="javascript" src="http://api.flickr.com/services/rest/?format=json&sort=randommethod=flickr.photos.search&tags=japan,food&tag_mode=allapi_key=66c61b93c4723c7c3a3c519728eac252"> </script>
This is the script in action, displaying random images about Japanese food.
| Labels: howto, coding |
|

Comment
Thanks for the code although there is two typos in the flickr url. You've missed two &. One between random and method One between mode=all and apikey
Thanks for the help.
Is it possible to fetch photos from a particular user?
Thanks.
setgetgo has a pretty awesome random image api, crazy stuff comes out of there: randomimage.setgetgo.com