This guide shows you how to embed the ngrok agent into FastAPI applications using the ngrok-python library.
It covers setting up a FastAPI application with ngrok integration for secure ingress.
ngrok-python and FastAPI libraries used in this example are sensitive to versions.
Use of Virtual Environments is highly recommended.
What you’ll need
1. Install dependencies
Create a requirements.txt file with the following dependencies:
# requirements.txt
ngrok==1.4.0
uvicorn==0.29.0
fastapi==0.111.0
loguru==0.7.2
Install the dependencies:
pip install -r requirements.txt
2. Create the FastAPI application
Create a main.py file with the following code:
# main.py
from contextlib import asynccontextmanager
from os import getenv
import ngrok
import uvicorn
from fastapi import FastAPI
from loguru import logger
NGROK_AUTH_TOKEN = getenv("NGROK_AUTH_TOKEN", "")
APPLICATION_PORT = 5000
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Setting up ngrok Endpoint")
ngrok.set_auth_token(NGROK_AUTH_TOKEN)
ngrok.forward(
addr=APPLICATION_PORT,
)
yield
logger.info("Tearing Down ngrok Endpoint")
ngrok.disconnect()
app = FastAPI(lifespan=lifespan)
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=APPLICATION_PORT, reload=True)