pm21-dragon/exercises/release/exercise-11/2__making_HTTP_get_calls.ipynb
2025-01-10 09:56:07 +01:00

12 KiB

None <html> <head> </head>
In [ ]:
# Import libraries we need
import requests
import urllib.parse
In [ ]:
# You must run this cell, but you can ignore its contents.
import hashlib

def ads_hash(ty):
    """Return a unique string for input"""
    ty_str = str(ty).encode()
    m = hashlib.sha256()
    m.update(ty_str)
    return m.hexdigest()[:10]
In [ ]:
SWAPI_BASE='https://swapi.py4e.com/api/'

def starwars_url(path):
    '''return a URL to the Star Wars API using SWAPI_BASE
    
    For example, to get the URL for person with ID 10,
    call:
    
        starwars_url('people/10/')
    '''
    return urllib.parse.urljoin(SWAPI_BASE,path)

We need to be able to create an HTTP request to get a particular person from SWAPI. We are going to be making HTTP GET requests using the URL to request the information we want. So, we need to create a String with the appropriate request.

Q1 Define a function which will take an integer as an argument and return a string, which is the URL to get that particular person from the SWAPI. Call your function get_person_url.

For example for person 42, this function should return something like: "https://swapi.dev/api/people/42/". However, the URL should be made with the starwars_url() function so that it starts with the value SWAPI_BASE (and not necessarily https://swapi.dev/api). This is useful in case the website changes location or in case we decide to start hosting our own copy of the website at a different URL.

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks that the above worked
person_10_url = get_person_url(10)
assert(type(person_10_url)==str)
assert(person_10_url.startswith(SWAPI_BASE))
assert(person_10_url.endswith('people/10') or person_10_url.endswith('people/10/'))

Now, let's use the Python requests library to make an HTTP GET call to this URL. View its documentation at https://docs.python-requests.org/en/latest/.

Q2 Using your get_person_url() function, create a variable called person_url for person 10. Now, assign the result of requests.get(person_url) to a variable called response.

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks that the above worked
assert ads_hash(response.json()['name'])=='6e84377ee7'

Now let's wrap this up in a function which takes a person ID number and returns a dictionary for that person using the response.json() method from requests.

Q3 Make a function called get_person which takes an integer as an argument and returns a dict with the result from the SWAPI

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks that the above worked
assert ads_hash(get_person(1)['name'])=='9d00804504'

HTTP POST requests

Up to now, we have been using HTTP GET requests. These are what your browser does when you go to a webpage and are good for getting information.

Sometimes, however, we want to upload more complicated data to another program. This is often done with the HTTP POST request.

Here we are going to POST data to a server which will add a value to our input.

In [ ]:
ADDER_URL = 'http://http-demo-server.strawlab.org/'
response = requests.post(ADDER_URL+'add_to_value', json={'value':100})
In [ ]:
# Any status code other than 200 is an error
response.status_code
In [ ]:
response.text
In [ ]:
response.json()

Q4 What is the value added the the input by the HTTP server? Put your answer in the variable added.

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks that the above worked
assert ads_hash(added)=='73475cb40a'

Q5 There is another path on our server called mystery. It works similarly to add_to_value. What is the JSON value returned by this HTTP endpoint when called with an input value of 100? Put your answer in the variable mystery100.

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks that the above worked
assert ads_hash(mystery100)=='26d228663f'

Q6 Play around with this mystery until you think you understand what it is doing. Now make a function called myfunc which takes a single integer argument and returns an integer which should do the same thing as the mystery HTTP endpoint.

In [ ]:
# YOUR CODE HERE
raise NotImplementedError()
In [ ]:
# This checks that the above worked
assert ads_hash(type(myfunc))=='ac75372cfc' 
assert ads_hash(myfunc(3))=='6b51d431df'
assert ads_hash(myfunc(5))=='f5ca38f748'

What have we learned here?

HTTP is the "language" (protocol, to be technically correct) that your web browser uses to get webpages and images on the internet. More than that, it is also a useful language for computer programs to talk to each other on the internet.

(HTTPS is just a secure version of HTTP. This means it is encrypted and there is a cryptographic "chain of trust" to the owner of the domain name.)

GET requests typically just get a certain resource.

POST requests often send more data to the server. The server then does something with this data.

There are other HTTP request types, but GET and POST are the dominant ones.

There are zillions of data sources on the internet that you can access with HTTP.

</html>