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?
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With