Flickr.API 0.4.2
Making a simple call
flickr.test.echo is a simple place to start and a good way to make sure that everything is set up correctly. It echoes back any parameters you provide.
import Flickr.API api = Flickr.API.API(key, secret=None) test_rsp = api.execute_method(method='flickr.test.echo', sign=False)
that returns:
<?xml version="1.0" encoding="utf-8" ?> <rsp stat="ok"> <api_key> your api key </api_key> <method>flickr.test.echo</method> </rsp>
- the default response format from flickr is xml (called 'rest' on http://www.flickr.com/services/api/response.rest.html)
- test_rsp is a file-like addinfourl instance, like that returned by urllib2.urlopen(). That means:
- test_rsp has a read() method, great for passing into ElementTree.parse() or json.load()
- test_rsp has an HTTP response code (test_rsp.code), which should be checked before you even bother to parse the response contents
- Every response from flickr is wrapped in rsp tags. Be sure to check the value of stat after every call
Adding some parameters to request a json response looks like:
test_json_rsp = api.execute_method( method='flickr.test.echo', args={'format':'json', 'nojsoncallback':1}, sign=False)
That returns:
{"api_key": {"_content":" your api key"}, "nojsoncallback":{"_content":"1"}, "method":{"_content":"flickr.test.echo"}, "format":{"_content":"json"}, "stat":"ok"}
There are numerous xml and json handling libraries in python so handling either response type is a matter of preference.
Putting it together
Putting these basic calls together to create a real application using the Flickr API should be pretty straightforward now. Let's say you'd like to write a command-line uploading utility. The Flickr API Upload Documentation specifies that uploading photos requires write permission on a user's account. This means we need to authenticate the user and get our application approved with write access. Desktop Auth lays out the approach (starting with step #3):
Request a frob
api = Flickr.API.API(key, secret) frob_request = Flickr.API.Request(method='flickr.auth.getFrob') frob_rsp = api.execute_request(frob_request) if frob_rsp.code == 200: frob_rsp_et = xml.etree.ElementTree.parse(frob_rsp) if frob_rsp_et.getroot().get('stat') == 'ok': frob = frob_rsp_et.findtext('frob')
This introduces the other way to make an api call with Flickr.API. Here, we create a Flickr.API.Request object as frob_request and pass that into api.execute_request. Note that now we provide the secret instead of None - the secret is required for generating api call signatures. api.execute_method is simply a convenience method that does exactly the same thing. Flickr.API.Request provides more options for configuration as it is a urllib2.Request object. This means you can configure a proxy server, add your own headers, etc. Also, execute_method() takes arguments as a dict (args={}), originally intended to mirror the way Flickr::API works. execute_request uses the more pythonic **kwargs for arguments.
We also see here some of the application-level error handling that needs to be done. Note that execute_request could throw any of the exceptions urllib2.urlopen() does so that should be wrapped in a try/except and handled appropriately.
Create a login link
The get_authurl method makes this step easy. Continuing with the command line uploader, here we display the link and wait until the user confirms that it visited that url. For web authentication, you don't get the frob until after authorization happens so you would just leave out the frob paramater.
auth_url = api.get_authurl('write', frob=frob) print "auth me: %s" % (auth_url,) input = raw_input("done [y]: ") if input.lower() not in ('', 'y', 'Y'): sys.exit()
Convert Frob to Token
token_rsp = api.execute_request(Flickr.API.Request( method='flickr.auth.getToken', frob=frob, format='json', nojsoncallback=1) ) if token_rsp.code == 200: token_rsp_json = simplejson.load(token_rsp) if token_rsp_json['stat'] == 'ok': token = str(token_rsp_json['auth']['token']['_content'])
Here we see how to handle a json response. Now that we have the token, we can make any authenticated calls by passing auth_token=token in the list of arguments.
Make an authenticated call
There are two methods for uploading photos provided in Flickr.API. Like execute_method, execute_upload is a convenience method that calls execute_request with the appropriate Flickr.API.Request object. That looks like:
photo = open('photo.jpg', 'rb') upload_response = api.execute_upload( filename='photo.jpg', args={'auth_token':token, 'title':'test upload', 'photo':photo})
If you need to build your own request object, that could look like:
photo = open('photo.jpg', 'rb') upload_request = Flickr.API.Request( url="http://api.flickr.com/services/upload", auth_token=token, title='test upload', photo=photo) upload_response = api.execute_request(upload_request, sign=True, encode=Flickr.API.encode_multipart_formdata)
Either way, the upload response contains the unique photo id assigned by Flickr to that photo. This response is always XML, even if you try to specify the response format. The url to that photo is: http://www.flickr.com/photos/nsid/photoid or just: http://www.flickr.com/photo.gne?id=photoid.
That's it, go create.
