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:
objectAn object containing information about a
ngroktunnel.-
pyngrok_config:
PyngrokConfig¶ The
pyngrokconfiguration to use when interacting with thengrok.
-
config:
Dict[str,Any]¶ The
configblock specific to v2 tunnels (e.g.{"addr": ..., "inspect": ...}); empty for v3 endpoints.
-
metrics:
Dict[str,Any]¶ Metrics for the tunnel.
- refresh_metrics()[source]¶
Get the latest metrics for the tunnel and update the
metricsvariable.- Raises:
PyngrokError: When the API does not returnmetrics.- Return type:
-
pyngrok_config:
- class pyngrok.ngrok.NgrokApiResponse(status, data)[source]¶
Bases:
objectAn object containing a response from the
ngrokAPI.
- pyngrok.ngrok.install_ngrok(pyngrok_config=None)[source]¶
Download, install, and initialize
ngrokfor the given config. Ifngrokand its default config is already installed, calling this method will do nothing.- Parameters:
pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.- Return type:
- pyngrok.ngrok.set_auth_token(token, pyngrok_config=None)[source]¶
Set the
ngrokauth token in the config file to streamline access to more features (for instance, multiple concurrent tunnels, custom domains, etc.).If
ngrokis not installed atPyngrokConfig’sngrok_path, calling this method will first download and installngrok.- Parameters:
token (
str) – The auth token to set.pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.
- Return type:
- pyngrok.ngrok.set_api_key(key, pyngrok_config=None)[source]¶
Set the
ngrokAPI key in the config file to enable access to more features (for instance, Internal Endpoints).If
ngrokis not installed atPyngrokConfig’sngrok_path, calling this method will first download and installngrok.- Parameters:
key (
str) – The API key to set.pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.
- Return type:
- pyngrok.ngrok.get_ngrok_process(pyngrok_config=None)[source]¶
Get the current
ngrokprocess for the given config’sngrok_path.If
ngrokis not installed atPyngrokConfig’sngrok_path, calling this method will first download and installngrok.If
ngrokis not running, calling this method will first start a process withPyngrokConfig.Use
is_process_runningto check if a process is running without also implicitly installing and starting it.- Parameters:
pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.- Return type:
- Returns:
The
ngrokprocess.
- pyngrok.ngrok.connect(addr=None, proto=None, name=None, pyngrok_config=None, **options)[source]¶
Establish a new
ngroktunnel for the given protocol to the given port, returning an object representing the connected tunnel.Routing is driven by
config_version:"2"usesngrok’s Tunnels and reads the v2tunnelsconfig block;"3"uses Endpoints and reads the v3endpointsblock (and atunnelsblock if also present, sincengrokallows both there).If a tunnel definition in
ngrok’s config file matches the givenname, it will be loaded and used to start the tunnel (note that “-api” will be appended to its name when started). WhennameisNoneand a “pyngrok-default” definition exists inngrok’s config, it will be loaded and used. Anykwargspassed asoptionswill override properties from the loaded definition.In v3 mode, v2 arguments (
addr/proto) are translated into the equivalentupstreamblock. Passing v3-only arguments such asupstreamorbindingswhileconfig_versionis"2"raisesPyngrokError.If
ngrokis not installed atPyngrokConfig’sngrok_path, calling this method will first download and installngrok.If
ngrokis not running, calling this method will first start a process withPyngrokConfig.- Parameters:
addr (
Optional[str]) – The local port to which the tunnel will forward traffic, or a local directory or network address, defaults to “80”.proto (
Union[str,int,None]) – A valid tunnel protocol, defaults to “http”.name (
Optional[str]) – A friendly name for the tunnel, or the name of a definition inngrok’s config file.pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.options (
Any) – Remainingkwargsare passed as configuration for thengrokagent (see the v2 or v3 schema).
- Return type:
- Returns:
The created
ngroktunnel.- Raises:
PyngrokError: When the tunnel definition is invalid, the requested options are incompatible with the configuredconfig_version, or the response does not containpublic_url.
- pyngrok.ngrok.disconnect(public_url, pyngrok_config=None)[source]¶
Disconnect the
ngroktunnel for the given URL, if open.If
ngrokis not running, calling this method will first start a process withPyngrokConfig.- Parameters:
public_url (
str) – The public URL of the tunnel to disconnect.pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.
- Return type:
- pyngrok.ngrok.get_tunnels(pyngrok_config=None)[source]¶
Get a list of active
ngroktunnels for the given config’sngrok_path.If
ngrokis not installed atPyngrokConfig’sngrok_path, calling this method will first download and installngrok.If
ngrokis not running, calling this method will first start a process withPyngrokConfig.- Parameters:
pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.- Return type:
- Returns:
The active
ngroktunnels.- Raises:
PyngrokError: When the response was invalid or does not containpublic_url.
- pyngrok.ngrok.kill(pyngrok_config=None)[source]¶
Terminate the
ngrokprocesses, if running, for the given config’sngrok_path. This method will not block, it will just issue a kill request.- Parameters:
pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.- Return type:
- pyngrok.ngrok.api(*args, pyngrok_config=None)[source]¶
Run a
ngrokcommand against theapiwith the given args. This will use the local agent to run a remote API request forngrok, which requires that an API key has been set. For a list of available commands, pass"--help".- Parameters:
pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.args (
Any) – The args to pass to theapicommand.
- Return type:
- Returns:
The response from executing the
apicommand.- Raises:
PyngrokNgrokError The
ngrokprocess exited with an error.- Raises:
CalledProcessError An error occurred while executing the process.
- pyngrok.ngrok.get_version(pyngrok_config=None)[source]¶
Get a tuple with the
ngrokandpyngrokversions.- Parameters:
pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.- Return type:
- Returns:
A tuple of
(ngrok_version, pyngrok_version).
- pyngrok.ngrok.update(pyngrok_config=None)[source]¶
Update
ngrokfor the given config’sngrok_path, if an update is available.- Parameters:
pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.- Return type:
- Returns:
The result from the
ngrokupdate.
- 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
ngroktunnels: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
ngrokAPI 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:
- Return type:
- Returns:
The response from the request.
- Raises:
PyngrokSecurityError: When theurlis 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
ngrokis installed at the default path, then callrun_process.This method is meant for interacting with
ngrokfrom the command line and is not necessarily compatible with non-blocking API methods. For that, usengrok’s interface methods (likeconnect), or useget_process.- Parameters:
args (
Optional[List[str]]) – Arguments to be passed to thengrokprocess.pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.
- Return type:
- pyngrok.ngrok.main()[source]¶
Entry point for the package’s
console_scripts. This initializes a call from the command line and invokesrun.This method is meant for interacting with
ngrokfrom the command line and is not necessarily compatible with non-blocking API methods. For that, usengrok’s interface methods (likeconnect), or useget_process.- Return type:
Process Management¶
- class pyngrok.process.NgrokProcess(proc, pyngrok_config)[source]¶
Bases:
objectAn object containing information about the
ngrokprocess.-
pyngrok_config:
PyngrokConfig¶ The
pyngrokconfiguration to use withngrok.
- _log_startup_line(line)[source]¶
Parse the given startup log line and use it to manage the startup state of the
ngrokprocess.
- _log_line(line)[source]¶
Parse, log, and emit (if
log_event_callbackinPyngrokConfigis registered) the given log line.
- healthy()[source]¶
Check whether the
ngrokprocess has finished starting up and is in a running, healthy state.- Return type:
- Returns:
Trueif thengrokprocess is started, running, and healthy.- Raises:
PyngrokSecurityError: When theurlis not supported.
- start_monitor_thread()[source]¶
Start a thread that will monitor the
ngrokprocess and its logs until it completes.If a monitor thread is already running, nothing will be done.
- Return type:
- stop_monitor_thread()[source]¶
Set the monitor thread to stop monitoring the
ngrokprocess 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
ngrokprocess itself, onlypyngrok’s monitor of the process and its logs.- Return type:
-
pyngrok_config:
- pyngrok.process.set_auth_token(pyngrok_config, token)[source]¶
Set the
ngrokauth token in the config file to streamline access to more features (for instance, multiple concurrent tunnels, custom domains, etc.).- Parameters:
pyngrok_config (
PyngrokConfig) – Thepyngrokconfiguration to use when interacting with thengrokbinary.token (
str) – The auth token to set.
- Raises:
PyngrokError: When thengrok_versionis not supported.- Raises:
PyngrokNgrokError: Whenngrokcould not start.- Return type:
- pyngrok.process.set_api_key(pyngrok_config, key)[source]¶
Set the
ngrokAPI key in the config file to enable access to more features (for instance, Internal Endpoints).- Parameters:
pyngrok_config (
PyngrokConfig) – Thepyngrokconfiguration to use when interacting with thengrokbinary.key (
str) – The API key to set.
- Raises:
PyngrokError: When thengrok_versionis not supported.- Raises:
PyngrokNgrokError: Whenngrokcould not start.- Return type:
- pyngrok.process.is_process_running(ngrok_path)[source]¶
Check if the
ngrokprocess is currently running.
- pyngrok.process.get_process(pyngrok_config)[source]¶
Get the current
ngrokprocess for the given config’sngrok_path.If
ngrokis not running, calling this method will first start a process withPyngrokConfig.- Parameters:
pyngrok_config (
PyngrokConfig) – Thepyngrokconfiguration to use when interacting with thengrokbinary.- Return type:
- Returns:
The
ngrokprocess.
- pyngrok.process.kill_process(ngrok_path)[source]¶
Terminate the
ngrokprocesses, if running, for the given path. This method will not block, it will just issue a kill request.
- pyngrok.process.run_process(ngrok_path, args)[source]¶
Start a blocking
ngrokprocess with the binary at the given path and the passed args.This method is meant for invoking
ngrokdirectly (for instance, from the command line) and is not necessarily compatible with non-blocking API methods. For that, useget_process.
- pyngrok.process.capture_run_process(ngrok_path, args)[source]¶
Start a blocking
ngrokprocess 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
ngrokdirectly (for instance, for API requests) and is not necessarily compatible with non-blocking API methods or interacting with active tunnels. For that, useget_process.- Parameters:
- Return type:
- Returns:
The output from the process.
- Raises:
PyngrokNgrokError The
ngrokprocess exited with an error.- Raises:
CalledProcessError An error occurred while executing the process.
- pyngrok.process._validate_path(ngrok_path)[source]¶
Validate the given path exists, is a
ngrokbinary, and is ready to be started, otherwise raise a relevant exception.- Parameters:
ngrok_path (
str) – The path to thengrokbinary.- Raises:
PyngrokNgrokError: Whenngrokcould not start.- Return type:
- pyngrok.process._start_process(pyngrok_config)[source]¶
Start a
ngrokprocess with no tunnels. This will start thengrokweb interface, against which HTTP requests can be made to create, interact with, and destroy tunnels.- Parameters:
pyngrok_config (
PyngrokConfig) – Thepyngrokconfiguration to use when interacting with thengrokbinary.- Return type:
- Returns:
The
ngrokprocess.- Raises:
PyngrokNgrokError: Whenngrokcould 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='3', api_key=None, config_version='2')[source]¶
Bases:
objectAn object containing
pyngrok’s configuration for interacting with thengrokbinary. All values are optional when it is instantiated, and default values will be used for parameters not passed.Use
get_defaultandset_defaultto interact with the defaultpyngrok_config, or pass another instance of this object as thepyngrok_configkeyword arg to most methods in thengrokmodule to override the default.from pyngrok import conf, ngrok # Here you update the entire default config pyngrok_config = conf.PyngrokConfig(ngrok_path="/usr/local/bin/ngrok") conf.set_default(pyngrok_config) # Here you update just one variable in the default config conf.get_default().ngrok_path = "/usr/local/bin/ngrok" # Here you 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
ngrokbinary, defaults to being placed in the same directory as ngrok’s configs.
-
auth_token:
Optional[str]¶ A
ngrokauthtoken to pass to commands (overrides what is in the config). If a value is not passed, will attempt to use the environment variableNGROK_AUTHTOKENif it is set.
-
monitor_thread:
bool¶ Whether
ngrokshould 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
ngrokemits a log. The function should take one argument of typestr.monitor_threadmust be set toTrueor the function will stop being called afterngrokfinishes starting.
-
max_logs:
int¶ The max number of logs to store in
NgrokProcess’slogsvariable.
-
start_new_session:
bool¶ Passed to
subprocess.Popenwhen launchingngrok. (Python 3 and POSIX only).
-
ngrok_version:
str¶ The major version of
ngrokinstalled. The only version currently supported is3.
- config_version¶
The
ngrokconfig version.
-
ngrok_path:
- pyngrok.conf.get_default()[source]¶
Get the default config to be used with methods in the
ngrokmodule. To override the default individually, thepyngrok_configkeyword arg can also be passed to most of these methods, or set a new default config withset_default.- Return type:
- Returns:
The default
pyngrok_config.
- pyngrok.conf.set_default(pyngrok_config)[source]¶
Set a new default config to be used with methods in the
ngrokmodule. To override the default individually, thepyngrok_configkeyword arg can also be passed to most of these methods.- Parameters:
pyngrok_config (
PyngrokConfig) – The newpyngrok_configto be used by default.- Return type:
- pyngrok.conf.get_config_path(pyngrok_config)[source]¶
Return the
config_pathif set on the givenpyngrok_configg, otherwise returnngrok’s default path.- Parameters:
pyngrok_config (
PyngrokConfig) – Thepyngrokconfiguration to first check for aconfig_path.- Return type:
- Returns:
The path to the config file.
Agent Interface¶
- class pyngrok.agent.NgrokAgent(data)[source]¶
Bases:
objectAn object containing information about a
ngrokagent.
- class pyngrok.agent.CapturedRequest(data)[source]¶
Bases:
objectAn object containing a Captured Request from a
ngroktunnel.
- pyngrok.agent.get_agent_status(pyngrok_config=None)[source]¶
Get the
ngrokagent status.If
ngrokis not installed atPyngrokConfig’sngrok_path, calling this method will first download and installngrok.If
ngrokis not running, calling this method will first start a process withPyngrokConfig.- Parameters:
pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.- Return type:
- Returns:
The requests made to the tunnels.
- pyngrok.agent.get_requests(tunnel_name=None, pyngrok_config=None)[source]¶
Get the list of requests made to either all tunnels, or the given tunnel name.
If
ngrokis not installed atPyngrokConfig’sngrok_path, calling this method will first download and installngrok.If
ngrokis not running, calling this method will first start a process withPyngrokConfig.- Parameters:
pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.
- Return type:
- Returns:
The requests made to the tunnels.
- pyngrok.agent.get_request(request_id, pyngrok_config=None)[source]¶
Get the given request made.
If
ngrokis not installed atPyngrokConfig’sngrok_path, calling this method will first download and installngrok.If
ngrokis not running, calling this method will first start a process withPyngrokConfig.- Parameters:
request_id (
str) – The ID of the request to fetch.pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.
- Return type:
- Returns:
The request made to the tunnel.
- pyngrok.agent.replay_request(request_id, tunnel_name=None, pyngrok_config=None)[source]¶
Replay a given request through its original tunnel, or through a different given tunnel.
If
ngrokis not installed atPyngrokConfig’sngrok_path, calling this method will first download and installngrok.If
ngrokis not running, calling this method will first start a process withPyngrokConfig.- Parameters:
request_id (
str) – The request ID.tunnel_name (
Optional[str]) – The name of tunnel to replay the request through.pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.
- Return type:
- pyngrok.agent.delete_requests(pyngrok_config=None)[source]¶
Delete request history.
If
ngrokis not installed atPyngrokConfig’sngrok_path, calling this method will first download and installngrok.If
ngrokis not running, calling this method will first start a process withPyngrokConfig.- Parameters:
pyngrok_config (
Optional[PyngrokConfig]) – Apyngrokconfiguration to use when interacting with thengrokbinary, overridingget_default.- Return type:
ngrok Installer¶
- pyngrok.installer.get_default_ngrok_dir()[source]¶
Get the default
ngrokdirectory for the current system.- Return type:
- Returns:
The default
ngrokdirectory.
- pyngrok.installer.get_system()[source]¶
Parse the name of the OS from the system and return a friendly name.
- Return type:
- Returns:
The friendly name of the OS.
- Raises:
PyngrokNgrokInstallError: When the platform is not supported.
- pyngrok.installer.get_arch()[source]¶
Get the architecture of the current system. This will be
i386for 32-bit systems,x86_64for 64-bit systems, and have_armappended for ARM systems. Special architectures like s390x and ppc64le will be returned as-is.- Return type:
- Returns:
The name of the architecture.
- pyngrok.installer.get_ngrok_bin()[source]¶
Get the
ngrokexecutable for the current system.- Return type:
- Returns:
The name of the
ngrokexecutable.- Raises:
PyngrokNgrokInstallError: When the platform is not supported.
- pyngrok.installer.get_ngrok_cdn_url(ngrok_version)[source]¶
Determine the
ngrokCDN URL for the current OS and architecture.
- pyngrok.installer.install_ngrok(ngrok_path, ngrok_version='3', **kwargs)[source]¶
Download and install the latest
ngrokfor the current system, overwriting any existing contents at the given path.- Parameters:
ngrok_path (
str) – The path to where thengrokbinary will be downloaded.ngrok_version (
Optional[str]) – The major version ofngrokto be installed.kwargs (
Any) – Remainingkwargswill be passed to_download_file.
- Raises:
PyngrokError: When thengrok_versionis not supported.- Raises:
PyngrokNgrokInstallError: When an error occurs installingngrok.- Return type:
- pyngrok.installer._install_ngrok_archive(ngrok_path, archive_path)[source]¶
Extract the
ngrokarchive to the given path. Supports both.zipand.tgzarchives.
- pyngrok.installer.get_ngrok_config(config_path, use_cache=True, ngrok_version='3', config_version='2')[source]¶
Get the
ngrokconfig from the given path.- Parameters:
- Return type:
- Returns:
The
ngrokconfig.
- pyngrok.installer.get_default_config(ngrok_version, config_version)[source]¶
Get the default config params for the given major version of
ngrokand config version.
- pyngrok.installer.install_default_config(config_path, data=None, ngrok_version='3', config_version='2')[source]¶
Install the given data to the
ngrokconfig. 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 withpyngrok.- Parameters:
- Return type:
- pyngrok.installer.validate_config(data)[source]¶
Validate that the given dict of config items are valid for
ngrokandpyngrok.- 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:
- 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) – Remainingkwargswill be passed tourllib.request.urlopen.
- Return type:
- Returns:
The path to the downloaded temporary file.
- Raises:
PyngrokSecurityError: When theurlis not supported.- Raises:
PyngrokNgrokInstallError: When an error occurs downloadingngrok.
Logging¶
Exceptions¶
- exception pyngrok.exception.PyngrokError[source]¶
Bases:
ExceptionRaised when a general
pyngrokerror has occurred.
- exception pyngrok.exception.PyngrokSecurityError[source]¶
Bases:
PyngrokErrorRaised when a
pyngroksecurity error has occurred.
- exception pyngrok.exception.PyngrokNgrokInstallError[source]¶
Bases:
PyngrokErrorRaised when an error has occurred while downloading and installing the
ngrokbinary.
- exception pyngrok.exception.PyngrokNgrokError(error, ngrok_logs=None, ngrok_error=None)[source]¶
Bases:
PyngrokErrorRaised when an error occurs interacting directly with the
ngrokbinary.
- exception pyngrok.exception.PyngrokNgrokHTTPError(error, url, status_code, message, headers, body)[source]¶
Bases:
PyngrokNgrokErrorRaised when an error occurs making a request to the
ngrokweb interface. Thebodycontains the error response received fromngrok.
- exception pyngrok.exception.PyngrokNgrokURLError(error, reason)[source]¶
Bases:
PyngrokNgrokErrorRaised when an error occurs when trying to initiate an API request.