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/api/characters‘)

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.herokuapp.com/api/characters/staff‘)

And if we want just the students, we can make a request like this:

response =  get(‘https://hp-api.herokuapp.com/api/characters/students‘)

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/api‘ followed by something else. What if we could write something that took ‘https://hp-api.herokuapp.com/api‘ and also whatever ending we want, combine the two, and then get the data? For instance, what if we could write something that would just return students, meaning we provide the base URL,  ‘https://hp-api.herokuapp.com/api‘, and the ending, ‘/characters/students’? That’s just what the above definition does. Here is an example call:

response = getHarryPotterData(‘https://hp-api.herokuapp.com/api‘, ‘/characters/students’)

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/api
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]])

Menu