Python Programming
A function in a programming language represents reusable code. You can define how it’s supposed to work and reuse it repeatedly instead of writing out the same lines of code in different places. The below code defines a simple function that takes parameters and returns data in a specific format (JSON). A parameter is something provided to the function to make it work. In this case the function takes a URL, an ending to attach to the URL, and
requests data. The parameters are called “baseUrl” and “ending.” The function then returns the data that’s provided.
from requests import get
def getHarryPotterData(baseUrl, ending):
response = get(baseUrl + ending)
jsonList = response.json()
return jsonList
We have used the requests library before. In previous code, we simply wrote something like this:
response = get( ‘https://hp-api.herokuapp.com/
This returns data about Harry Potter characters, such as name, species, eye color, and so on. If we want to get just the staff from the list of characters, we can make a request like this:
response = get(‘https://hp-api.
And if we want just the students, we can make a request like this:
response = get(‘https://hp-api.
Notice that in each case, the URL provided to get the data varies slightly. In each case, you always have ‘https://hp-api.herokuapp.com/
response = getHarryPotterData(‘https://
For homework, copy and paste the below code and run it. What’s the output?
from requests import get
def getHarryPotterData(baseUrl, ending):
response = get(baseUrl + ending)
jsonList = response.json()
return jsonList
baseUrl = ‘https://hp-api.herokuapp.com/
listOfEndings = [‘/characters’, ‘/characters/students’, ‘/characters/staff’]
listOfKeys = [‘name’, ‘species’]
listOfJsons = []
for ending in listOfEndings:
currentJson = getHarryPotterData(baseUrl, ending)
for s in currentJson:
print(s[listOfKeys[0]], s[listOfKeys[1]])