API Documentation

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

Main ngrok Interface

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

Bases: object

An object containing information about a ngrok tunnel.

Variables:
  • name (str) – The name of the tunnel.
  • proto (str) – A valid tunnel protocol.
  • uri (str) – The tunnel URI, a relative path that can be used to make requests to the ngrok web interface.
  • public_url (str) – The public ngrok URL.
  • config (dict) – The config for the tunnel.
  • metrics (dict) – Metrics for the tunnel.
  • pyngrok_config (PyngrokConfig) – The pyngrok configuration to use with ngrok.
  • api_url (str) – The API URL for the ngrok web interface.
refresh_metrics()[source]

Refresh the metrics from the tunnel.

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

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

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

from pyngrok import ngrok

public_url = ngrok.connect()
response = ngrok.api_request("{}/some-route".format(public_url),
                             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("{}/api/requests/http".format(api_url),
                             params={"tunnel_name": "foo"})
Parameters:
  • url (str) – The request URL.
  • method (str, optional) – The HTTP method.
  • data (dict, optional) – The request body.
  • params (dict, optional) – The URL parameters.
  • timeout (float, optional) – The request timeout, in seconds.
Returns:

The response from the request.

Return type:

dict

pyngrok.ngrok.connect(port='80', proto='http', name=None, pyngrok_config=None, return_ngrok_tunnel=False, **options)[source]

Establish a new ngrok tunnel for the given protocol to the given port, returning the connected public URL that tunnels to the local port.

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:
  • port (str, optional) – The local port to which the tunnel will forward traffic, defaults to “80”. Can also be a local directory or network address.
  • proto (str, optional) – The protocol to tunnel, defaults to “http”.
  • name (str, optional) – A friendly name for the tunnel.
  • pyngrok_config (PyngrokConfig, optional) – The pyngrok configuration to use when interacting with the ngrok binary, defaults to conf.DEFAULT_PYNGROK_CONFIG (which can be overridden instead, as shown here).
  • return_ngrok_tunnel (bool, optional) – True if a NgrokTunnel should be returned, False for str.
  • options (dict, optional) – Remaining kwargs are passed as configuration for the ngrok tunnel.
Returns:

The connected public URL if return_ngrok_tunnel is False, otherwise a NgrokTunnel.

Return type:

str

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

Disconnect the ngrok tunnel for the given URL.

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:
  • public_url (str) – The public URL of the tunnel to disconnect.
  • pyngrok_config (PyngrokConfig, optional) –

    The pyngrok configuration to use when interacting with the ngrok binary, defaults to conf.DEFAULT_PYNGROK_CONFIG (which can be overridden instead, as shown here).

pyngrok.ngrok.ensure_ngrok_installed(ngrok_path)[source]

Ensure ngrok is installed at the given path, downloading and installing the binary for the current system if not.

Parameters:ngrok_path (str) – The path to the ngrok binary.
pyngrok.ngrok.get_ngrok_process(pyngrok_config=None)[source]

Retrieve 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.

Parameters:pyngrok_config (PyngrokConfig, optional) –

The pyngrok configuration to use when interacting with the ngrok binary, defaults to conf.DEFAULT_PYNGROK_CONFIG (which can be overridden instead, as shown here).

Returns:The ngrok process.
Return type:NgrokProcess
pyngrok.ngrok.get_tunnels(pyngrok_config=None)[source]

Retrieve 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 (PyngrokConfig, optional) –

The pyngrok configuration to use when interacting with the ngrok binary, defaults to conf.DEFAULT_PYNGROK_CONFIG (which can be overridden instead, as shown here).

Returns:The active ngrok tunnels.
Return type:list[NgrokTunnel]
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 (PyngrokConfig, optional) –

The pyngrok configuration to use when interacting with the ngrok binary, defaults to conf.DEFAULT_PYNGROK_CONFIG (which can be overridden instead, as shown here).

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.

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

Ensure ngrok is installed in the default location, 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:args (list[str], optional) – Arguments to be passed to the ngrok process.
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 (PyngrokConfig, optional) –

    The pyngrok configuration to use when interacting with the ngrok binary, defaults to conf.DEFAULT_PYNGROK_CONFIG (which can be overridden instead, as shown here).

Process Management

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

Bases: object

An object containing a parsed log from the ngrok process.

Variables:
  • line (str) – The raw, unparsed log line.
  • t (str) – The log’s ISO 8601 timestamp.
  • lvl (str) – The log’s level.
  • msg (str) – The log’s message.
  • err (str) – The log’s error, if applicable.
  • addr (str) – The URL, if obj is “web”.
class pyngrok.process.NgrokProcess(proc, pyngrok_config)[source]

Bases: object

An object containing information about the ngrok process.

Variables:
  • proc (subprocess.Popen) – The child process that is running ngrok.
  • pyngrok_config (PyngrokConfig) – The pyngrok configuration to use with ngrok.
  • api_url (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 (str) – If ngrok startup fails, this will be the log of the failure.
_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.
Returns:The parsed log.
Return type:NgrokLog
_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.
Returns:The parsed log.
Return type:NgrokLog
healthy()[source]

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

Returns:True if the ngrok process is started, running, and healthy.
Return type:bool
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.

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.

pyngrok.process._ensure_path_ready(ngrok_path)[source]

Ensure the binary for ngrok at the given path is ready to be started, raise a relevant exception if not.

Parameters:ngrok_path (str) – The path to the ngrok binary.
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.
Returns:The ngrok process.
Return type:NgrokProcess
pyngrok.process.get_process(pyngrok_config)[source]

Retrieve 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.
Returns:The ngrok process.
Return type:NgrokProcess
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.
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.
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.

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)[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.

On import, conf.DEFAULT_PYNGROK_CONFIG is instantiated to a PyngrokConfig with default values. When pyngrok_config is not passed to methods in ngrok, this default will be used.

Variables:
  • ngrok_path (str) – The path to the ngrok binary, defaults to the value in conf.DEFAULT_NGROK_PATH
  • config_path (str) – The path to the ngrok config, defaults to None and ngrok manages it.
  • auth_token (str) – An authtoken to pass to commands (overrides what is in the config).
  • region (str) – The region in which ngrok should start.
  • monitor_thread (bool) – Whether ngrok should continue to be monitored (for logs, etc.) after it startup is complete.
  • log_event_callback (types.FunctionType) – A callback that will be invoked each time ngrok emits a log. 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)
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.

Returns:The default pyngrok_config.
Return type:PyngrokConfig

ngrok Installer

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, optional) – The number of retries to attempt, if download fails.
  • kwargs (dict, optional) – Remaining kwargs will be passed to urllib.request.urlopen.
