Skip to content

Instantly share code, notes, and snippets.

@alexdlaird
Last active March 5, 2024 18:22
Show Gist options
  • Save alexdlaird/1f0e45d943120d9e9cea8485773a0e4f to your computer and use it in GitHub Desktop.
Save alexdlaird/1f0e45d943120d9e9cea8485773a0e4f to your computer and use it in GitHub Desktop.
Fast API integration example for pyngrok, full documentation found at https://pyngrok.readthedocs.io/en/latest/integrations.html
# USE_NGROK=True uvicorn server:app
import os
import sys
from fastapi import FastAPI
from fastapi.logger import logger
from pydantic import BaseSettings
class Settings(BaseSettings):
# ... The rest of our FastAPI settings
BASE_URL = "http://localhost:8000"
USE_NGROK = os.environ.get("USE_NGROK", "False") == "True"
settings = Settings()
def init_webhooks(base_url):
# Update inbound traffic via APIs to use the public-facing ngrok URL
pass
# Initialize the FastAPI app for a simple web server
app = FastAPI()
if settings.USE_NGROK and os.environ.get("NGROK_AUTHTOKEN"):
# pyngrok should only ever be installed or initialized in a dev environment when this flag is set
from pyngrok import ngrok
# Get the dev server port (defaults to 8000 for Uvicorn, can be overridden with `--port`
# when starting the server
port = sys.argv[sys.argv.index("--port") + 1] if "--port" in sys.argv else "8000"
# Open a ngrok tunnel to the dev server
public_url = ngrok.connect(port)
logger.info(f"ngrok tunnel \"{public_url}\" -> \"http://127.0.0.1:{port}\")
# Update any base URLs or webhooks to use the public ngrok URL
settings.BASE_URL = public_url
init_webhooks(public_url)
# ... Initialize routers and the rest of our app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment