Your browser is very old. You might enjoy surfing the web more if you used something newer like:

Google Chrome

Even Firefox would be OK.

If you're being forced at gunpoint to use Internet Explorer, you should at least upgrade it. Version 8 is tolerable and 9 will be OK when it comes out.

Posts tagged “api”

Flickr REST API Basics

It’s been a while since I’ve played with the Flickr API and I was pleasantly surprised by how much easier it’s gotten to use. I don’t believe the REST interface was available last time I tried (although it’s possible I was just dumb and missed it) so I ended up using somebody’s PHP XML-RPC class which was a bit clunky.

The REST API is dead-simple to use. The basic url format is


http://api.flickr.com/services/rest/?method=<method-name>&name=value...

While only some API calls require authentication, all require an API key.

Here’s what a call to flickr.photos.search method might look like:


http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=YOURKEY&tags=monkey

The above call returns the 100 most recently uploaded photos matching the tag monkey. The flickr.photos.search method has lots of other options that let you customize the search.

You get back a big chunk of XML (there’s a parameter to return JSON and several other formats instead) that looks like this:

<rsp stat="ok">
    <photos page="1" pages="3410" perpage="100" total="340901">
        <photo id="4195976808" owner="40592053@N02" secret="7605f0aa9f" server="2698" farm="3" title="373" ispublic="1" isfriend="0" isfamily="0"/>
        <photo id="4195224913" owner="32143071@N00" secret="199a3c18cb" server="2650" farm="3" title="Q & Milk II" ispublic="1" isfriend="0" isfamily="0"/>
    </photos>
</rsp>

Once you have a photo id, you can call flickr.photos.getinfo which, among other things, lets you get the URL to the page for that photo. You can also get thumbnail URLs in different sizes with a call to flickr.photos.getSizes.

I decided to do my latest playing around in Python rather than PHP. Here’s a very basic function I threw together for making API calls:

def flickrRequest(method, params):
    args = '&' + '&'.join([key + '=' + str(params[key]) for key in params.keys()])
    url = "http://api.flickr.com/services/rest/?method=" + method + args
    resp = urllib2.urlopen(url)
    raw_xml = unicode(resp.read(), errors="ignore")
    return minidom.parseString(raw_xml.encode("utf-8"))

It takes an API method name a dictionary of parameters, then uses urllib2 to get the XML response. The XML response is parsed using minidom and the DOM object is returned.

Since this is just for fun, the code basically just glosses over the Unicode aspect of the response by ignoring any Unicode errors. This lets us parse the XML at the expense of possible mangling some characters (generally only in the image title).

This is how the above function would be used to do a simple search:

tags = ["monkey", "chimp"]

searchParams = {
                    'api_key': FLICKR_API_KEY,
                    'tags': ','.join(tags),
                    'tag_mode': 'any',
                    'content_type': 1,
                    'page': 1
                    'sort': 'date-posted-desc',
                    }

dom = flickrRequest('flickr.photos.search', searchParams)

This searches for any pictures that are tagged monkey or chimp. This only returns the first page (the first 100 by default). You can get the next batch by incrementing the page parameter.

Now let’s say I want to call flickr.photos.getInfo for each image:

#This gives me all of the 'photo' nodes in the XML
photos = dom.getElementsByTagName("photo")

for photo in photos:
  dom = flickrRequest('flickr.photos.getInfo', {'api_key': FLICKR_API_KEY, 'photo_id': photo.attributes["id"].value})

  #The dom object now contains XML with info about the current photo
  #You can take a look at the format here:  http://www.flickr.com/services/api/flickr.photos.getInfo.html

And that’s the basics of using the Flickr REST api. My ultimate goal with learning the API is to write some sort of script that will let me backup all of the meta-information (tags, sets, collections, descriptions) of my Flickr account.

Where am I? Where are you?

Today, we’re going to cover the very basics of the Google Maps API which, like most of the other Google APIs I’ve been playing with, is very full-featured and easy to use.

I’ll show the basic code to embed a map on a web page and place a marker at a specific address.

Map of Washington, DC

The first thing to do is add the appropriate script tags to the <head> tags of your page.


    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>

    <script src="http://maps.google.com/maps?file=api&v=2&sensor=false
        &key=ABQIAAAAJKAoDxf0DXpmiPNGeIJ5_BTGeqkvninRPqN0VBb3AwYRVTSEZxQ5doci0or7L4Elev6DsRR4ertl1A"
        type="text/javascript">
    </script>

Notice the key parameter. That’s your API key (which is domain-specific). You can get your own by signing up here.

The first thing to do is create a couple of global variables for the map & geocoding objects. We initialize the map (giving it a <div> to put the map content in), add the zoom control, and enable scroll wheel zooming. The home function centers the map over the middle of the United States and sets the zoom level so the whole country is visible.

  var geocoder;
  var map;

    function home() {
                        map.setCenter(new GLatLng(37.0625, -95.677068), 3);
                    }

    Event.observe(window, 'load', function() {
                        map = new google.maps.Map2($('map_canvas'));
                        geocoder = new GClientGeocoder();

                        map.addControl(new GSmallZoomControl3D());
                        map.enableScrollWheelZoom();

                        home();
                    })

Here’s the html of the <div> where the map content gets placed.


        <div id="map_canvas" style="border:1px solid #979797; background-color:#e5e3df; width:400px; height:300px; margin-bottom:  10px;">
            <div style="padding:1em; color:gray;">Loading...</div>
        </div>

The code for placing a marker is pretty simple. The point variable is a GPoint object which is the Latitude and Longitude of where to place the marker.


    var marker = new GMarker(point);

    map.addOverlay(marker);

This page shows the above in action by letting the user enter an address and place a marker on the map for that address.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Where am I?  Where are you?</title>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>

        <script src="http://maps.google.com/maps?file=api&v=2&sensor=false
        &key=ABQIAAAAJKAoDxf0DXpmiPNGeIJ5_BTGeqkvninRPqN0VBb3AwYRVTSEZxQ5doci0or7L4Elev6DsRR4ertl1A"
        type="text/javascript">
        </script>

        <script type="text/javascript">
                    var geocoder;
                    var map;

                    function showAddress(address) {
                        if (geocoder) {
                            geocoder.getLatLng(
                                address,
                                function(point) {
                                    if (!point) {
                                        alert(address + " not found");
                                    } else {
                                        var marker = new GMarker(point);
                                        map.addOverlay(marker);
                                        marker.openInfoWindowHtml(address);
                                    }
                                }
                            );
                        }
                    }

                    function home() {
                        map.setCenter(new GLatLng(37.0625, -95.677068), 3);
                    }

                    Event.observe(window, 'load', function() {
                        Event.observe($('mapit'), 'click', function(event) {
                            Event.stop(event);

                            if($('address').value) {
                                showAddress($('address').value);
                            }
                        });

                        map = new google.maps.Map2($('map_canvas'));
                        geocoder = new GClientGeocoder();

                        map.addControl(new GSmallZoomControl3D());
                        map.enableScrollWheelZoom();

                        home();
                    })

        </script>
    </head>
    <body>
        <div id="map_canvas" style="border:1px solid #979797; background-color:#e5e3df; width:400px; height:300px; margin-bottom:  10px;">
            <div style="padding:1em; color:gray;">Loading...</div>
        </div>

        <textarea id="address" rows="3" cols="35"></textarea><br />
        <input type="submit" id="mapit" value="Map It!" />
    </body>
</html>