Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check user existence using GitHub API

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?

like image 257
Anubhav Madhav Avatar asked Oct 28 '25 08:10

Anubhav Madhav


3 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

like image 55
Prateek Dewan Avatar answered Oct 31 '25 02:10

Prateek Dewan


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
like image 28
vineetvdubey Avatar answered Oct 31 '25 01:10

vineetvdubey


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

like image 35
Prateek Dewan Avatar answered Oct 31 '25 02:10

Prateek Dewan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!