0
# Response Types
1
2
Different types of mock responses including static responses, callback-based dynamic responses, and passthrough responses for selective mocking. Response types provide flexibility in how mock responses are generated and delivered.
3
4
## Capabilities
5
6
### Static Response
7
8
The standard Response class for fixed, predetermined responses. This is the most common response type used for straightforward mocking scenarios.
9
10
```python { .api }
11
class Response:
12
def __init__(
13
self,
14
method,
15
url,
16
body="",
17
json=None,
18
status=200,
19
headers=None,
20
stream=None,
21
content_type=None,
22
auto_calculate_content_length=False,
23
match_querystring=None,
24
match=(),
25
*,
26
passthrough=False
27
):
28
"""
29
Create a static mock response.
30
31
Parameters:
32
- method: HTTP method string (GET, POST, etc.)
33
- url: URL pattern as string or compiled regex Pattern
34
- body: Response body as string or bytes
35
- json: Response body as JSON object (mutually exclusive with body)
36
- status: HTTP status code (default: 200)
37
- headers: Response headers as dict or list of tuples
38
- stream: Deprecated, use stream parameter in request instead
39
- content_type: Content-Type header value (auto-detected if not specified)
40
- auto_calculate_content_length: Auto-add Content-Length header
41
- match_querystring: Deprecated, use query matchers instead
42
- match: List of matcher functions for advanced request matching
43
- passthrough: Whether to pass request to real server after matching
44
"""
45
```
46
47
**Usage Example:**
48
49
```python
50
# Direct Response object creation
51
response_obj = responses.Response(
52
method="GET",
53
url="http://api.example.com/data",
54
json={"message": "Hello, World!"},
55
status=200,
56
headers={"X-Custom-Header": "value"}
57
)
58
59
responses.add(response_obj)
60
61
# Or using the shortcut (more common)
62
responses.add(
63
responses.GET,
64
"http://api.example.com/data",
65
json={"message": "Hello, World!"},
66
status=200,
67
headers={"X-Custom-Header": "value"}
68
)
69
```
70
71
### Callback Response
72
73
Dynamic responses generated by callback functions. Useful when response content needs to be computed based on the request or when simulating complex server behavior.
74
75
```python { .api }
76
class CallbackResponse:
77
def __init__(
78
self,
79
method,
80
url,
81
callback,
82
stream=None,
83
content_type="text/plain",
84
match_querystring=None,
85
match=(),
86
*,
87
passthrough=False
88
):
89
"""
90
Create a callback-based dynamic response.
91
92
Parameters:
93
- method: HTTP method string
94
- url: URL pattern as string or regex Pattern
95
- callback: Function that generates response (see callback signature below)
96
- stream: Deprecated, use stream parameter in request instead
97
- content_type: Default content type for callback responses
98
- match_querystring: Deprecated, use query matchers instead
99
- match: List of matcher functions
100
- passthrough: Whether to pass request to real server after callback
101
"""
102
103
def add_callback(method, url, callback, match_querystring=False, content_type="text/plain", match=()):
104
"""
105
Convenience method to add a callback response.
106
107
Parameters:
108
- method: HTTP method string
109
- url: URL pattern
110
- callback: Response generation function
111
- match_querystring: Deprecated, use query matchers instead
112
- content_type: Default content type
113
- match: List of matcher functions
114
115
Returns:
116
BaseResponse object representing the callback response
117
"""
118
```
119
120
#### Callback Function Signature
121
122
```python { .api }
123
def callback_function(request):
124
"""
125
Generate dynamic response based on request.
126
127
Parameters:
128
- request: PreparedRequest object containing request details
129
130
Returns:
131
Tuple of (status_code, headers, body) or Exception to raise
132
133
The callback can:
134
- Return (int, dict, str/bytes) for normal responses
135
- Return (int, list, str/bytes) where list contains (name, value) header tuples
136
- Return an Exception to simulate request failures
137
- Access request.url, request.method, request.body, request.headers, etc.
138
"""
139
```
140
141
**Usage Example:**
142
143
```python
144
def dynamic_response_callback(request):
145
# Extract data from request
146
if "error" in request.url:
147
return (500, {}, "Server Error")
148
149
# Generate response based on request
150
request_data = json.loads(request.body) if request.body else {}
151
response_data = {
152
"received": request_data,
153
"method": request.method,
154
"url": request.url
155
}
156
157
return (200, {"Content-Type": "application/json"}, json.dumps(response_data))
158
159
@responses.activate
160
def test_callback_response():
161
responses.add_callback(
162
responses.POST,
163
"http://api.example.com/echo",
164
callback=dynamic_response_callback
165
)
166
167
response = requests.post(
168
"http://api.example.com/echo",
169
json={"message": "Hello"}
170
)
171
172
data = response.json()
173
assert data["received"]["message"] == "Hello"
174
assert data["method"] == "POST"
175
```
176
177
### Passthrough Response
178
179
Responses that allow requests to pass through to real servers. Useful for selective mocking where only some endpoints need to be mocked while others hit real services.
180
181
```python { .api }
182
class PassthroughResponse:
183
def __init__(self, *args, **kwargs):
184
"""
185
Create a response that passes requests through to real servers.
186
187
Inherits from BaseResponse with passthrough=True set automatically.
188
"""
189
190
def add_passthru(prefix):
191
"""
192
Register a URL prefix or regex pattern for passthrough.
193
194
Parameters:
195
- prefix: URL prefix string or compiled regex Pattern
196
197
All requests matching this prefix will be passed to real servers
198
instead of being intercepted by responses.
199
"""
200
```
201
202
**Usage Example:**
203
204
```python
205
@responses.activate
206
def test_selective_mocking():
207
# Mock specific endpoint
208
responses.add(
209
responses.GET,
210
"http://api.example.com/mock-me",
211
json={"mocked": True}
212
)
213
214
# Allow real requests to this domain
215
responses.add_passthru("http://httpbin.org")
216
217
# This hits the mock
218
mock_response = requests.get("http://api.example.com/mock-me")
219
assert mock_response.json()["mocked"] is True
220
221
# This hits the real server (if network available)
222
real_response = requests.get("http://httpbin.org/get")
223
# Would get real response from httpbin.org
224
```
225
226
### Base Response Class
227
228
The abstract base class that all response types inherit from. Generally not used directly but provides the interface for custom response types.
229
230
```python { .api }
231
class BaseResponse:
232
def __init__(
233
self,
234
method,
235
url,
236
match_querystring=None,
237
match=(),
238
*,
239
passthrough=False
240
):
241
"""
242
Base class for all response types.
243
244
Parameters:
245
- method: HTTP method string
246
- url: URL pattern
247
- match_querystring: Deprecated query string matching
248
- match: List of matcher functions
249
- passthrough: Whether to pass requests through to real server
250
"""
251
252
def matches(self, request):
253
"""
254
Check if this response matches the given request.
255
256
Parameters:
257
- request: PreparedRequest object
258
259
Returns:
260
Tuple of (bool, str) indicating match status and reason
261
"""
262
263
def get_response(self, request):
264
"""
265
Generate HTTPResponse object for the request.
266
267
Abstract method that must be implemented by subclasses.
268
269
Parameters:
270
- request: PreparedRequest object
271
272
Returns:
273
HTTPResponse object
274
"""
275
276
@property
277
def call_count(self):
278
"""Number of times this response has been used."""
279
280
@property
281
def calls(self):
282
"""CallList of requests that matched this response."""
283
```
284
285
## Response Properties and Methods
286
287
All response types share common properties for tracking usage and managing state.
288
289
### Call Tracking
290
291
```python { .api }
292
# Properties available on all response objects
293
@property
294
def call_count():
295
"""
296
Number of times this response has been matched and used.
297
298
Returns:
299
int: Count of matching requests
300
"""
301
302
@property
303
def calls():
304
"""
305
CallList containing all requests that matched this response.
306
307
Returns:
308
CallList: Collection of Call objects with request/response pairs
309
"""
310
```
311
312
### URL and Method Properties
313
314
```python { .api }
315
# Properties set during response creation
316
url: Union[str, Pattern] # URL pattern for matching
317
method: str # HTTP method
318
passthrough: bool # Whether to pass through to real server
319
```
320
321
**Usage Example:**
322
323
```python
324
@responses.activate
325
def test_response_tracking():
326
# Add a response
327
mock_response = responses.add(
328
responses.GET,
329
"http://api.example.com/test",
330
json={"test": True}
331
)
332
333
# Make requests
334
requests.get("http://api.example.com/test")
335
requests.get("http://api.example.com/test")
336
337
# Check response usage
338
assert mock_response.call_count == 2
339
assert len(mock_response.calls) == 2
340
341
# Access individual calls
342
first_call = mock_response.calls[0]
343
assert first_call.request.method == "GET"
344
assert first_call.request.url == "http://api.example.com/test"
345
```
346
347
## Error Handling in Callbacks
348
349
Callback responses can simulate various error conditions by returning exceptions or error status codes.
350
351
**Usage Example:**
352
353
```python
354
from requests.exceptions import ConnectionError, Timeout
355
356
def error_callback(request):
357
if "timeout" in request.url:
358
# Simulate timeout
359
raise Timeout("Request timed out")
360
elif "connection" in request.url:
361
# Simulate connection error
362
raise ConnectionError("Connection failed")
363
elif "server-error" in request.url:
364
# Return server error
365
return (500, {}, "Internal Server Error")
366
else:
367
return (200, {}, "OK")
368
369
@responses.activate
370
def test_error_handling():
371
responses.add_callback(
372
responses.GET,
373
re.compile(r"http://api\.example\.com/.*"),
374
callback=error_callback
375
)
376
377
# Test timeout simulation
378
with pytest.raises(Timeout):
379
requests.get("http://api.example.com/timeout")
380
381
# Test connection error simulation
382
with pytest.raises(ConnectionError):
383
requests.get("http://api.example.com/connection")
384
385
# Test server error
386
response = requests.get("http://api.example.com/server-error")
387
assert response.status_code == 500
388
```