Search code examples
oauthgitlab-api

How to get the GitLab userid in a Python app that uses GitLab as an Oauth provider?


I'm writing a Python app that uses GitLab as OAuth provider. When an user logs in in the app (which redirects to GitLab login), the app receives an oauth token.

Using the GitLab API in Python, how can my app get the current GitLab userid?

I've tried something like this:

import gitlab

# create a GitLab API client
gitlab_url = 'https://your.gitlab.url/api/v4'
auth_token = 'your-auth-token-here'
gl = gitlab.Gitlab(gitlab_url, private_token=auth_token)

# get the current user's information and the user id
user_id = gl.user.id

print(f'The user ID is {user_id}')

but gl.user is None.


Solution

  • I solved it by replacing private_token by oauth_token, then calling gl.auth():

    import gitlab
    
    # create a GitLab API client
    gitlab_url = 'https://your.gitlab.url/api/v4'
    auth_token = 'your-auth-token-here'
    gl = gitlab.Gitlab(gitlab_url, oauth_token=auth_token)
    gl.auth()
    
    # get the current user's information and the user id
    user_id = gl.user.id
    
    print(f'The user ID is {user_id}')