python · level 2 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A pizza order with a symbol in it. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
from urllib.parse import urlencode
print(urlencode({"topping": "ham & pineapple", "size": "L"}))
your turn
Your turn. Search a pretend film API.
Type a film to search for. The pretend API always sends the same reply, so fill in the function that parses JSON and the key that holds the list of films.
fix it
The weather URL has a gap in it. Can you fix it?
- Look at the printed URL. Is there anything in it a web address must never contain?
- A URL cannot hold a space. The code imports
urlencodeon line 1 but never uses it. - Change line 3 to url = "https://api.example.com/weather?" + urlencode({"city": city}), then run.
nailed it
you talked to the web. :D
- A request is a URL, with the question in its query string.
urlencodebuilds a safe query string from a dictionary.- Replies are usually JSON, so parse them with
json.loads.
new words in your collection
- URL
- API
- request
- query string
This lesson isn’t saved. A free account remembers every lesson you finish.