0
# API Integration
1
2
Direct access to ngrok's CLI API and HTTP request functionality for advanced integrations and custom workflows.
3
4
## Capabilities
5
6
### ngrok CLI API Access
7
8
Direct interface to ngrok's command-line API for advanced operations and configurations.
9
10
```python { .api }
11
def api(*args, pyngrok_config=None):
12
"""
13
Run ngrok command against the API with given arguments.
14
Uses the local agent to run remote API requests, requires API key.
15
16
Parameters:
17
- *args: Arguments to pass to the ngrok api command
18
- pyngrok_config (PyngrokConfig, optional): Configuration override
19
20
Returns:
21
NgrokApiResponse: Response from executing the api command
22
23
Raises:
24
PyngrokNgrokError: When ngrok process exits with error
25
CalledProcessError: When process execution fails
26
"""
27
28
class NgrokApiResponse:
29
"""
30
Container for ngrok API command response.
31
"""
32
status: str # Description of the response
33
data: dict # Parsed API response data
34
35
@staticmethod
36
def from_body(body):
37
"""
38
Construct NgrokApiResponse from response body string.
39
40
Parameters:
41
- body (str): Response body to parse
42
43
Returns:
44
NgrokApiResponse: Constructed response object
45
"""
46
```
47
48
**Usage Examples:**
49
50
```python
51
from pyngrok import ngrok, conf
52
53
# Configure with API key for CLI API access
54
config = conf.PyngrokConfig(api_key="your_ngrok_api_key_here")
55
ngrok.set_default(config)
56
57
# Get help for API commands
58
help_response = ngrok.api("--help")
59
print(f"Status: {help_response.status}")
60
if help_response.data:
61
print(f"Data: {help_response.data}")
62
63
# Create a reserved domain
64
domain = "my-app.ngrok.dev"
65
domain_response = ngrok.api("reserved-domains", "create", "--domain", domain)
66
print(f"Domain creation: {domain_response.status}")
67
68
# List reserved domains
69
list_response = ngrok.api("reserved-domains", "list")
70
print(f"Domains: {list_response.data}")
71
72
# Create a Cloud Endpoint with traffic policy
73
endpoint_response = ngrok.api(
74
"endpoints", "create",
75
"--bindings", "public",
76
"--url", f"https://{domain}",
77
"--traffic-policy-file", "policy.yml"
78
)
79
print(f"Endpoint creation: {endpoint_response.status}")
80
```
81
82
### HTTP API Requests
83
84
Low-level HTTP request functionality for interacting with ngrok APIs and tunneled services.
85
86
```python { .api }
87
def api_request(url, method="GET", data=None, params=None, timeout=4, auth=None):
88
"""
89
Make HTTP API request to the given URL with JSON response parsing.
90
91
Parameters:
92
- url (str): The request URL (must start with "http")
93
- method (str): HTTP method ("GET", "POST", "PUT", "DELETE", etc.)
94
- data (dict, optional): Request body data (will be JSON-encoded)
95
- params (dict, optional): URL query parameters
96
- timeout (float): Request timeout in seconds
97
- auth (str, optional): Bearer token for Authorization header
98
99
Returns:
100
dict: Parsed JSON response data
101
102
Raises:
103
PyngrokSecurityError: When URL is not supported
104
PyngrokNgrokHTTPError: When request returns error response
105
PyngrokNgrokURLError: When request times out
106
"""
107
```
108
109
**Usage Examples:**
110
111
```python
112
from pyngrok import ngrok
113
114
# Start a tunnel to make API requests through
115
tunnel = ngrok.connect("8000")
116
print(f"Tunnel URL: {tunnel.public_url}")
117
118
# Make GET request through tunnel
119
try:
120
response = ngrok.api_request(f"{tunnel.public_url}/api/status")
121
print(f"Status response: {response}")
122
except Exception as e:
123
print(f"Request failed: {e}")
124
125
# Make POST request with data
126
post_data = {"name": "test", "value": 123}
127
try:
128
response = ngrok.api_request(
129
f"{tunnel.public_url}/api/data",
130
method="POST",
131
data=post_data
132
)
133
print(f"POST response: {response}")
134
except Exception as e:
135
print(f"POST request failed: {e}")
136
137
# Make request with query parameters
138
params = {"limit": 10, "offset": 0}
139
try:
140
response = ngrok.api_request(
141
f"{tunnel.public_url}/api/items",
142
params=params
143
)
144
print(f"Items: {response}")
145
except Exception as e:
146
print(f"Query request failed: {e}")
147
```
148
149
### ngrok API Requests
150
151
Make requests directly to the ngrok local API for tunnel management and inspection.
152
153
**Usage Examples:**
154
155
```python
156
from pyngrok import ngrok
157
158
# Get the ngrok process to access API URL
159
process = ngrok.get_ngrok_process()
160
api_url = process.api_url
161
162
# Get tunnel information via direct API
163
tunnels_response = ngrok.api_request(f"{api_url}/api/tunnels")
164
print(f"Active tunnels: {len(tunnels_response['tunnels'])}")
165
166
for tunnel_data in tunnels_response['tunnels']:
167
print(f" {tunnel_data['name']}: {tunnel_data['public_url']}")
168
169
# Get detailed tunnel information
170
if tunnels_response['tunnels']:
171
tunnel_uri = tunnels_response['tunnels'][0]['uri']
172
tunnel_detail = ngrok.api_request(f"{api_url}{tunnel_uri}")
173
print(f"Tunnel details: {tunnel_detail}")
174
175
# Get request history via API
176
requests_response = ngrok.api_request(f"{api_url}/api/requests/http")
177
print(f"Captured requests: {len(requests_response.get('requests', []))}")
178
179
# Get agent status via API
180
status_response = ngrok.api_request(f"{api_url}/api/status")
181
print(f"Agent status: {status_response.get('status', 'unknown')}")
182
```
183
184
### Authenticated API Requests
185
186
Make requests to external ngrok APIs using authentication.
187
188
**Usage Examples:**
189
190
```python
191
from pyngrok import ngrok
192
193
# Configure API key for external API access
194
api_key = "your_ngrok_api_key_here"
195
196
# Get account information
197
try:
198
account_response = ngrok.api_request(
199
"https://api.ngrok.com/account",
200
auth=api_key
201
)
202
print(f"Account: {account_response}")
203
except Exception as e:
204
print(f"Account request failed: {e}")
205
206
# List domains via API
207
try:
208
domains_response = ngrok.api_request(
209
"https://api.ngrok.com/reserved_domains",
210
auth=api_key
211
)
212
print(f"Reserved domains: {domains_response}")
213
except Exception as e:
214
print(f"Domains request failed: {e}")
215
216
# Create a tunnel via API
217
tunnel_config = {
218
"addr": "http://localhost:8000",
219
"name": "api-created-tunnel"
220
}
221
try:
222
create_response = ngrok.api_request(
223
"https://api.ngrok.com/tunnels",
224
method="POST",
225
data=tunnel_config,
226
auth=api_key
227
)
228
print(f"Tunnel created: {create_response}")
229
except Exception as e:
230
print(f"Tunnel creation failed: {e}")
231
```
232
233
### Advanced API Integration Patterns
234
235
Examples of complex API integration scenarios.
236
237
**Usage Examples:**
238
239
```python
240
from pyngrok import ngrok, conf
241
import json
242
import time
243
244
def setup_advanced_tunnel_with_monitoring():
245
"""Create tunnel with comprehensive monitoring setup"""
246
247
# Configure with all necessary credentials
248
config = conf.PyngrokConfig(
249
auth_token="your_authtoken",
250
api_key="your_api_key",
251
monitor_thread=True
252
)
253
254
# Create tunnel with custom configuration
255
tunnel = ngrok.connect(
256
"8000",
257
pyngrok_config=config,
258
subdomain="my-monitored-app"
259
)
260
261
print(f"Advanced tunnel created: {tunnel.public_url}")
262
263
# Set up monitoring through API
264
process = ngrok.get_ngrok_process(config)
265
api_url = process.api_url
266
267
def monitor_tunnel_health():
268
"""Monitor tunnel health and performance"""
269
while True:
270
try:
271
# Check tunnel status
272
tunnel_response = ngrok.api_request(f"{api_url}{tunnel.uri}")
273
metrics = tunnel_response.get('metrics', {})
274
275
# Check request rate
276
conn_count = metrics.get('conns', {}).get('count', 0)
277
print(f"Active connections: {conn_count}")
278
279
# Check for errors in recent requests
280
requests_response = ngrok.api_request(
281
f"{api_url}/api/requests/http",
282
params={"tunnel_name": tunnel.name}
283
)
284
285
recent_requests = requests_response.get('requests', [])[-10:]
286
error_count = sum(1 for req in recent_requests
287
if req.get('response', {}).get('status', 0) >= 400)
288
289
if error_count > 5:
290
print(f"WARNING: High error rate ({error_count}/10)")
291
292
except Exception as e:
293
print(f"Monitoring error: {e}")
294
295
time.sleep(30) # Check every 30 seconds
296
297
# Start monitoring in background thread
298
import threading
299
monitor_thread = threading.Thread(target=monitor_tunnel_health, daemon=True)
300
monitor_thread.start()
301
302
return tunnel
303
304
def api_based_tunnel_management():
305
"""Manage multiple tunnels through API calls"""
306
307
config = conf.PyngrokConfig(api_key="your_api_key")
308
process = ngrok.get_ngrok_process(config)
309
api_url = process.api_url
310
311
# Create multiple tunnels via API
312
tunnel_configs = [
313
{"addr": "8000", "name": "web-app", "proto": "http"},
314
{"addr": "3000", "name": "api-server", "proto": "http"},
315
{"addr": "22", "name": "ssh-access", "proto": "tcp"}
316
]
317
318
created_tunnels = []
319
for tunnel_config in tunnel_configs:
320
try:
321
response = ngrok.api_request(
322
f"{api_url}/api/tunnels",
323
method="POST",
324
data=tunnel_config
325
)
326
created_tunnels.append(response)
327
print(f"Created tunnel: {response['name']} -> {response['public_url']}")
328
except Exception as e:
329
print(f"Failed to create tunnel {tunnel_config['name']}: {e}")
330
331
# Monitor all tunnels
332
def get_tunnel_summary():
333
tunnels_response = ngrok.api_request(f"{api_url}/api/tunnels")
334
summary = {}
335
for tunnel in tunnels_response['tunnels']:
336
metrics = tunnel.get('metrics', {})
337
summary[tunnel['name']] = {
338
'url': tunnel['public_url'],
339
'connections': metrics.get('conns', {}).get('count', 0),
340
'bytes_in': metrics.get('http', {}).get('bytes_in', 0),
341
'bytes_out': metrics.get('http', {}).get('bytes_out', 0)
342
}
343
return summary
344
345
# Print tunnel summary
346
summary = get_tunnel_summary()
347
print(json.dumps(summary, indent=2))
348
349
return created_tunnels
350
351
# Use the advanced integration functions
352
advanced_tunnel = setup_advanced_tunnel_with_monitoring()
353
managed_tunnels = api_based_tunnel_management()
354
```
355
356
### Error Handling for API Requests
357
358
Comprehensive error handling for API integrations.
359
360
**Usage Examples:**
361
362
```python
363
from pyngrok import ngrok
364
from pyngrok.exception import (
365
PyngrokSecurityError,
366
PyngrokNgrokHTTPError,
367
PyngrokNgrokURLError
368
)
369
370
def robust_api_request(url, **kwargs):
371
"""Make API request with comprehensive error handling"""
372
try:
373
return ngrok.api_request(url, **kwargs)
374
375
except PyngrokSecurityError as e:
376
print(f"Security error - invalid URL: {e}")
377
return None
378
379
except PyngrokNgrokHTTPError as e:
380
print(f"HTTP error {e.status_code}: {e.message}")
381
print(f"Response body: {e.body}")
382
383
# Handle specific error codes
384
if e.status_code == 401:
385
print("Authentication required - check API key")
386
elif e.status_code == 429:
387
print("Rate limited - wait before retrying")
388
elif e.status_code >= 500:
389
print("Server error - may be temporary")
390
391
return None
392
393
except PyngrokNgrokURLError as e:
394
print(f"Network error: {e.reason}")
395
print("Check network connectivity")
396
return None
397
398
except Exception as e:
399
print(f"Unexpected error: {e}")
400
return None
401
402
# Use robust API requests
403
tunnel = ngrok.connect("8000")
404
405
# Safe API request to tunnel
406
response = robust_api_request(f"{tunnel.public_url}/api/status")
407
if response:
408
print(f"API response: {response}")
409
else:
410
print("API request failed")
411
412
# Safe request to ngrok API
413
process = ngrok.get_ngrok_process()
414
api_response = robust_api_request(f"{process.api_url}/api/tunnels")
415
if api_response:
416
print(f"Found {len(api_response['tunnels'])} tunnels")
417
```