API Documentation

This part of the documentation covers the interfaces used to develop with pyngrok.

Main ngrok Interface

class pyngrok.ngrok.NgrokTunnel(data, pyngrok_config, api_url)[source]

Bases: object

An object containing information about a ngrok tunnel.

data: Dict[str, Any]

The original tunnel data.

pyngrok_config: PyngrokConfig

The pyngrok configuration to use when interacting with the ngrok.

api_url: Optional[str]

The API URL for the ngrok web interface.

id: Optional[str]

The ID of the tunnel.

name: Optional[str]

The name of the tunnel.

proto: Optional[str]

The protocol of the tunnel.

uri: Optional[str]

The tunnel URI, a relative path that can be used to make requests to the ngrok web interface.

public_url: Optional[str]

The public ngrok URL.

config: Dict[str, Any]

The config for the tunnel.

metrics: Dict[str, Any]

Metrics for the tunnel.

refresh_metrics()[source]

Get the latest metrics for the tunnel and update the metrics variable.

Raises:

PyngrokError: When the API does not return metrics.

Return type:

None

pyngrok.ngrok.install_ngrok(pyngrok_config=None)[source]

Download, install, and initialize ngrok for the given config. If ngrok and its default config is already installed, calling this method will do nothing.

Parameters:

pyngrok_config (Optional[PyngrokConfig]) – A pyngrok configuration to use when interacting with the ngrok binary, overriding get_default.

Return type:

None

pyngrok.ngrok.set_auth_token(token, pyngrok_config=None)[source]

Set the ngrok auth token in the config file, enabling authenticated features (for instance, more concurrent tunnels, custom subdomains, etc.).

If ngrok is not installed at PyngrokConfig’s ngrok_path, calling this method will first download and install ngrok.

Parameters:
  • token (str) – The auth token to set.

  • pyngrok_config (Optional[PyngrokConfig]) – A pyngrok configuration to use when interacting with the ngrok binary, overriding get_default.

Return type:

None

pyngrok.ngrok.get_ngrok_process(pyngrok_config=None)[source]

Get the current ngrok process for the given config’s ngrok_path.

If ngrok is not installed at PyngrokConfig’s ngrok_path, calling this method will first download and install ngrok.

If ngrok is not running, calling this method will first start a process with PyngrokConfig.

Use is_process_running to check if a process is running without also implicitly installing and starting it.

Parameters:

pyngrok_config (Optional[PyngrokConfig]) – A pyngrok configuration to use when interacting with the ngrok binary, overriding get_default.

Return type:

NgrokProcess

Returns:

The ngrok process.

pyngrok.ngrok.connect(addr=None, proto=None, name=None, pyngrok_config=None, **options)[source]

Establish a new ngrok tunnel for the given protocol to the given port, returning an object representing the connected tunnel.

If a tunnel definition in ngrok’s config file matches the given name, it will be loaded and used to start the tunnel. When name is None and a “pyngrok-default” tunnel definition exists in ngrok’s config, it will be loaded and use. Any kwargs passed as options will override properties from the loaded tunnel definition.

If ngrok is not installed at PyngrokConfig’s ngrok_path, calling this method will first download and install ngrok.

pyngrok is compatible with ngrok v2 and v3, but by default it will install v3. To install v2 instead, set ngrok_version to “v2” in PyngrokConfig:

If ngrok is not running, calling this method will first start a process with PyngrokConfig.

Note

ngrok v2’s default behavior for http when no additional properties are passed is to open two tunnels, one http and one https. This method will return a reference to the http tunnel in this case. If only a single tunnel is needed, pass bind_tls=True and a reference to the https tunnel will be returned.

Parameters:
Return type:

NgrokTunnel

Returns:

The created ngrok tunnel.

Raises:

PyngrokError: When the tunnel definition is invalid, or the response does not contain public_url.

pyngrok.ngrok.disconnect(public_url, pyngrok_config=None)[source]

Disconnect the ngrok tunnel for the given URL, if open.

Parameters:
  • public_url (str) – The public URL of the tunnel to disconnect.

  • pyngrok_config (Optional[PyngrokConfig]) – A pyngrok configuration to use when interacting with the ngrok binary, overriding get_default.

Return type:

None

