FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Record a client's API once and keep CI green when their sandbox dies

VCR.py and pytest-recording replay saved responses with no network at all, provided tokens and customer data are scrubbed before the cassette is committed.

ShareLinkedInFacebookX

In brief

  • Record real requests to a cassette once; after that, tests replay the responses with no network and no token.
  • Filter headers, query strings and response bodies before committing, because a cassette is a plain text file anyone can read.
  • In CI, leave pytest-recording in its default none mode and add --block-network so any unexpected request fails.
Table of VCR.py's five record modes: once records only when no cassette exists, used for the first recording; new_episodes replays and appends new recordings, used when adding an endpoint; none replays but never records, highlighted, used for CI and day-to-day runs; all always records and never replays, rarely used; rewrite re-records from scratch, used when the client changes its schema.
Only none mode never records. Any request missing from the cassette turns the test red, so CI cannot quietly call the client's real API. Source: VCR.py and pytest-recording documentation, as covered in the article.

In the second week at a client site, their API sandbox starts returning 503 errors every afternoon. Each time, CI goes red, even though not a single line of your code has changed.

The cleanest fix is to call the real API exactly once, record every request and response, and let every later run use that recording. VCR.py does precisely this. According to the library’s documentation, the first time a test runs it records HTTP requests to a YAML cassette file, and from then on the test reads from that file.

This guide builds a complete example: a client for a hypothetical customer orders API, pytest tests that record once, sensitive data masked before commit, and CI that runs entirely offline. It is the kind of thing an integration engagement needs in its first week.

What do you need before starting?

You need Python, pytest, the requests library and two packages: vcrpy and pytest-recording. The second is a pytest plugin built on VCR.py that lets you mark tests with pytest.mark.vcr instead of wrapping each block of code yourself.

pip install pytest requests vcrpy pytest-recording

The api.example-customer.com endpoint below is a placeholder. On a real engagement, swap in the client’s sandbox and a token they issue you.

Step 1: write a thin client, separate from the tests

Keep every HTTP call in its own module. Tests call this function exactly the way production code does.

# orders_client.py
import requests

BASE_URL = "https://api.example-customer.com"

def list_orders(token, status="open"):
    resp = requests.get(
        f"{BASE_URL}/v1/orders",
        params={"status": status},
        headers={"Authorization": f"Bearer {token}"},
        timeout=10,
    )
    resp.raise_for_status()
    return resp.json()["orders"]

Check: run this function once from a terminal with a real token to confirm the API returns a list of orders. If this step fails, record nothing, because the cassette will faithfully store the error too.

Step 2: record a first cassette with plain VCR.py

Before reaching for the plugin, see how VCR.py works at its lowest level.

# test_raw.py
import os
import vcr
from orders_client import list_orders

def test_list_orders_raw():
    with vcr.use_cassette("fixtures/vcr_cassettes/orders.yaml"):
        orders = list_orders(token=os.environ["CUSTOMER_TOKEN"])
    assert isinstance(orders, list)

VCR.py’s default record mode is once: if the cassette file does not exist, it records new interactions; if it does, it only replays. Run the test twice and the second run is noticeably faster, because it no longer goes over the network.

Now open orders.yaml. The Authorization header and its token sit there verbatim, alongside the full contents of the client’s orders. Note down a few real email addresses and the email domain you see; they will be needed for checking later. Do not commit this file. Delete it and move on to step 3.

Step 3: switch to pytest-recording and filter secrets

With pytest-recording, recording configuration lives in the vcr_config fixture. That is also where you declare what must never reach a cassette.

# conftest.py
import pytest
from scrub import scrub_response

@pytest.fixture(scope="module")
def vcr_config():
    return {
        "filter_headers": ["authorization"],
        "filter_query_parameters": ["api_key"],
        "before_record_response": scrub_response,
    }

filter_headers takes a list of headers to drop from the recording, and filter_query_parameters does the same for the query string. The second matters when a client passes keys in the URL, as in ?api_key=..., which older systems still do.

# test_orders.py
import os
import pytest
from orders_client import list_orders

@pytest.mark.vcr
def test_list_open_orders():
    token = os.environ.get("CUSTOMER_TOKEN", "dummy")
    orders = list_orders(token=token)
    assert all(o["status"] == "open" for o in orders)

