VCR.py: Record and Replay HTTP Interactions in Python Tests

VCR.py: Record and Replay HTTP Interactions in Python Tests

Tests that make real HTTP calls are slow, flaky, and break the moment a third-party API is down. Mocking those calls by hand is tedious and produces mocks that drift from the real API's behavior. VCR.py solves this by recording real HTTP interactions the first time your test runs, then replaying those recordings in every subsequent run — no network required, no manual mock writing.

The name comes from VHS tapes: record once, play back indefinitely.

How VCR.py Works

VCR.py intercepts Python's HTTP libraries at the socket level. When a test runs for the first time in record mode, VCR.py lets the HTTP request go through to the real server, records the full request and response, and saves it to a YAML file called a cassette. On subsequent runs, VCR.py intercepts the same request pattern, finds the matching cassette entry, and returns the recorded response without touching the network.

The cassette file is a plain YAML file you commit to version control alongside your test code. It documents exactly what the API returned at the time you recorded the test.

Installation

pip install vcrpy

VCR.py integrates with unittest, pytest, and plain Python code. No additional plugins are required for basic usage.

Basic Usage

The simplest way to use VCR.py is as a decorator:

import vcr
import requests

@vcr.use_cassette('cassettes/github_user.yaml')
def test_get_github_user():
    response = requests.get('https://api.github.com/users/octocat')
    assert response.status_code == 200
    data = response.json()
    assert data['login'] == 'octocat'

The first time this test runs, VCR.py makes a real request to the GitHub API and saves the result to cassettes/github_user.yaml. Every subsequent run replays the saved cassette — the test completes in milliseconds with no network activity.

The cassette file looks like this:

interactions:
- request:
    body: null
    headers:
      Accept:
      - '*/*'
      User-Agent:
      - python-requests/2.28.0
    method: GET
    uri: https://api.github.com/users/octocat
  response:
    body:
      string: '{"login":"octocat","id":583231,"name":"The Octocat",...}'
    headers:
      Content-Type:
      - application/json; charset=utf-8
    status:
      code: 200
      message: OK
version: 1

Using VCR.py with pytest

VCR.py provides a pytest plugin with a vcr fixture:

# conftest.py
import pytest
import vcr

@pytest.fixture(scope="module")
def vcr_config():
    return {
        "cassette_library_dir": "cassettes",
        "record_mode": "none",  # Never make real requests in CI
    }
# test_api.py
def test_fetch_weather(vcr):
    with vcr.use_cassette('weather_london.yaml'):
        response = requests.get(
            'https://api.openweathermap.org/data/2.5/weather',
            params={'q': 'London', 'appid': 'fake-key-for-test'}
        )
        assert response.json()['name'] == 'London'

Setting record_mode: "none" in CI ensures tests never accidentally make real network calls — if a cassette is missing, the test fails immediately with a clear error rather than hitting the network.

Record Modes

VCR.py offers four record modes that control when real HTTP calls are made:

@vcr.use_cassette('cassette.yaml', record_mode='none')
# Never record. Fail if cassette missing or request not in cassette.

@vcr.use_cassette('cassette.yaml', record_mode='new_episodes')
# Record new requests not in the cassette. Replay existing ones.

@vcr.use_cassette('cassette.yaml', record_mode='all')
# Always record. Overwrite cassette every run.

@vcr.use_cassette('cassette.yaml', record_mode='once')
# Record on first run (cassette doesn't exist), replay forever after.
# Default mode.

The recommended workflow: use once during development (record when you need to, replay always), and none in CI to enforce that all cassettes are committed.

Filtering Sensitive Data

API keys, tokens, and other credentials appear in recorded HTTP requests and responses. Committing these to version control is a security problem. VCR.py provides request and response filters:

@vcr.use_cassette(
    'cassettes/api_call.yaml',
    filter_headers=[('Authorization', 'REDACTED')],
    filter_query_parameters=['api_key', 'token'],
    filter_post_data_parameters=['password', 'secret']
)
def test_authenticated_request():
    response = requests.get(
        'https://api.example.com/data',
        headers={'Authorization': 'Bearer real-token-here'},
        params={'api_key': 'real-key-here'}
    )
    assert response.status_code == 200

The cassette stores REDACTED instead of the real token. When replaying, VCR.py doesn't care what value is in the outgoing request's Authorization header — it replays the recorded response regardless.

Matching Strategies

By default, VCR.py matches requests by URI and HTTP method. You can customize what constitutes a "matching" request:

@vcr.use_cassette(
    'cassettes/search.yaml',
    match_on=['method', 'scheme', 'host', 'path', 'query']
)
def test_search():
    # Query parameters are part of the match
    response = requests.get(
        'https://api.example.com/search',
        params={'q': 'python testing', 'page': '1'}
    )

Available matchers: method, scheme, host, port, path, query, headers, body. For POST requests with JSON bodies, you often want to include body in the match to distinguish between different requests to the same endpoint.

Handling Dynamic Requests

Some APIs return different data based on the current time, user-specific state, or randomized IDs. VCR.py will record whatever the API returned at record time, which may not be valid input for tests that assert on specific current-time values.

The solution is to use request matchers that ignore the varying parts:

import vcr

def custom_matcher(r1, r2):
    # Ignore timestamp parameters when matching
    return r1.path == r2.path and r1.method == r2.method

my_vcr = vcr.VCR()
my_vcr.register_matcher('path_method_only', custom_matcher)

@my_vcr.use_cassette('cassette.yaml', match_on=['path_method_only'])
def test_with_timestamps():
    response = requests.get(
        'https://api.example.com/events',
        params={'since': int(time.time()) - 3600}
    )

When to Use VCR.py vs Other Approaches

Use VCR.py when:

  • Testing code that calls third-party APIs you don't control
  • You want tests to serve as documentation of actual API responses
  • The API returns complex, realistic data that's tedious to construct by hand
  • You want offline-capable tests without maintaining manual mocks

Use manual mocks when:

  • You need to test specific error conditions the real API rarely returns
  • The API's response structure is simple enough that hand-written fixtures are clearer
  • You need to simulate network errors or timeouts

Use integration tests against a real API when:

  • You need to verify the actual API contract, not just your handling of it
  • Running a small, infrequent contract verification suite is acceptable

VCR.py occupies the middle ground — real API data, synthetic test execution. It's most valuable for teams with many external API integrations who want fast, reliable test runs without the maintenance burden of manual mock objects.

Beyond VCR.py

VCR.py has equivalents in other languages: Ruby has vcr gem, JavaScript/Node has Polly.js and nock-record, Go has go-vcr. The concept is the same across all of them: record once, replay forever, keep cassettes in version control.

For production monitoring of the same APIs your VCR.py tests cover, HelpMeTest provides continuous health checks that run against live endpoints — detecting when an external API changes behavior in ways your recorded cassettes would never catch.

Read more

Start now free