Week 7: Working with External Data
with open(...) as f:
syntax.'r'
is for reading from a file.'w'
is for writing to a file (this will overwrite the existing content).'a'
is for appending to the end of a file.{}
).[]
).json
libraryjson
library gives us two key functions for working with json data and files.json.dump()
: serializes a python object (like a list or dict) into a json-formatted string and writes it to a file.json.load()
: reads a json file and deserializes its content back into a python object.import json
# A python dictionary
contacts = {"name": "ada lovelace", "email": "ada@example.com"}
# Serialize and write the dictionary to a file
with open("contact.json", "w") as f:
json.dump(contacts, f, indent=4)
# Deserialize the file back into a python object
with open("contact.json", "r") as f:
data = json.load(f)
print(data["name"])
json
library to persist your application’s data.requests
. We will need to install it (pip install requests
).GET
, which is used to retrieve data from a specific url.200
means OK, while 404
means not found.GET
requestrequests
library is very straightforward.requests.get()
with the url of the api endpoint.response.status_code
to ensure the request was successful.requests
library can automatically parse for us using the response.json()
method.import requests
# The URL of a public API endpoint
url = "[https://pokeapi.co/api/v2/pokemon/pikachu](https://pokeapi.co/api/v2/pokemon/pikachu)"
# Make the GET request
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
# Parse the JSON response into a python dictionary
data = response.json()
print(f"Name: {data['name'].title()}")
print(f"Height: {data['height']} decimetres")
else:
print(f"Error: Received status code {response.status_code}")
labs/lab07/README.md
.IS4010: App Development with AI