g.raphaelli's weblog

Flickr.API Helper Script

written by g, on Aug 7, 2009 11:23:00 AM.

Here is a [formerly] little script I use to test out Flickr API calls: flickrcall.py. It grew by about 200 lines getting it ready for posting here and it's still not pretty. It does work though, so use it like this:

Create a config file (optional, you can specify the key and secret on the command line)

$ cat > ~/.flickr.cfg
[api]
key = your key
secret = your secret
^D

Make the call

$ flickrcall.py flickr.test.echo foo=bar -j -b

that will return the familiar:

{"api_key": {"_content":" your api key"},
 "foo":{"_content":"bar"}
 "nojsoncallback":{"_content":"1"},
 "method":{"_content":"flickr.test.echo"},
 "format":{"_content":"json"},
 "stat":"ok"}

Need to make an authenticated call but don't have a token yet? Pass in -t:

$ flickrcall.py -t -j -b -p write flickr.contacts.getList page=1 per_page=5
auth me:  http://flickr.com/services/auth/...
done [y]:
try auth_token= acquired_auth_token next time for write permissions

Some desktop auth action later you have a token for use in subsequent calls. Of course, you also get the response you were (hopefully) after:

{u'stat': u'ok', u'contacts': {u'perpage': 1000, u'pages': 1, u'contact': [ ....

I often just run ipython -i flickrcall.py ... to get an interactive session, the 'rsp' and 'r' variables contain the response object and the whole response as a string so you can mess with parsing or otherwise interrogate Flickr's response.

Finally, flickrcall can be used as a library

>>> import flickrcall
>>> flickrcall.main("flickr.test.echo", "-n", "foo=bar", bar="foo").read()
'<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<api_key> your_api_key </api_key>
<foo>bar</foo>
<bar>foo</bar>
<method>flickr.test.echo</method>
</rsp>'

Here is the full usage:

$ flickrcall.py -h
Usage: flickrcall.py [options] api.method [key=val ... ]

Options:
  -h, --help            show this help message and exit
  -c CONFIG, --config=CONFIG
                        flickr config file
  --no-sign             don't sign request
  -k KEY, --key=KEY     Flickr API key
  -s SECRET, --secret=SECRET
                        Flickr API secret
  -n, --no-secret       don't use the Flickr API secret
  -p PERMS, --permissions=PERMS
                        permissions
  -t, --get-auth-token  get an authentication token first
  -b, --nojsoncallback  nojsoncallback=1
  -j, --json            request response in json
  -x, --xml             request response in xml (rest)
  -D, --debug           print some details about what's going on

A few things that could be added another day:

  • Optional checkToken
  • Loading/Saving auth tokens in the config file
  • Multiple API Key config file support