ngrok Python SDK
The ngrok Python SDK is an official, open-source library that enables developers to integrate secure ingress directly into their Python applications. It acts as a Python-packaged version of the ngrok Agent CLI, allowing applications to expose local services to the internet without complex network configurations. The library is actively maintained, with a current version of 1.7.0, and typically sees updates in line with major ngrok platform developments.
Warnings
- gotcha There are multiple Python libraries related to ngrok. `ngrok` (ngrok-python) is the official SDK for embedding ngrok functionality directly into your application without needing a separate ngrok binary. `pyngrok` is a wrapper for the ngrok binary, managing its download and execution. `ngrok-api` is for interacting with the ngrok HTTP API. Ensure you are using the correct library for your use case.
- gotcha An ngrok authtoken is usually required for full functionality, especially for custom domains or advanced features. Failing to provide one will limit capabilities or prevent the tunnel from starting.
- gotcha For long-running applications or when integrating with async frameworks, ensure the ngrok listener is properly managed to prevent resource leaks. The `ngrok.forward()` method may return an awaitable in async contexts.
Install
-
pip install ngrok
Imports
- ngrok
import ngrok
Quickstart
import ngrok
import os
import time
# Ensure NGROK_AUTHTOKEN is set in your environment variables
# or pass it directly: ngrok.forward(9000, authtoken="YOUR_AUTHTOKEN")
if os.environ.get('NGROK_AUTHTOKEN') == None:
print("WARNING: NGROK_AUTHTOKEN environment variable not set. Please set it for ngrok to function correctly.")
# Establish connectivity to a local service running on port 9000
# For this example, imagine a simple HTTP server is running on localhost:9000
listener = ngrok.forward(9000, authtoken_from_env=True)
print(f"ngrok Ingress established at {listener.url()}")
# Keep the listener alive
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\nClosing ngrok listener")
ngrok.disconnect(listener.url())
ngrok.kill()