# Saved Copies: Working Offline

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.

Journeyman · Python · REST API · Web Development · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Save a web API's answer to a JSON file with its date, and fall back to that saved copy when a request fails
- Pass the function that fetches data as a parameter, so a test can hand in a stand-in that never touches the network

## Key takeaways

- Saving each good answer to a JSON file, with the date it was saved, gives the program something to show when the network is down.
- When a request fails, the program loads the saved copy and says how old it is, instead of stopping.
- A function can be passed to another function like any value, without parentheses, so get_forecast(fetch) works with whatever fetch it's given.
- Tests hand in a stand-in fetch that returns saved data or raises an error, so they run the same way every time and never need the network.

*When a Request Fails* left the camping program with a friendly message: "Couldn't reach the weather service." Polite, but at the campground, with one bar of signal, you still don't know whether to pack the tarp. Yesterday's forecast would be far better than none. The same idea runs the apps on your phone that still show something on a plane, and it also solves a second problem: tests that call a real web API fail whenever the network does.

The example is still the Pine Ridge Campground forecast.

## Save each answer with its date

Each time a request works, write its answer to a JSON file, a **saved copy**, along with the day it was saved, so the program can say how old it is later. (A saved copy of slow or far-away data is often called a **cache**.)

```python
import json


def save_copy(forecast, path, today):
    with open(path, "w", encoding="utf-8") as file:
        json.dump({"saved_on": today, "forecast": forecast}, file, indent=2)


def load_copy(path):
    with open(path, encoding="utf-8") as file:
        saved = json.load(file)
    return saved["forecast"], saved["saved_on"]


forecast = {"properties": {"periods": [{"name": "Saturday", "temperature": 43}]}}
save_copy(forecast, "forecast-copy.json", "2026-11-17")

copy, saved_on = load_copy("forecast-copy.json")
print(copy["properties"]["periods"][0]["name"], "from the copy saved on", saved_on)
```

```text
Saturday from the copy saved on 2026-11-17
```

The file holds the forecast inside a dictionary with its date:

```json
{
  "saved_on": "2026-11-17",
  "forecast": {
    "properties": {
      "periods": [
        {
          "name": "Saturday",
          "temperature": 43
        }
      ]
    }
  }
}
```

In a real program, `today` is `str(date.today())`: `date.today()` from `datetime` is today's date, and `str()` turns it into text such as `2026-11-17`.

## Fall back when the request fails

Now put it together. `get_forecast` tries to fetch the forecast. If any request fails, it loads the saved copy; if it works, the `else` block saves the new answer:

```python
import json
from datetime import date

import requests

headers = {"User-Agent": "PythonCourseExample/1.0 (example@example.com)"}


def fetch_forecast():
    points = requests.get("https://api.weather.gov/points/44.8783,-122.6534", headers=headers, timeout=10)
    points.raise_for_status()
    response = requests.get(points.json()["properties"]["forecast"], headers=headers, timeout=10)
    response.raise_for_status()
    return response.json()


def get_forecast(fetch, path):
    try:
        forecast = fetch()
    except requests.exceptions.RequestException:
        with open(path, encoding="utf-8") as file:
            saved = json.load(file)
        return saved["forecast"], "saved copy from " + saved["saved_on"]
    else:
        with open(path, "w", encoding="utf-8") as file:
            json.dump({"saved_on": str(date.today()), "forecast": forecast}, file, indent=2)
        return forecast, "live"


def no_signal():
    raise requests.exceptions.ConnectionError("no signal at the campground")


forecast, source = get_forecast(fetch_forecast, "forecast-copy.json")
print(source)

forecast, source = get_forecast(no_signal, "forecast-copy.json")
print(source)
```

```text
live
saved copy from 2026-11-17
```

The first call reached the Weather Service and saved its answer; the second ran into "no signal" and got that copy back, with the day it was saved (yours shows the day you run it). `requests.exceptions.RequestException` catches every way a request can fail. The function returns two values, the forecast and where it came from, so the program can tell the user: *live*, or *saved copy from Tuesday*.

## Hand in the fetch

Look at `get_forecast(fetch, path)`. `fetch` is a parameter holding a function, and `fetch()` calls whatever function it holds. `get_forecast(fetch_forecast, ...)` passes the real one, without parentheses, so it's handed over rather than called. `no_signal` is a stand-in: a function with the same shape that fails on purpose. A function that takes another function as a value is a **higher-order function**.

That's what lets a test check the fallback without the network, and with a fixed date. With pytest, which *Fixtures and Temporary Files* uses for files like this one:

```python
import json

import requests

from camping import get_forecast


def no_signal():
    raise requests.exceptions.ConnectionError("no signal at the campground")


def test_no_signal_gives_the_saved_copy(tmp_path):
    path = tmp_path / "forecast-copy.json"
    path.write_text(json.dumps({"saved_on": "2026-11-20", "forecast": {"periods": []}}), encoding="utf-8")

    forecast, source = get_forecast(no_signal, path)

    assert forecast == {"periods": []}
    assert source == "saved copy from 2026-11-20"
```

It passes every time, offline or on, because no request is ever sent. A stand-in for the real thing in a test is a **test double**.

Handing in `fetch` has one more payoff. **httpx** is another package for web requests, with the same shape: `httpx.get(url, headers=headers, timeout=10)`, `.status_code`, `.json()` and `.raise_for_status()`. To move to it, only `fetch_forecast` changes; `get_forecast` and its tests stay as they are.

## Do it: fall back to the saved forecast

The camping program's offline mode needs one function. In the practice box there's no network and no requests package, so the stand-in fetches raise Python's own built-in `ConnectionError`, the error for a lost connection.

- `fetch`: a function with no parameters. It returns the forecast (here a small dictionary), or raises `ConnectionError` when there's no signal.
- `path`: the saved copy's file name.
- `today`: today's date as text, such as `"2026-11-21"`.

**Your job:** write `forecast_or_copy(fetch, path, today)`. It returns two values: the forecast and where it came from.

- When `fetch()` works, save `{"saved_on": today, "forecast": <the forecast>}` to `path` as JSON, and return the forecast and `"live"`.
- When `fetch()` raises `ConnectionError`, load the copy from `path`, and return its forecast and `"saved copy from "` followed by its `saved_on` date.

Worked through: `path` holds `{"saved_on": "2026-11-20", "forecast": {"Saturday": 43}}`, and `fetch` raises `ConnectionError`. So `forecast_or_copy(fetch, path, "2026-11-21")` returns `{"Saturday": 43}` and `"saved copy from 2026-11-20"`.

Practiced live on the lesson page: write the Python right there and check it.

## Check yourself

2 questions to try on the lesson page.

## So what

A saved copy with its date keeps a program useful when the network isn't, and a fetch handed in as a parameter lets its tests run anywhere, in a second, with the same answer every time.

## Key terms

- [Cache](https://www.ask-codey.com/glossary/cache-software-development)
- [Higher-Order Function](https://www.ask-codey.com/glossary/higher-order-function)
- [Test Double](https://www.ask-codey.com/glossary/test-double)
- [httpx](https://www.ask-codey.com/glossary/httpx)

## Related

- [When a Request Fails](https://www.ask-codey.com/lessons/python-requests-when-it-fails)
- [JSON Files: Saving Your Data](https://www.ask-codey.com/lessons/python-files-json)
- [Fixtures and Temporary Files](https://www.ask-codey.com/lessons/python-testing-fixtures-and-tmp-path)

Source: https://www.ask-codey.com/lessons/python-web-apis-saved-copies
