Skip to content

Instantly share code, notes, and snippets.

@nothingalike
Created September 28, 2019 02:16
Show Gist options
  • Save nothingalike/d10f6f24421e555f16bf42e83864b43f to your computer and use it in GitHub Desktop.
Save nothingalike/d10f6f24421e555f16bf42e83864b43f to your computer and use it in GitHub Desktop.
LOTR!!!
#We need to import our 'requests' library/package in order to have the ability to make an HTTP call
import requests
def checkKey(dict, key):
# Original Logic
# if key in dict.keys():
# return True
# else:
# return False
# simpler expression
return key in dict.keys()
#a simple variable that holds our API Key to our TheOneApi
apiKey = "wyA5fQhAvYYnDVVjFYOl"
#execute a HTTP GET request to:
# url: https://the-one-api.herokuapp.com/v1/character
#with header:
# Authorization: Bearer (value of variable apiKey)
response = requests.get(
'https://the-one-api.herokuapp.com/v1/character',
headers={'Authorization': 'Bearer %s' % (apiKey)},
)
#save response data (aka the json) to a variable
jsonResponse = response.json()
#Since the json data stores the list of characters on the key 'docs' we will loop through this key
# (note: python translates json to a Dictionary, hence 'docs' is a key whose value is an Array of Dictionaries)
for x in jsonResponse["docs"]: #x = a dictionary of Character Properties [name, race, gender, etc]
#We want to treat the following scenarios the same:
# 1) the key does not exist
# 2) the key exists but does not have a value set
# aka name = "Troxyn" vs name = ""
# name = "" => this is known as an Empty String
#1) the key does not exist
#Lets store whether or not x has a name, race and gender
hasName = checkKey(x, "name")
hasRace = checkKey(x, "race")
hasGender = checkKey(x, "gender")
#2) the key exists but does not have a value set
#If x does have a name, race and/or gender
# lets make sure that the value of said key (name/race/gender) actually has a value and is not empty/blank
#
# note: i added another check because even if the key exists it could be None/null
if hasName:
hasName = x["name"] != "" and x["name"] != None
if hasRace:
hasRace = x["race"] != "" and x["race"] != None
if hasGender:
hasGender = x["gender"] != "" and x["gender"] != None
#We want to produce the 1 of the following 4 statements
# 1) Name is a Race and is Gender
# 2) Name is a Race
# 3) Name is Gender
# 4) Hi Name
#in order to product 1 of 4 statements, we have to have a name
if hasName:
if hasRace and hasGender:
print("%s is a %s and is %s" % (x["name"], x["race"], x["gender"]))
elif hasRace and not hasGender:
print("%s is a %s" % (x["name"], x["race"]))
elif not hasRace and hasGender:
print("%s is %s" % (x["name"], x["gender"]))
else: #we only have a name
print("Hi %s" % (x["name"]))
else: # we dont have a name,
print("EPIC FAILURE, NO NAME!!!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment