×

python · level 2 · unit 6 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A goes out as a , and the reply comes back as JSON.

Apps get live data from an : they send a request to a URL and get a reply, usually JSON. The question rides in the after the ?, as key=value pairs joined by &.

urlencode from urllib.parse builds a query string from a dictionary, turning spaces and symbols into safe codes. Then json.loads parses the reply.

Gwecode lessons have no internet, so the replies here are pretend ones, written as strings. Real replies look exactly the same.

import json
from urllib.parse import urlencode
query = urlencode({"city": "St Ives", "days": 2})
url = "https://api.example.com/weather?" + query
print(url)
reply = '{"city": "St Ives", "forecast": ["sun", "rain"]}'
data = json.loads(reply)
print(f"Tomorrow in {data['city']}: {data['forecast'][0]}")

urlencode turns a space into + and an & into %26, so your question cannot be misread.