pyngrok.ngrok.get_tunnels(pyngrok_config=None)[source]

Get a list of active ngrok tunnels for the given config’s ngrok_path.

If ngrok is not installed at PyngrokConfig’s ngrok_path, calling this method will first download and install ngrok.

If ngrok is not running, calling this method will first start a process with PyngrokConfig.

Parameters:

pyngrok_config (Optional[PyngrokConfig]) – A pyngrok configuration to use when interacting with the ngrok binary, overriding get_default.

Return type:

List[NgrokTunnel]

Returns:

The active ngrok tunnels.

Raises:

PyngrokError: When the response was invalid or does not contain public_url.

pyngrok.ngrok.kill(pyngrok_config=None)[source]

Terminate the ngrok processes, if running, for the given config’s ngrok_path. This method will not block, it will just issue a kill request.

Parameters:

pyngrok_config (Optional[PyngrokConfig]) – A pyngrok configuration to use when interacting with the ngrok binary, overriding get_default.

Return type:

None

pyngrok.ngrok.get_version(pyngrok_config=None)[source]

Get a tuple with the ngrok and pyngrok versions.

Parameters:

pyngrok_config (Optional[PyngrokConfig]) – A pyngrok configuration to use when interacting with the ngrok binary, overriding get_default.

Return type:

Tuple[str, str]

Returns:

A tuple of (ngrok_version, pyngrok_version).

pyngrok.ngrok.update(pyngrok_config=None)[source]

Update ngrok for the given config’s ngrok_path, if an update is available.

Parameters:

pyngrok_config (Optional[PyngrokConfig]) – A pyngrok configuration to use when interacting with the ngrok binary, overriding get_default.

Return type:

str

Returns:

The result from the ngrok update.

pyngrok.ngrok.api_request(url, method='GET', data=None, params=None, timeout=4, auth=None)[source]

Invoke an API request to the given URL, returning JSON data from the response.

One use for this method is making requests to ngrok tunnels:

from pyngrok import ngrok

public_url = ngrok.connect()
response = ngrok.api_request(f"{public_url}/some-route",
                             method="POST", data={"foo": "bar"})

Another is making requests to the ngrok API itself:

from pyngrok import ngrok

api_url = ngrok.get_ngrok_process().api_url
response = ngrok.api_request(f"{api_url}/api/requests/http",
                             params={"tunnel_name": "foo"})
Parameters:
  • url (str) – The request URL.

  • method (str) – The HTTP method.

  • data (Optional[Dict[str, Any]]) – The request body.

  • params (Optional[Dict[str, Any]]) – The URL parameters.

  • timeout (float) – The request timeout, in seconds.

  • auth (Optional[str]) – Set as Bearer for an Authorization header.

Return type:

Dict[str, Any]

Returns:

The response from the request.

Raises:

PyngrokSecurityError: When the url is not supported.

Raises:

PyngrokNgrokHTTPError: When the request returns an error response.

Raises:

PyngrokNgrokURLError: When the request times out.

pyngrok.ngrok.run(args=None, pyngrok_config=None)[source]

Ensure ngrok is installed at the default path, then call run_process.

This method is meant for interacting with ngrok from the command line and is not necessarily compatible with non-blocking API methods. For that, use ngrok’s interface methods (like connect), or use get_process.

Parameters:
Return type:

None

pyngrok.ngrok.main()[source]

Entry point for the package’s console_scripts. This initializes a call from the command line and invokes run.

This method is meant for interacting with ngrok from the command line and is not necessarily compatible with non-blocking API methods. For that, use ngrok’s interface methods (like connect), or use get_process.

Return type:

None

Process Management

class pyngrok.process.NgrokProcess(proc, pyngrok_config)[source]

Bases: object

An object containing information about the ngrok process.

proc: Popen

The child process that is running ngrok.

pyngrok_config: PyngrokConfig

The pyngrok configuration to use with ngrok.

api_url: Optional[str]

The API URL for the ngrok web interface.

logs: List[NgrokLog]

A list of the most recent logs from ngrok, limited in size to max_logs.

startup_error: Optional[str]

If ngrok startup fails, this will be the log of the failure.

_log_startup_line(line)[source]

Parse the given startup log line and use it to manage the startup state of the ngrok process.

