Intermediate level · Module 4: Working with Web APIs · Lesson 3 of 3
Reliable API Clients for Low-Bandwidth Conditions
Make API-based programs useful even when the connection is slow or drops, by retrying sensibly and caching results.
In this lesson you will
- Handle connection errors and retries
- Cache responses to a file and fall back to cached data
Key concepts
ConnectionErrorretry with backofflocal cachedata freshness
The lesson
Internet access in South Sudan can be slow, expensive or temporarily unavailable. A reliable client keeps working: it saves each successful response to a local cache and falls back to the cache when the network fails.
Store the time of each fetch alongside the data so the program can tell the user how old the cached figures are. Only request new data when the cache is older than you need — once a day is enough for exchange rates, and it saves data bundles.
Retry a failed request a small number of times with a pause between attempts, then fall back to the cache. Never retry in a tight loop: it wastes bandwidth and may get your access blocked.
Step by step
- Save the JSON response and a timestamp to rates_cache.json.
- On start-up, use the cache if it is less than 24 hours old.
- Otherwise request new data, with up to three retries.
- If all retries fail, use the cache and print its age.
Practice activity
Extend the exchange-rate script to save each successful response to rates_cache.json and use the cached rates, clearly labelled with their date, when offline.
Expected result: The script works offline using cached data and says how old it is.
Check your understanding
-
What should a program tell the user when it shows cached data?
Show answer
That the data is cached and when it was last updated.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.