Returns:

The path to the downloaded temporary file.

Return type:

str

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.
pyngrok.installer.get_ngrok_bin()[source]

Retrieve the ngrok executable for the current system.

Returns:The name of the ngrok executable.
Return type:str
pyngrok.installer.install_default_config(config_path, data=None)[source]

Install the default ngrok config. If one is not already present, create one. Before saving new values 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 (dict, optional) – A dictionary of things to added to the default config.
pyngrok.installer.install_ngrok(ngrok_path, **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.
  • kwargs (dict, optional) – Remaining kwargs will be passed to _download_file.
pyngrok.installer.validate_config(data)[source]

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

Parameters:data (dict) – A dictionary of things to be validated as config items.

Exceptions

exception pyngrok.exception.PyngrokError[source]

Bases: Exception

Raised when a general pyngrok error has occurred.

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

Bases: pyngrok.exception.PyngrokError

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

Variables:
  • error (str) – A description of the error being thrown.
  • ngrok_logs (list[NgrokLog]) – The ngrok logs, which may be useful for debugging the error.
  • ngrok_error (str) – The error that caused the ngrok process to fail.
exception pyngrok.exception.PyngrokNgrokHTTPError(error, url, status_code, message, headers, body)[source]

Bases: pyngrok.exception.PyngrokNgrokError

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

Variables:
  • error (str) – A description of the error being thrown.
  • url (str) – The request URL that failed.
  • status_code (int) – The response status code from ngrok.
  • message (str) – The response message from ngrok.
  • headers (dict[str, str]) – The request headers sent to ngrok.
  • body (str) – The response body from ngrok.
exception pyngrok.exception.PyngrokNgrokInstallError[source]

Bases: pyngrok.exception.PyngrokError

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

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

Bases: pyngrok.exception.PyngrokNgrokError

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

Variables:
  • error (str) – A description of the error being thrown.
  • reason (str) – The reason for the URL error.
exception pyngrok.exception.PyngrokSecurityError[source]

Bases: pyngrok.exception.PyngrokError

Raised when a pyngrok security error has occurred.