Parameters:

line (str) – The line to be parsed and logged.

Return type:

Optional[NgrokLog]

Returns:

The parsed log.

_log_line(line)[source]

Parse, log, and emit (if log_event_callback in PyngrokConfig is registered) the given log line.

Parameters:

line (str) – The line to be processed.

Return type:

Optional[NgrokLog]

Returns:

The parsed log.

healthy()[source]

Check whether the ngrok process has finished starting up and is in a running, healthy state.

Return type:

bool

Returns:

True if the ngrok process is started, running, and healthy.

Raises:

PyngrokSecurityError: When the url is not supported.

start_monitor_thread()[source]

Start a thread that will monitor the ngrok process and its logs until it completes.

If a monitor thread is already running, nothing will be done.

Return type:

None

stop_monitor_thread()[source]

Set the monitor thread to stop monitoring the ngrok process after the next log event. This will not necessarily terminate the thread immediately, as the thread may currently be idle, rather it sets a flag on the thread telling it to terminate the next time it wakes up.

This has no impact on the ngrok process itself, only pyngrok’s monitor of the process and its logs.

Return type:

None

pyngrok.process.set_auth_token(pyngrok_config, token)[source]

Set the ngrok auth token in the config file, enabling authenticated features (for instance, more concurrent tunnels, custom subdomains, etc.).

Parameters:
  • pyngrok_config (PyngrokConfig) – The pyngrok configuration to use when interacting with the ngrok binary.

  • token (str) – The auth token to set.

Raises:

PyngrokError: When the ngrok_version is not supported.

Raises:

PyngrokNgrokError: When ngrok could not start.

Return type:

None

pyngrok.process.is_process_running(ngrok_path)[source]

Check if the ngrok process is currently running.

Parameters:

ngrok_path (str) – The path to the ngrok binary.

Return type:

bool

Returns:

True if ngrok is running from the given path.

pyngrok.process.get_process(pyngrok_config)[source]

Get the current ngrok process for the given config’s ngrok_path.

If ngrok is not running, calling this method will first start a process with PyngrokConfig.

Parameters:

pyngrok_config (PyngrokConfig) – The pyngrok configuration to use when interacting with the ngrok binary.

Return type:

NgrokProcess

Returns:

The ngrok process.

pyngrok.process.kill_process(ngrok_path)[source]

Terminate the ngrok processes, if running, for the given path. This method will not block, it will just issue a kill request.

Parameters:

ngrok_path (str) – The path to the ngrok binary.

Return type:

None

pyngrok.process.run_process(ngrok_path, args)[source]

Start a blocking ngrok process with the binary at the given path and the passed args.

This method is meant for invoking ngrok directly (for instance, from the command line) and is not necessarily compatible with non-blocking API methods. For that, use get_process.

Parameters:
  • ngrok_path (str) – The path to the ngrok binary.

  • args (List[str]) – The args to pass to ngrok.

Return type:

None

pyngrok.process.capture_run_process(ngrok_path, args)[source]

Start a blocking ngrok process with the binary at the given path and the passed args. When the process returns, so will this method, and the captured output from the process along with it.

This method is meant for invoking ngrok directly (for instance, from the command line) and is not necessarily compatible with non-blocking API methods. For that, use get_process.

Parameters:
  • ngrok_path (str) – The path to the ngrok binary.

  • args (List[str]) – The args to pass to ngrok.

Return type:

str

Returns:

The output from the process.

pyngrok.process._validate_path(ngrok_path)[source]

Validate the given path exists, is a ngrok binary, and is ready to be started, otherwise raise a relevant exception.

Parameters:

ngrok_path (str) – The path to the ngrok binary.

Raises:

PyngrokNgrokError: When ngrok could not start.

Return type:

None

pyngrok.process._start_process(pyngrok_config)[source]

Start a ngrok process with no tunnels. This will start the ngrok web interface, against which HTTP requests can be made to create, interact with, and destroy tunnels.

Parameters:

pyngrok_config (PyngrokConfig) – The pyngrok configuration to use when interacting with the ngrok binary.

Return type:

NgrokProcess

Returns:

The ngrok process.

Raises:

PyngrokNgrokError: When ngrok could not start.

