thornomad
thornomad

Reputation: 6797

Get user info from YouTube Google API in Python (API v3)

I'm new to the Google APIs but making some progress; I have a Django app that is getting a list of a user's video uploads. This works great! I took everything from the docs and the examples Google offers.

I would like to be able to also get the user's profile information that is connected with the YouTube account they are authorized under (because a user on my site may have more than one YouTube account and I need to tell them apart).

Here is a simplified version of what I have that is working:

YOUTUBE_READONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

# added this to increase the scope
GOOGLE_USER_INFO_SCOPE = "https://www.googleapis.com/auth/userinfo.profile"

FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope=[ YOUTUBE_READONLY_SCOPE, GOOGLE_USER_INFO_SCOPE ],
    redirect_uri='http://127.0.0.1:8000/youtube/oauth2callback')

@login_required
def index(request):
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    credential = storage.get()

    http = httplib2.Http()
    http = credential.authorize(http)

    # gets a workable YouTube service!
    service = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=http)

    # how do I get the user name or email or other profile information here?

After reading this post I know I can't just use userinfo = build('userinfo', "v2", http=http) ... but I'm a little confused as to what I do next. I read this example but it appears to be using a different library (I installed the google-api-python-client).

Do I need to install a different library (the gdata library) in order to get user info? Or is the user info hidden in some other service I can call build on (like the Google+ service)?

Upvotes: 0

Views: 1136

Answers (1)

thornomad
thornomad

Reputation: 6797

So had to add an additional scope and it is part of the Google Plus API. This is the scope I added:

GOOGLE_PLUS_SCOPE = "https://www.googleapis.com/auth/plus.me"
GOOGLE_PLUS_SERVICE_NAME = "plus"
GOOGLE_PLUS_VERSION = "v1"

Here is how I did both scopes at the same time:

FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope=[ GOOGLE_PLUS_SCOPE, YOUTUBE_READONLY_SCOPE ],
    redirect_uri='http://127.0.0.1:8000/youtube/oauth2callback')

Finally, here is how I got the info about the logged in user:

userservice = build(GOOGLE_PLUS_SERVICE_NAME, GOOGLE_PLUS_VERSION, http=http)
userpeople = userservice.people()
me = userpeople.get(userId="me").execute()

print(me)

One thing to point out is I had to enable the Google+ API as well as the Contacts API. I don't know why but this wouldn't work until the Contacts API was enabled.

Upvotes: 2

Related Questions