Wednesday, July 15, 2009

How To Use the Youtube Data API: Authentication

After a couple days trouble with the Youtube Data API and the provided Python wrappers around it, I thought it would be good to collect my findings on what works and doesn't and to fill in the gaps that I see in the docs. I really hope this series will be useful to some others in my position.

Some Doors Are Locked and Some Doors Are Ajar

A lot of the APIs use requires no authentication, not even a developer key. This makes a lot of the most common, read-only integrations a snap. However, I think this makes it more difficult to adjust when the need to authenticate for other integration comes along. This did some damage to my schedule, so I'm going to help others avoid the problem.

Public operations are simple. Youtube gives us resources in the form of feeds and images and other things at API locations, like http://i.ytimg.com/vi/FedVhnHYn-Y/0.jpg to get the first thumbnail of a video. Just plug in your video ID and go.

When you get into the realm of authenticated requests, you've got to get a bit of foundation in place, to start. I don't recommend crafting any requests your self, so grab the client library for gdata. You'll also want to register your site and get a developer key.

With that all set up, gdata.youtube.service.YouTubeService is going to be your friend. The service object begins unauthenticated. At user authorization is can be upgraded single and long-term authenticated use. There is a ClientLogin path, intended for desktop applications, where you actually ask for their username and password. We won't be covering that.

AuthSub is going to be used. With this method, the user is directed from our site to a crafted URL at YouTube, essentially telling them "Hey, I want this user to let me access their account. Is that alright with them?" The user has the job of deciding if you are trusted or not. When they do, Youtube generates a special token to send to a URL you provided. The token you've been given is good for one request, so make it a good one! The best use of that one-time token is usually going to be exchanging it for a session token that you can keep using forever, until the user revokes your rights to their account. These are the steps we're going to see next.

def authsub_url(self, request):
base = '/return/path/at/my/website/'
next = 'http://%s%s?next=%s' % (
request.get_host(),
base,
urllib2.quote(request.build_absolute_uri()))
scope = 'http://gdata.youtube.com'
secure = False
session = True

return yt_service.GenerateAuthSubURL(next, scope, secure, session)

The function generates and returns a unique URL to direct our user to. It takes a request, because we need the host and I used the current URL in my own usage and the absolute URI as the return destination coming back from Youtube. You can also assume here that yt_service is an instance of gdata.youtube.service.YouTubeService, of course. Of note is the session parameter, passed as True, which enables the token we receive to be upgraded to a session token. The user will get a different message from Youtube, depending on this parameter, so they know what you might be doing and how much access they're authorizing.

You're callback URL will be brought up by the user with a token parameter added to the querystring, and you'll be expected to keep track of that.

    yt_service.SetAuthSubToken(token)
yt_service.UpgradeToSessionToken()
session_token = yt_service.current_token.get_token_string()

This part tripped me up for a bit, because the way the official docs are split among the official guide, the python guide, and the actual definitive(ish) API reference, it wasn't as clear that the single-use token and the session-token were distinct tokens, rather than the original becoming a session-token, which my understand was, at first. It would be a lot more clear, I think, if that UpgradeToSessionToken() actually returned that new token. Of course, this isn't important if you're just using the yt_service right now. If you need to store that token for future use, however, then it happens to be really important information.

Later, if you saved this token, you can easily use it again:

    yt_service.SetAuthSubToken(session_token)


Summary

The ease of use is pretty nice. Generate the authorization URL and direct the user there, take the returned token and upgrade it for session use, and from then on, you can do lots of fun things when their account.

No comments:

I write here about programming, how to program better, things I think are neat and are related to programming. I might write other things at my personal website.

I am happily employed by the excellent Caktus Group, located in beautiful and friendly Carrboro, NC, where I work with Python, Django, and Javascript.

Blog Archive