First we note the URL of where the data resides. Then we pass that as a parameter to the get function from the requests package, to issue an HTTP GET request:
import requests# the URL of some JSON data we stored online:request_url ="https://raw.githubusercontent.com/prof-rossetti/intro-software-dev-python-book/main/docs/data/gradebook.json"response = requests.get(request_url)print(type(response))
<class 'requests.models.Response'>
We receive a response object from the server. The response object has a few methods and properties we care about. First, the status code tells us if the request was generally successful:
response.status_code
200
The text property is a string that looks like it could one day be some data:
The final step is to convert this JSON-formatted string to actual Python data. We can do this using the json method of the response object, or by leveraging the loads function from the json module:
This data happens to be dictionary-like at the top level. However be aware, when we fetch JSON, it can be either list-like, or dictionary-like on the top level. So you must observe the structure of your particular data before processing it further.
students = data["students"]print(type(students))len(students)
<class 'list'>
10
Looping through the items:
for student in students:print(student["studentId"], student["finalGrade"])