Categories
Data Engineering

How to setup ngrok tunnel for API running in Colab notebook

ngrok is a tool that allows you to expose your local development server to the internet, making it accessible from anywhere. In this article, we’ll walk you through the steps to set up an ngrok tunnel for an API running in a Colab notebook.

Here are the steps:

Step 1. Create an ngrok account

To get started, create an ngrok account by signing up on the ngrok dashboard

You’ll need to set up multi-factor authentication (MFA) using an authenticator app like Google Authenticator. When you’ve done this, use the code from the authenticator app to log in to ngrok.

Make sure to save your recovery codes in a safe place.

Complete the description form on the Welcome to ngrok page.

Step 2. Create and save your ngrok authtoken

Create and save your ngrok authtoken. You’ll need this token to authenticate with ngrok in your Colab notebook.

Step 3: Run ngrok and Open Tunnel

Run the following code in your Colab notebook.

!pip install pyngrok --quiet

from pyngrok import ngrok

# Terminate open tunnels if they exist

ngrok.kill()

# Set your auth token

NGROK_AUTH_TOKEN = "<your ngrok authtoken>"
ngrok.set_auth_token(NGROK_AUTH_TOKEN)

# Open an ngrok tunnel on port 5000 for application running on http://localhost:5000

public_url = ngrok.connect(port = "5000")

print("Application URL: {public_url}")

nest_asyncio.apply()

uvicorn.run(app, port = port_num)

The code does the following:

  • First, install pyngrok
  • Then terminate any open tunnels if they exist.
  • Set the auth token
  • Open an ngrok tunnel on port 5000 for application running on http://localhost:5000
  • Print the public URL of the tunnel to the console.
  • Make calls to nest_asyncio and uvicorn

Why nest_asyncio.apply()?

In Colab notebooks, the asyncio event loop is already running, which can cause issues when trying to run another asyncio-based application (like Uvicorn). nest_asyncio.apply() enables nested asyncio event loops, allowing us to run Uvicorn within the existing Colab event loop.

Why uvicorn.run(app, port=port_num)?

uvicorn.run(app, port=port_num) starts the Uvicorn server, running your API application on the specified port. This is necessary because ngrok only exposes the API to the internet; it doesn’t run the application itself. By running Uvicorn, we ensure that the API is actually running and accessible through the ngrok tunnel.

Step 4: Access the Application

Access the application running on {public_url}/index on your browser

That’s it! You’ve successfully set up an ngrok tunnel for your API running in a Colab notebook. Note: Make sure to replace <your_ngrok_authtoken> with your actual ngrok authtoken and port_num with the port number of your application.