Testing code that calls an external HTTP API with the responses library

Backend Live Coding November 13, 2026 python

In unit tests I never go out to the internet.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# ======================================================================
# Q: How do you test code that calls an external HTTP API?
#
# In unit tests I never go out to the internet. With the responses library (for
# requests) or respx (for httpx) I define what the "API" returns and I also test
# the bad scenarios: 429, 500, timeout, malformed JSON.
# For integration: a few tests against a real provider sandbox, in a separate CI
# job (not on every commit), or recorded responses with VCR.py / pytest-
# recording.
# ======================================================================

import responses

@responses.activate
def test_forecast_raises_rate_limited():
    responses.get('https://api.example.com/v2/forecast',
                  status=429, headers={'Retry-After': '30'})
    with pytest.raises(RateLimited) as exc:
        WeatherClient('key').forecast('Athens')
    assert exc.value.retry_after == 30

@responses.activate
def test_forecast_timeout_is_set():
    responses.get('https://api.example.com/v2/forecast',
                  body=requests.exceptions.ConnectTimeout())
    with pytest.raises(requests.exceptions.ConnectTimeout):
        WeatherClient('key').forecast('Athens')