0
# Agent and Request Inspection
1
2
HTTP request capture and inspection functionality for debugging and replaying requests through ngrok tunnels with full request/response details.
3
4
## Capabilities
5
6
### Agent Status Information
7
8
Container for ngrok agent status and session information.
9
10
```python { .api }
11
class NgrokAgent:
12
"""
13
Container for ngrok agent information.
14
"""
15
data: dict # Original agent data from ngrok
16
status: str # Status of the agent
17
agent_version: str # Version of the ngrok agent
18
session: dict # Session details for the agent
19
uri: str # URI of the agent
20
```
21
22
### Request Capture Information
23
24
Container for captured HTTP requests through ngrok tunnels.
25
26
```python { .api }
27
class CapturedRequest:
28
"""
29
Container for captured HTTP request from ngrok tunnel.
30
"""
31
data: dict # Original request data from ngrok
32
id: str # ID of the captured request
33
uri: str # URI of the captured request
34
tunnel_name: str # Name of tunnel that captured the request
35
remote_addr: str # Remote address of the request
36
start: str # Start time of the request
37
duration: int # Duration of the request in milliseconds
38
request: dict # Request details (method, headers, body, etc.)
39
response: dict # Response details (status, headers, body, etc.)
40
```
41
42
### Getting Agent Status
43
44
Retrieve current ngrok agent status and session information.
45
46
```python { .api }
47
def get_agent_status(pyngrok_config=None):
48
"""
49
Get the ngrok agent status.
50
51
Parameters:
52
- pyngrok_config (PyngrokConfig, optional): Configuration override
53
54
Returns:
55
NgrokAgent: The agent status information
56
"""
57
```
58
59
**Usage Examples:**
60
61
```python
62
from pyngrok import agent, ngrok
63
64
# Start a tunnel first to have an active agent
65
tunnel = ngrok.connect("8000")
66
67
# Get agent status
68
agent_status = agent.get_agent_status()
69
print(f"Agent status: {agent_status.status}")
70
print(f"Agent version: {agent_status.agent_version}")
71
print(f"Agent URI: {agent_status.uri}")
72
73
# Access raw agent data
74
print(f"Session info: {agent_status.session}")
75
```
76
77
### Listing Captured Requests
78
79
Retrieve HTTP requests that have been captured by ngrok tunnels.
80
81
```python { .api }
82
def get_requests(tunnel_name=None, pyngrok_config=None):
83
"""
84
Get list of requests made to tunnels.
85
86
Parameters:
87
- tunnel_name (str, optional): Filter by specific tunnel name
88
- pyngrok_config (PyngrokConfig, optional): Configuration override
89
90
Returns:
91
list[CapturedRequest]: List of captured request objects
92
"""
93
```
94
95
**Usage Examples:**
96
97
```python
98
from pyngrok import agent, ngrok
99
import requests
100
import time
101
102
# Create a tunnel
103
tunnel = ngrok.connect("8000")
104
print(f"Send requests to: {tunnel.public_url}")
105
106
# Make some HTTP requests to generate captured data
107
# (In real usage, external services would make these requests)
108
time.sleep(1) # Allow tunnel to be ready
109
110
# Get all captured requests
111
all_requests = agent.get_requests()
112
print(f"Total requests captured: {len(all_requests)}")
113
114
for req in all_requests[-5:]: # Last 5 requests
115
print(f"Request ID: {req.id}")
116
print(f"From: {req.remote_addr}")
117
print(f"Method: {req.request.get('method', 'Unknown')}")
118
print(f"Path: {req.request.get('uri', 'Unknown')}")
119
print(f"Duration: {req.duration}ms")
120
print("---")
121
122
# Get requests for specific tunnel
123
tunnel_requests = agent.get_requests(tunnel_name=tunnel.name)
124
print(f"Requests for {tunnel.name}: {len(tunnel_requests)}")
125
```
126
127
### Getting Specific Request
128
129
Retrieve detailed information about a specific captured request.
130
131
```python { .api }
132
def get_request(request_id, pyngrok_config=None):
133
"""
134
Get details for a specific captured request.
135
136
Parameters:
137
- request_id (str): ID of the request to fetch
138
- pyngrok_config (PyngrokConfig, optional): Configuration override
139
140
Returns:
141
CapturedRequest: The detailed request information
142
"""
143
```
144
145
**Usage Examples:**
146
147
```python
148
from pyngrok import agent, ngrok
149
150
# Create tunnel and get some requests
151
tunnel = ngrok.connect("8000")
152
requests_list = agent.get_requests()
153
154
if requests_list:
155
# Get detailed info for first request
156
request_id = requests_list[0].id
157
detailed_request = agent.get_request(request_id)
158
159
print(f"Request ID: {detailed_request.id}")
160
print(f"Tunnel: {detailed_request.tunnel_name}")
161
print(f"Start time: {detailed_request.start}")
162
print(f"Duration: {detailed_request.duration}ms")
163
164
# Access detailed request information
165
request_info = detailed_request.request
166
print(f"Method: {request_info.get('method')}")
167
print(f"URI: {request_info.get('uri')}")
168
print(f"Headers: {request_info.get('headers', {})}")
169
170
# Access response information
171
response_info = detailed_request.response
172
if response_info:
173
print(f"Status: {response_info.get('status')}")
174
print(f"Response headers: {response_info.get('headers', {})}")
175
```
176
177
### Replaying Requests
178
179
Replay captured requests through ngrok tunnels for testing and debugging.
180
181
```python { .api }
182
def replay_request(request_id, tunnel_name=None, pyngrok_config=None):
183
"""
184
Replay a captured request through its original or different tunnel.
185
186
Parameters:
187
- request_id (str): ID of the request to replay
188
- tunnel_name (str, optional): Name of tunnel to replay through
189
- pyngrok_config (PyngrokConfig, optional): Configuration override
190
"""
191
```
192
193
**Usage Examples:**
194
195
```python
196
from pyngrok import agent, ngrok
197
198
# Create tunnels
199
tunnel1 = ngrok.connect("8000")
200
tunnel2 = ngrok.connect("9000")
201
202
# Get captured requests
203
requests_list = agent.get_requests()
204
205
if requests_list:
206
request_id = requests_list[0].id
207
208
# Replay through original tunnel
209
print(f"Replaying request {request_id} through original tunnel")
210
agent.replay_request(request_id)
211
212
# Replay through different tunnel
213
print(f"Replaying request {request_id} through {tunnel2.name}")
214
agent.replay_request(request_id, tunnel_name=tunnel2.name)
215
```
216
217
### Clearing Request History
218
219
Remove captured request history from ngrok.
220
221
```python { .api }
222
def delete_requests(pyngrok_config=None):
223
"""
224
Delete all captured request history.
225
226
Parameters:
227
- pyngrok_config (PyngrokConfig, optional): Configuration override
228
"""
229
```
230
231
**Usage Examples:**
232
233
```python
234
from pyngrok import agent, ngrok
235
236
# Create tunnel and generate some requests
237
tunnel = ngrok.connect("8000")
238
239
# Check current request count
240
requests_before = agent.get_requests()
241
print(f"Requests before cleanup: {len(requests_before)}")
242
243
# Clear all request history
244
agent.delete_requests()
245
246
# Verify cleanup
247
requests_after = agent.get_requests()
248
print(f"Requests after cleanup: {len(requests_after)}") # Should be 0
249
```
250
251
### Advanced Request Analysis
252
253
Examples of analyzing captured request data for debugging and monitoring.
254
255
**Usage Examples:**
256
257
```python
258
from pyngrok import agent, ngrok
259
from collections import Counter
260
import json
261
262
# Create tunnel for analysis
263
tunnel = ngrok.connect("8000")
264
print(f"Analyze requests at: {tunnel.public_url}")
265
266
# Wait for some requests to be made...
267
# Then analyze the captured data
268
269
requests_list = agent.get_requests()
270
271
# Analyze request patterns
272
if requests_list:
273
# Count requests by method
274
methods = [req.request.get('method', 'Unknown') for req in requests_list]
275
method_counts = Counter(methods)
276
print(f"Request methods: {dict(method_counts)}")
277
278
# Count requests by path
279
paths = [req.request.get('uri', 'Unknown') for req in requests_list]
280
path_counts = Counter(paths)
281
print(f"Popular paths: {dict(path_counts)}")
282
283
# Analyze response times
284
durations = [req.duration for req in requests_list if req.duration]
285
if durations:
286
avg_duration = sum(durations) / len(durations)
287
max_duration = max(durations)
288
print(f"Average response time: {avg_duration:.2f}ms")
289
print(f"Max response time: {max_duration}ms")
290
291
# Find errors
292
error_requests = []
293
for req in requests_list:
294
if req.response:
295
status = req.response.get('status', 0)
296
if status >= 400:
297
error_requests.append(req)
298
299
print(f"Error requests: {len(error_requests)}")
300
for error_req in error_requests[-3:]: # Last 3 errors
301
status = error_req.response.get('status')
302
path = error_req.request.get('uri')
303
print(f" {status} error on {path}")
304
305
# Export request data for external analysis
306
def export_requests_to_json(filename):
307
requests_list = agent.get_requests()
308
export_data = []
309
for req in requests_list:
310
export_data.append({
311
'id': req.id,
312
'tunnel_name': req.tunnel_name,
313
'remote_addr': req.remote_addr,
314
'start': req.start,
315
'duration': req.duration,
316
'request': req.request,
317
'response': req.response
318
})
319
320
with open(filename, 'w') as f:
321
json.dump(export_data, f, indent=2)
322
print(f"Exported {len(export_data)} requests to {filename}")
323
324
# Export current requests
325
export_requests_to_json("ngrok_requests.json")
326
```
327
328
### Monitoring and Alerting
329
330
Set up monitoring based on captured request patterns.
331
332
**Usage Examples:**
333
334
```python
335
from pyngrok import agent, ngrok
336
import time
337
import threading
338
339
def monitor_requests(tunnel_name, alert_threshold=10):
340
"""Monitor request rate and alert on high traffic"""
341
last_count = 0
342
343
while True:
344
current_requests = agent.get_requests(tunnel_name=tunnel_name)
345
current_count = len(current_requests)
346
347
requests_per_minute = current_count - last_count
348
if requests_per_minute > alert_threshold:
349
print(f"ALERT: High traffic detected! {requests_per_minute} requests/minute")
350
351
# Analyze recent requests
352
recent_requests = current_requests[-requests_per_minute:]
353
error_count = sum(1 for req in recent_requests
354
if req.response and req.response.get('status', 0) >= 400)
355
print(f" Error rate: {error_count}/{requests_per_minute}")
356
357
last_count = current_count
358
time.sleep(60) # Check every minute
359
360
# Start tunnel and monitoring
361
tunnel = ngrok.connect("8000")
362
monitor_thread = threading.Thread(
363
target=monitor_requests,
364
args=(tunnel.name, 5), # Alert if >5 requests/minute
365
daemon=True
366
)
367
monitor_thread.start()
368
369
print(f"Monitoring traffic to {tunnel.public_url}")
370
print("Send requests to trigger monitoring...")
371
```