Note the "dummy" value: on replay, the test needs no real token. CI holds no secrets at all, which is exactly what you want.

Step 4: mask customer data in the response

Filtering headers solves only half the problem. The response body still holds end customers’ emails, names and addresses. The before_record_response hook lets you modify a response before it is recorded, or return None to drop that request-response pair from the cassette entirely.

# scrub.py
import json

def scrub_response(response):
    body = response["body"]["string"]
    try:
        data = json.loads(body)
    except ValueError:
        return response
    for order in data.get("orders", []):
        order["customer_email"] = "redacted@example.com"
    response["body"]["string"] = json.dumps(data).encode()
    return response

This is simplified. It assumes the body is uncompressed JSON and that the field to mask is named customer_email. With a real API, ask the client which fields hold personal data instead of guessing.

Now record again. pytest-recording runs in none mode by default to avoid unintended network calls, so you have to switch recording on deliberately. Since the plugin’s recording settings live in vcr_config, the easiest approach to keep track of is to set once mode temporarily in that fixture on your machine, run the test once with a real token, then remove that line before committing.

CUSTOMER_TOKEN=xxx pytest test_orders.py

Check: open the newly generated cassette and search for Bearer, for the token, then for the client’s real email domain and the addresses you noted in step 2. Do not search for the @ character, because the replacement value redacted@example.com contains one too. Commit only when nothing turns up.

Step 5: lock CI into offline mode

In CI, the record mode needs no extra configuration, because none is already the default. This mode raises an error on any new request, so if someone adds an API call and forgets to record a cassette, the test fails immediately instead of quietly reaching out to the network.

pytest --block-network

The --block-network flag blocks all network access while tests run, including tests without the vcr marker. It is a second layer of protection, catching network calls that bypass VCR altogether.

When the client’s API changes, how do you re-record?

This is where many people break their cassettes. Each record mode serves a different situation, and the wrong choice can leave CI accidentally calling the real network.

Mode Behavior Use when
once Records only when no cassette exists First recording on your machine
new_episodes Replays existing interactions, records new ones Adding an endpoint to an existing test
none Raises an error on any new request CI and every routine run
all Never replays, always records Rarely; almost never in CI
rewrite Re-records the cassette from scratch (pytest-recording) The client changed its schema and you need a clean recording

When the client reports a schema change, run rewrite on your own machine, open the file and check for secrets as in step 4, then commit in a separate pull request. The cassette diff shows exactly what changed in the API.

Common mistakes

The first concerns how requests are matched. By default VCR.py matches on method, scheme, host, port, path and query, which means the body is ignored. Two POST /v1/orders calls with different bodies can be treated as one, and your test receives the wrong response.

When you need to test several POSTs to the same URL, the safe approach is to give each call its own cassette file with vcr.use_cassette, as in step 2.

The second is adding filters after a cassette has already been committed. Filters apply only to the next recording; they cannot remove a token that is already in git history. If that happens, tell the client so they can revoke the token. Fixing the file alone is not enough.

The third is forgetting to remove the record mode from vcr_config after a debugging session, worst of all leaving it on all. Every run then calls the real API, CI starts needing a token, and you are back where you started.

How does this skill play out at a client site?

On a real engagement, the cassette doubles as documentation. When the client asks what your system sends to their API, you can open the YAML file and show them the masked requests. That answer is more convincing than any architecture diagram.

It also helps with handover. An engineer on the client’s side clones the repo, runs pytest --block-network and sees green tests without requesting sandbox access. You leave the site; the test suite stays and keeps running.

On the career side: when reading FDE job descriptions, look for phrases such as “integrate with customer systems” or “own integrations end to end”. On a CV, rather than writing “wrote tests”, describe the outcome, for example “built an offline integration test suite for a client API, recorded with VCR.py, with credentials and personal data filtered and CI needing no network”.

In an interview, if you can explain clearly why CI should run in none mode, the interviewer will see that you understand the risk as well as the library.

The next time the client’s sandbox returns a 503, your CI will not notice. The only time you need to call the real API again is the day the client announces a schema change.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
5 sources
Read next on the roadmap · Stage 1: FoundationsOne bad record, and Promise.all leaves client data in a blind spotA rejection does not cancel the writes still in flight, so only per-record results from allSettled show what landed and whether a rerun is safe.