> ## Documentation Index
> Fetch the complete documentation index at: https://ngrok.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Using ngrok with FastAPI

> Learn how to embed ngrok into FastAPI applications using the ngrok-python library for secure ingress.

This guide shows you how to embed the ngrok agent into FastAPI applications using the [ngrok-python](https://github.com/ngrok/ngrok-python) library.
It covers setting up a FastAPI application with ngrok integration for secure ingress.

<Warning>
  ngrok-python and FastAPI libraries used in this example are sensitive to versions.
  Use of Virtual Environments is highly recommended.
</Warning>

## What you'll need

* Python installed on your machine.
* An [ngrok account](https://dashboard.ngrok.com/signup).
* Your [ngrok authtoken](https://dashboard.ngrok.com/get-started/your-authtoken).

## 1. Install dependencies

Create a `requirements.txt` file with the following dependencies:

```sh theme={null}
# requirements.txt
ngrok==1.4.0
uvicorn==0.29.0
fastapi==0.111.0
loguru==0.7.2
```

Install the dependencies:

```sh theme={null}
pip install -r requirements.txt
```

## 2. Create the FastAPI application

Create a `main.py` file with the following code:

```python theme={null}
# 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)
```
