Exercises: Working with APIs & JSON
starter.py below, then run
python3 starter.py from inside the folder you saved it
in. Every "response" in these exercises is a hardcoded JSON string —
nothing here needs an internet connection.
1 json.loads() on a mocked response
Parse mock_response_text (a JSON string standing in for response.text) with json.loads() into a dict named weather. Print weather["city"] and weather["temp_f"].
2 json.dumps() with indent=
Build a dict named profile with keys "username" ("cleo") and "followers" (1204). Convert it to a pretty-printed JSON string named pretty using json.dumps(profile, indent=2), and print it.
3 Navigating nested JSON
Parse mock_nested_text into data. Print data["repo"], then loop over data["contributors"] (a list of dicts), printing each contributor's name and commit count.
4 Checking a status code
Given status_code = 404, print "Success!" if it's 200, otherwise print a message including the actual status code.
5 .get() with a default
Read quote_data's "author" key with .get() and a default of "Unknown" (the dict deliberately has no "author" key), then print the quote with its author.
6 Building a query string
Build a query string from the params dict in the form "key1=value1&key2=value2", and print the full URL it would produce.
🐞 Task 7 — Debug the Code
This is supposed to parse mock_text and print its "city" key, but it forgot to actually call json.loads() first, so it's indexing into a plain string instead of a dict, which raises a TypeError. Find and fix it.
mock_text = '{"city": "Seattle", "temp_f": 61}'
data = mock_text
print(data["city"])
🐞 Task 8 — Debug the Code
This is supposed to safely handle a response that's missing the "condition" key using .get() with a default, but it used square-bracket indexing instead, which raises a KeyError since "condition" genuinely isn't present. Find and fix it.
weather_data = {"city": "Miami", "temp_f": 90}
condition = weather_data["condition"]
print(f"Condition: {condition}")