computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

🌐

🎓

⏱ 30 min

Free

JSON & APIs

Learn how apps share data with JSON and how APIs let programs talk to each other.

🎯 What you will learn

  • Read and write JSON with the json module
  • Understand what an API is
  • Handle data you get from the internet safely

👋 Let’s get started!

When a weather app shows the forecast, it asked a weather server through an API and got data back as JSON 🌐. JSON looks like Python dictionaries and lists — so you already speak it!

🪜 Step by step

1. 📄 JSON

JSON is text that stores data. json.loads() turns it into Python; json.dumps() turns Python into JSON.

import json
text = '{"city": "Atlanta", "temp": 72}'
data = json.loads(text)
print(data["city"])
2. 🔌 APIs

An API is a menu of requests a server understands. You send a request to a URL and get JSON back. With the requests package: requests.get(url).json()

# Outside the browser:
# import requests
# r = requests.get("https://api.example.com/weather?city=Atlanta")
# data = r.json()
3. 🛡️ Be safe with data

Never paste API keys into public code, check for missing fields, and don’t trust data blindly.

temp = data.get("temp", "unknown")
print("Temperature:", temp)

🧪 Try it!

Change the code and press ▶ Run to see what happens. You can’t break anything!

Parse a pretend API response

import json

response = '''
{"planet": "Mars", "moons": ["Phobos", "Deimos"], "day_hours": 24.6}
'''

data = json.loads(response)
print(f"{data['planet']} has {len(data['moons'])} moons:")
for moon in data["moons"]:
    print(" 🌑", moon)
print("A day lasts", data["day_hours"], "hours")

Save settings as JSON

import json
settings = {"theme": "dark", "volume": 7}
text = json.dumps(settings)
print(text)

📖 Key words

Tap a card to flip it over!

JSON
A text format for sharing data 📄
API
A way for programs to talk to each other 🔌
Request
A message asking a server for data 📨
API key
A secret password for an API 🔑

🏆 Challenge

Parse the JSON and print the name of the oldest student.

Challenge

import json
text = '[{"name": "Sam", "age": 14}, {"name": "Lin", "age": 16}, {"name": "Ola", "age": 15}]'

Knowledge Check Quiz

  1. What does json.loads() do?
  2. What is an API?
  3. Where should API keys go?
← Previous lesson
Next lesson →