Skip to main content

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.

Comments

Popular posts from this blog

On Pruning Your Passions

We live in a hobby-rich world. There is no shortage of pastimes to grow a passion for. There is a shortage of one thing: time to indulge those passions. If you're someone who pours your heart into that one thing that makes your life worthwhile, that's a great deal. But, what if you've got no shortage of interests that draw your attention and you realize you will never have the time for all of them?

If I look at all the things I'd love to do with my life as a rose bush I'm tending, I realize that careful pruning is essential for the best outcome. This is a hard lesson to learn, because it can mean cutting beautiful flowers and watching the petals fall to the ground to wither. It has to be done.

I have a full time job that takes a lot of my mental energy. I have a wife and a son and family time is very important in my house. I try to read more, and I want to keep up with new developments in my career, and I'm trying to make time for simple, intentional relaxing t…

The Insidiousness of The Slow Solution

In software development, slow solutions can be worse than no progress at all. I'll even say its usually worse and if you find yourself making slow progress on a problem, consider stopping while you're a head.

Its easy to see why fast progress is better: either you solve the problem or you prove a proposed solution wrong and find a better one. Even a total standstill in pushing forward on a task or a bug or a request can force you to seek out new information or a second opinion.

Slow solutions, on the other hand, is kind of sneaky. Its insidious. Slow solution is related the Sunk Cost Fallacy, but maybe worse. Slow solutions have you constantly dripping more of your time, energy, and hope into a path that's still unproven, constantly digging a hole. Slow solutions are deceptive, because they still do offer real progress. It is hard to justify abandoning it or trying another route, because it is "working", technically.

We tend to romanticize the late night hacking…

Why I Switched From Git to Microsoft OneDrive

I made the unexpected move with a string of recent projects to drop Git to sync between my different computers in favor of OneDrive, the file sync offering from Microsoft. Its like Dropbox, but "enterprise."

Feeling a little ashamed at what I previously would have scoffed at should I hear of it from another developer, I felt a little write up of the why and the experience could be a good idea. Now, I should emphasize that I'm not dropping Git for all my projects, just specific kinds of projects. I've been making this change in habit for projects that are just for me, not shared with anyone else. It has been especially helpful in projects I work on sporadically. More on why a little later.

So, what drove me away from Git, exactly?

On the smallest projects, like game jam hacks, I just wanted to code. I didn't want to think about revisions and commit messages. I didn't need branching or merges. I didn't even need to rollback to another version, ever. I just …