Configuration

class pyngrok.conf.PyngrokConfig(ngrok_path=None, config_path=None, auth_token=None, region=None, monitor_thread=True, log_event_callback=None, startup_timeout=15, max_logs=100, request_timeout=4, start_new_session=False, ngrok_version='v3', api_key=None)[source]

Bases: object

An object containing pyngrok’s configuration for interacting with the ngrok binary. All values are optional when it is instantiated, and default values will be used for parameters not passed.

Use get_default and set_default to interact with the default pyngrok_config, or pass another instance of this object as the pyngrok_config keyword arg to most methods in the ngrok module to override the default.

from pyngrok import conf, ngrok

# Here we update the entire default config
pyngrok_config = conf.PyngrokConfig(ngrok_path="/usr/local/bin/ngrok")
conf.set_default(pyngrok_config)

# Here we update just one variable in the default config
conf.get_default().ngrok_path = "/usr/local/bin/ngrok"

# Here we leave the default config as-is and pass an override
pyngrok_config = conf.PyngrokConfig(ngrok_path="/usr/local/bin/ngrok")
ngrok.connect(pyngrok_config=pyngrok_config)
ngrok_path: str

The path to the ngrok binary, defaults to the value in conf.DEFAULT_NGROK_PATH.

config_path: Optional[str]

The path to the ngrok config, defaults to None and ngrok manages it.

auth_token: Optional[str]

A ngrok authtoken to pass to commands (overrides what is in the config). If a value is not passed, will attempt to use the environment variable NGROK_AUTHTOKEN if it is set.

region: Optional[str]

The region in which ngrok should start.

monitor_thread: bool

Whether ngrok should continue to be monitored (for logs, etc.) after startup is complete.

log_event_callback: Optional[Callable[[NgrokLog], None]]

A callback that will be invoked each time ngrok emits a log. The function should take one argument of type str. monitor_thread must be set to True or the function will stop being called after ngrok finishes starting.

startup_timeout: int

The max number of seconds to wait for ngrok to start before timing out.

max_logs: int

The max number of logs to store in NgrokProcess’s logs variable.

request_timeout: float

The max timeout when making requests to ngrok’s API.

start_new_session: bool

Passed to subprocess.Popen when launching ngrok. (Python 3 and POSIX only).

ngrok_version: str

The major version of ngrok installed.

api_key: Optional[str]

A ngrok API key.

pyngrok.conf.get_default()[source]

Get the default config to be used with methods in the ngrok module. To override the default individually, the pyngrok_config keyword arg can also be passed to most of these methods, or set a new default config with set_default.

Return type:

PyngrokConfig

Returns:

The default pyngrok_config.

pyngrok.conf.set_default(pyngrok_config)[source]

Set a new default config to be used with methods in the ngrok module. To override the default individually, the pyngrok_config keyword arg can also be passed to most of these methods.

Parameters:

pyngrok_config (PyngrokConfig) – The new pyngrok_config to be used by default.

Return type:

None

pyngrok.conf.get_config_path(pyngrok_config)[source]

Return the config_path if set on the given pyngrok_configg, otherwise return ngrok’s default path.

Parameters:

pyngrok_config (PyngrokConfig) – The pyngrok configuration to first check for a config_path.

Return type:

str

Returns:

The path to the config file.

ngrok Installer

pyngrok.installer.get_ngrok_bin()[source]

Get the ngrok executable for the current system.

Return type:

str

Returns:

The name of the ngrok executable.

Raises:

PyngrokNgrokInstallError: When the platform is not supported.

pyngrok.installer.install_ngrok(ngrok_path, ngrok_version='v3', **kwargs)[source]

Download and install the latest ngrok for the current system, overwriting any existing contents at the given path.

Parameters:
  • ngrok_path (str) – The path to where the ngrok binary will be downloaded.

  • ngrok_version (Optional[str]) – The major version of ngrok to be installed.

  • kwargs (Any) – Remaining kwargs will be passed to _download_file.

Raises:

PyngrokError: When the ngrok_version is not supported.

Raises:

PyngrokNgrokInstallError: When an error occurs installing ngrok.

Return type:

None

pyngrok.installer._install_ngrok_zip(ngrok_path, zip_path)[source]

