Check user existence using GitHub API

Viewed 2039

I am using GitHub API with python. I want to validate the user existence.

url = f"https://api.github.com/users/{username}"

r = requests.get(url.format(username)).json()

I want to know that, what do GitHub API returns when the 'username' doesn't exists. I know it returns an error message of not found, but what do it returns as python? What can I do to validate it?

4 Answers

It returns a JSON object with an error message as follows:

{
  "message": "Not Found",
  "documentation_url": "https://developer.github.com/v3/users/#get-a-single-user"
}

You can look for the "message" key with a "Not Found" value in your response r to check if the user does not exist.

In short:

url = f"https://api.github.com/users/{username}"
r = requests.get(url.format(username)).json()
if "message" in r:
    if r["message"] == "Not Found":   # Just to be double sure
        print ("User does not exist.")

Edit: In case you're curious, I just tried with a bunch of random usernames, and soon found one that did not exist. That's how I found this response. Try with https://api.github.com/users/llllaaa

In python what you get is a map .

look for r['login'] if this value doesn't exits , which means the user_name you provided is a valid one. so you can throw some try catch like this.

import requests

def checkUser(user):
    url = f"https://api.github.com/users/{user}"
    r = requests.get(url.format(user)).json()
    try:
        return r['login']
    except:
        return 'No User'


print(checkUser('raja-ravi-prakash'))

So, I am answering my own question.

The method which worked best for me, and will work best in every situation is by calculating and validating it through the length of the dictionary it returns.

length = len(r)

If 'length' is equal to 2, username doesn't exist. else: username exist.

Because, the error message returned by the API, when username isn't found is in the form of:

{
  "message": "Not Found",
  "documentation_url": "https://developer.github.com/v3/users/#get-a-single-user"
}

as mentioned by @PrateekDewan in the above/below answer.

So, calculating and validating it using the length of the returned dictionary/map can be a short and simple solution.

An alternative solution, not relying on the response body, but simply checking the response status code.

A user is a resource in REST semantics.

If the user doesn't exist then we expect response status code 404 - Not Found.

Documented here on the Github API Docs - Get a user


Demo:

>>> import requests

>>> r = requests.get('https://api.github.com/users/vineetvdubey')
>>> r.status_code
200

>>> r = requests.get('https://api.github.com/users/non-existing-user__')
>>> r.status_code
404
Related