Calling a web API
Not met yet
A web API is a program on someone else's computer that answers questions asked as URLs. The question goes in the query string after the ?, and urlencode writes it for you, punctuation and all. The answer usually comes back as JSON, which json.load turns into dictionaries and lists. Three things go wrong, and each wants its own answer: the request never gets through (an OSError), the service has nothing for you (an empty answer, not an error), or the answer is missing a field you need (a KeyError). Keep the asking in one function and let everything else work on data that has already arrived, so it can be checked with a saved reply and no internet.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks a URL carries spaces and punctuation exactly as typed, so a query string needs no encoding.
- Thinks every value must already be text before urlencode will put it in a query string.
- Thinks a web service that finds nothing raises an error, when it sends back an answer with nothing in it.
- Thinks the JSON a service sends is still one long string after json.load, so keys can't be looked up.