Calling Web APIs
Bring live data into your programs. You'll learn what a web API is and how its addresses, status codes and JSON answers work, fetch a real weather forecast with the requests package, handle the times it fails, and keep a saved copy so your program still works offline. Then you'll build a forecast and packing list for a weekend camping trip.
Updated
Web APIs
- What a Web API Is (Apprentice): A web API is a program on a server that answers requests sent to its web addresses, and every request and answer has the same parts, a URL with a domain, a path and a query string, a method, a status code and, usually, JSON that Python reads into dictionaries and lists.
Calling APIs with requests
- Getting Data with requests (Apprentice): The requests package sends a program's request to a web API with requests.get, a User-Agent header and a timeout, and gives back a response whose status_code says how it went and whose json() turns the answer into dictionaries and lists, which for the National Weather Service takes two steps, the point's forecast address and then the forecast.
- When a Request Fails (Journeyman): A web request can fail three ways, no connection, an error status code or no answer in time, and a program handles each with requests' own exceptions, raise_for_status() turning a 4xx or 5xx answer into an HTTPError, a friendly message instead of a traceback, and one more try when the network may come back.
- Saved Copies: Working Offline (Journeyman): A program that calls a web API can save each answer to a JSON file with the date it was saved, fall back to that copy when a request fails, and take the function that fetches as a parameter, so tests can hand in a stand-in and never touch the network.
Exercise: Camping Trip Forecast
- Exercise: Camping Trip Forecast (Journeyman): Write the four functions behind a camping trip's forecast, finding the forecast's address in the Weather Service's answer, picking out the weekend, planning the packing and falling back to a saved copy, and let pytest's tests check them offline with saved answers and stand-in fetches.
Up Next: Where Python Goes Next
- Up Next: Where Python Goes Next (Journeyman): Look back at what Module 5 taught, sorting and moving files, command-line options, running on a schedule and fetching live data with a saved copy, try a weekly report of your own that uses all of it, and see the three directions Module 6 lets you try, data analysis, machine learning and building web APIs.