Extract the ngrok zip file to the given path.

Parameters:
  • ngrok_path (str) – The path where ngrok will be installed.

  • zip_path (str) – The path to the ngrok zip file to be extracted.

Return type:

None

pyngrok.installer.get_ngrok_config(config_path, use_cache=True, ngrok_version='v3')[source]

Get the ngrok config from the given path.

Parameters:
  • config_path (str) – The ngrok config path to read.

  • use_cache (bool) – Use the cached version of the config (if populated).

  • ngrok_version (Optional[str]) – The major version of ngrok installed.

Return type:

Dict[str, Any]

Returns:

The ngrok config.

pyngrok.installer.get_default_config(ngrok_version)[source]

Get the default config params for the given major version of ngrok.

Parameters:

ngrok_version (Optional[str]) – The major version of ngrok installed.

Return type:

Dict[str, Any]

Returns:

The default config.

Raises:

PyngrokError: When the ngrok_version is not supported.

pyngrok.installer.install_default_config(config_path, data=None, ngrok_version='v3')[source]

Install the given data to the ngrok config. If a config is not already present for the given path, create one. Before saving new data to the default config, validate that they are compatible with pyngrok.

Parameters:
  • config_path (str) – The path to where the ngrok config should be installed.

  • data (Optional[Dict[str, Any]]) – A dictionary of things to add to the default config.

  • ngrok_version (Optional[str]) – The major version of ngrok installed.

Return type:

None

pyngrok.installer.validate_config(data)[source]

Validate that the given dict of config items are valid for ngrok and pyngrok.

Parameters:

data (Dict[str, Any]) – A dictionary of things to be validated as config items.

Raises:

PyngrokError: When a key or value fails validation.

Return type:

None

pyngrok.installer._download_file(url, retries=0, **kwargs)[source]

Download a file to a temporary path and emit a status to stdout (if possible) as the download progresses.

Parameters:
  • url (str) – The URL to download.

  • retries (int) – The retry attempt index, if download fails.

  • kwargs (Any) – Remaining kwargs will be passed to urllib.request.urlopen.

Return type:

str

Returns:

The path to the downloaded temporary file.

Raises:

PyngrokSecurityError: When the url is not supported.

Raises:

PyngrokNgrokInstallError: When an error occurs downloading ngrok.

Logging

class pyngrok.log.NgrokLog(line)[source]

Bases: object

An object containing a parsed log from the ngrok process.

line: str

The raw, unparsed log line.

t: Optional[str]

The log’s ISO 8601 timestamp.

lvl: str

The log’s level.

msg: Optional[str]

The log’s message.

err: Optional[str]

The log’s error, if applicable.

obj: Optional[str]

The log’s type.

addr: Optional[str]

The URL, if obj is “web”.

Exceptions

exception pyngrok.exception.PyngrokError[source]

Bases: Exception

Raised when a general pyngrok error has occurred.

exception pyngrok.exception.PyngrokSecurityError[source]

Bases: PyngrokError

Raised when a pyngrok security error has occurred.

exception pyngrok.exception.PyngrokNgrokInstallError[source]

Bases: PyngrokError

Raised when an error has occurred while downloading and installing the ngrok binary.

exception pyngrok.exception.PyngrokNgrokError(error, ngrok_logs=None, ngrok_error=None)[source]

Bases: PyngrokError

Raised when an error occurs interacting directly with the ngrok binary.

ngrok_logs: List[NgrokLog]

The ngrok logs, which may be useful for debugging the error.

ngrok_error: Optional[str]

The error that caused the ngrok process to fail.

exception pyngrok.exception.PyngrokNgrokHTTPError(error, url, status_code, message, headers, body)[source]

Bases: PyngrokNgrokError

Raised when an error occurs making a request to the ngrok web interface. The body contains the error response received from ngrok.

url: str

The request URL that failed.

status_code: int

The response status code from ngrok.

message: Optional[str]

The response message from ngrok.

headers: Any

The request headers sent to ngrok.

body: str

The response body from ngrok.

exception pyngrok.exception.PyngrokNgrokURLError(error, reason)[source]

Bases: PyngrokNgrokError

Raised when an error occurs when trying to initiate an API request.

reason: Any

The reason for the URL error.