> ## 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.

# Python SDK Quickstart

> Learn how to get started with the ngrok Python SDK to create secure tunnels from your Python applications to the internet.

<Prompt description="Give this to your AI coding agent to complete the full quickstart automatically." actions={["copy", "cursor"]}>
  Complete the ngrok Python SDK quickstart:

  1. Create `service.py` — a Python HTTP server on port 8080 that returns an HTML page saying "Hello from Python HTTP Server!"
  2. Install dependencies: `pip install ngrok python-dotenv`
  3. Create a `.env` file with NGROK\_AUTHTOKEN and NGROK\_DOMAIN — ask me for these values
  4. Create `endpoint.py` using `ngrok.forward()` to tunnel port 8080 to my reserved domain with a Google OAuth traffic policy
  5. Run `python service.py` in one terminal and `python endpoint.py` in another
  6. Confirm the tunnel URL is printed and that visiting it requires a Google login

  Ask me for my auth token and reserved domain before starting.
</Prompt>

[The ngrok Python SDK](https://ngrok.github.io/ngrok-python/index.html) is an open-source package that enables you to quickly and efficiently serve Python applications on the internet without the need to configure low-level network primitives like IPs, certificates, load balancers, or ports.
You can think of it as the [ngrok Agent CLI](/getting-started/) packaged as a Python library.

This quickstart uses the ngrok Python SDK to create an Agent Endpoint that forwards traffic from the internet to a Python app running on your local device, then secure it by requiring visitors to log in with a Google account to access it.

<Info>
  If you'd prefer to skip the boilerplate setup, you can clone the complete example from the [ngrok-samples collection](https://github.com/ngrok-samples/python-quickstart).
  In that case, you'll just need to reserve a domain and add your auth token as described below to get started.
</Info>

## What you'll need

* An [ngrok account](https://dashboard.ngrok.com/signup).
* Your [ngrok auth token](https://dashboard.ngrok.com/get-started/your-authtoken).
* [Python installed](https://www.python.org/downloads/) on your machine. You can check this by running `python -v` in your terminal.

## 1. Start your app or service

Start up the app or service you'd like to put online.
This is the app that your Agent Endpoint will forward online traffic to.

If you don't have an app to work with, you can create a minimal Python app using the following code to set up a basic HTTP server at port `8080`.

```python title="service.py" theme={null}
from http.server import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        html = b"""
        <html>
        <head><title>Test Page</title></head>
        <body><h1>Hello from Python HTTP Server!</h1></body>
        </html>
        """
        self.wfile.write(html)

def run(server_class=HTTPServer, handler_class=MyHandler, port=8080):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f"Serving custom HTML at http://localhost:{port}")
    httpd.serve_forever()

if __name__ == "__main__":
    run()
```

Navigate to the directory where this file is located and run the following command to start the server:

```bash theme={null}
python service.py
```

## 2. Install the Python SDK

Open a new terminal, then run the following terminal command to install the Python SDK:

```bash theme={null}
pip install ngrok
```

## 3. Create a .env file

Create a `.env` file and add [your ngrok auth token](https://dashboard.ngrok.com/get-started/your-authtoken) and reserved domain to it.
This file needs to be in the same directory where you'll put the script using ngrok's Python SDK.
The following terminal commands will create this directory, navigate into it, and add the `.env` file there:

```bash theme={null}
mkdir ngrok-python-demo && cd ngrok-python-demo
touch .env
```

Add your ngrok auth token and reserved domain to this file:

```txt title=".env" theme={null}
NGROK_AUTHTOKEN=your_actual_auth_token_here
NGROK_DOMAIN=your_actual_domain_here
```

Finally, you'll need to install [the `python-dotenv` package](https://pypi.org/project/python-dotenv/) to access your environment variable from your code.

```bash theme={null}
pip install python-dotenv
```

<Tip>
  If you don't want to use a `.env` file, you can instead [export your auth token as an environment variable](https://support.apple.com/en-il/guide/terminal/apd382cc5fa-4f58-4449-b20a-41c53c006f8f/mac) in your terminal session, or [call `ngrok.set_auth_token("your-token")`](https://ngrok.github.io/ngrok-python/index.html#authentication) in your code.

  You can set your reserved domain directly in your endpoint file below.
</Tip>

## 4. Create your endpoint

Create your Agent Endpoint, which will forward public traffic to your app.

Create a new file named `endpoint.py` in the same directory as your `.env` file and add the following code.
This example:

* Starts an Agent Endpoint that forwards from your reserved domain to your service running on port `8080`.
* Secures the endpoint with a Traffic Policy that requires authentication via Google OAuth.

<Note>
  This example uses ngrok's default Google OAuth application.
  To use your own, see [the OAuth Traffic Policy Action documentation](/traffic-policy/actions/oauth/#google-example).
</Note>

```python title="endpoint.py" theme={null}
from dotenv import load_dotenv
import os
import ngrok
import time

load_dotenv()

listener = ngrok.forward(
	# The port your app is running on.
  8080,
  authtoken=os.getenv("NGROK_AUTHTOKEN"),
  domain=os.getenv("NGROK_DOMAIN"),
	# Secure your endpoint with a Traffic Policy.
	# This could also be a path to a Traffic Policy file.
  traffic_policy='{"on_http_request": [{"actions": [{"type": "oauth","config": {"provider": "google"}}]}]}'
)

# Output ngrok URL to console
print(f"Ingress established at {listener.url()}")

# Keep the listener alive
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print("Closing listener")
```

## 5. Test your endpoint

Test your endpoint by running the following terminal command:

```bash theme={null}
python endpoint.py
```

This should print your reserved domain URL to the terminal.
When you visit the URL, you should be prompted to log in with Google.
After logging in, you'll see your app or service.

If you used the example app in this quickstart, you'll see **"Hello from Python HTTP Server!"** displayed in your browser.

## What's next?

In this guide, you learned how to use the Python SDK to an create Agent Endpoint that forwards traffic to your localhost.
You saw one way to implement a Traffic Policy directly in your codebase, including an action that adds authentication to your app with no configuration required.
What else can you do with these features?

* Dig deeper into [Traffic Policies](/traffic-policy/), which enable you to [grant conditional access](/traffic-policy/examples/add-authentication/#conditional-access-using-oauth-variables), [send custom headers](/traffic-policy/actions/add-headers/#examples), [rewrite URLs](/traffic-policy/actions/url-rewrite/#examples), and more with your endpoints.
* Learn more about the [Agent SDKs](/agent-sdks/) to understand how the Python SDK works under the hood.
* Read [the full Python SDK documentation](https://ngrok.github.io/ngrok-python/) for more code examples.
* If your use case calls for a centrally managed, always-on endpoint, instead of one that's only available when an agent is running, you should proceed to [getting started with Cloud Endpoints](/getting-started/cloud-endpoints-quickstart/).
