Serve a FastAPI App through rstream Tunnels

Serve a FastAPI application directly through a published rstream tunnel with the Python SDK, protect it with edge token auth, and consume the private variant over an rstream dial, all without a local HTTP server or an open port.


This guide serves a FastAPI application directly through the rstream Python SDK. The process opens an outbound connection to the engine and handles accepted HTTP streams in-process, without a Uvicorn listener or a local reverse proxy. HTTP routes keep their FastAPI shape; the application explicitly owns startup and shutdown.

The walkthrough mirrors the C++ Boost.Beast guide for the Python ecosystem, in idiomatic async Python. It publishes the app, adds an edge token policy without touching application code, and finishes with the private variant, where the same app is reachable only through an rstream dial.

rstream examples / python-fastapi-rstream-tunnelOpen the FastAPI tunnel sample with the published, token-protected, and private modes.

What you will build

One Python process owns the whole flow. A FastAPI application defines the endpoints, the SDK creates a tunnel under the selected rstream project, and rstream.asgi.serve parses each accepted stream and dispatches it to the app in-process. The sample opens outbound connections to the Engine and runs without a loopback HTTP server.

Prerequisites

On the development machine, install the CLI and sign in with rstream login. Run rstream project list and replace my-project-endpoint below with the project's ENDPOINT. Select the same project on any machine used for the private client.

rstream project use my-project-endpoint

For an unauthenticated first request, use a project with published access set to allowed. If the project requires caller authentication, use the token path. The sample needs Python 3.10 or newer and Git. Clone it and create an isolated environment.

git clone https://github.com/rstreamlabs/rstream-examples.git
cd rstream-examples/python-fastapi-rstream-tunnel
python3 -m venv .venv
. .venv/bin/activate
python -m pip install -r requirements.txt

On Windows, use py -m venv .venv and .\.venv\Scripts\Activate.ps1 in PowerShell. Keep the environment active for the server and dial client.

The SDK package installs as rstreamlabs-rstream and is imported as rstream. The asgi extra brings the in-process HTTP bridge, and the api extra lets the client resolve the managed project endpoint, exactly like the CLI does. The broader SDK surface is documented in Python SDK.

Start from a FastAPI app

Keep the FastAPI application and its routes. Change how the app receives HTTP requests.

from fastapi import FastAPI
 
app = FastAPI(title="python-fastapi-rstream-tunnel")
 
 
@app.get("/")
async def root() -> dict[str, str]:
    return {"service": "python-fastapi-rstream-tunnel", "status": "ok"}
 
 
@app.get("/items/{item_id}")
async def read_item(item_id: int) -> dict[str, int | str]:
    return {"item_id": item_id, "source": "rstream tunnel"}

HTTP routing, dependency injection and middleware run in-process. This direct adapter handles HTTP/1.1 only; it does not dispatch ASGI lifespan or WebSocket scopes. The sample enters app.router.lifespan_context(app) before opening the tunnel. Keep shared startup resources on app.state. The adapter leaves yielded lifespan scope state and nested application lifespans to a full ASGI server. Keep Uvicorn and use local forwarding when the application needs WebSockets or another ASGI-server feature.

Create the published tunnel

The runtime side reads the CLI-compatible configuration, opens a control channel, creates a published HTTP tunnel, and hands the app to the ASGI helper.

async with (
    app.router.lifespan_context(app),
    rstream.Client.from_env() as client,
    await client.connect() as control,
):
    tunnel = await control.create_tunnel(
        name="python-fastapi-demo",
        protocol="http",
        http_version="http/1.1",
        publish=True,
        labels={"app": "python-fastapi-demo"},
    )
    print("Forwarding address:", tunnel.forwarding_address, flush=True)
    await rstream.asgi.serve(app, tunnel)

Client.from_env resolves the same selected project as the CLI, so there are no credentials in the code. create_tunnel registers the endpoint under the project, and the printed forwarding address is the public URL. rstream.asgi.serve then iterates over accepted streams, parses HTTP/1.1, and dispatches each request to the app on the running event loop, one task per stream.

Run the sample

python main.py

The process prints the forwarding address once the tunnel is created. The Engine forwards requests allowed by the project's caller policy to FastAPI.

Leave the server running. In a second terminal, set FORWARDING_URL to the complete URL beginning with https:// from the program's output.

curl -fsS "${FORWARDING_URL%/}/items/42"

On Windows PowerShell, set the same URL in $forwardingUrl and run:

curl.exe -fsS "$($forwardingUrl.TrimEnd('/'))/items/42"

Expect {"item_id":42,"source":"rstream tunnel"}.

Stopping the process closes the tunnel; restarting it creates another tunnel with the same lookup name and potentially a different forwarding address. A stable public URL needs an explicitly retained or configured hostname. The small sample does not implement automatic reconnect; a production supervisor belongs outside request handlers.

Add edge policy

Stop the published sample before restarting it with token authentication. Running the sample with --token-auth passes auth=rstream.TunnelAuth(token=True) to create_tunnel, and the edge starts requiring a valid rstream token before any request reaches the app.

python main.py --token-auth

In another terminal, use the new forwarding URL. With token authentication alone, an unauthenticated request returns 401.

curl -sS -o /dev/null -w '%{http_code}\n' "$FORWARDING_URL"

For an authorized request, set CALLER_TOKEN to a token that can access /items/42 on the new tunnel.

curl -fsS -H "Authorization: Bearer $CALLER_TOKEN" "${FORWARDING_URL%/}/items/42"

Expect the same JSON response as before. The Engine checks the credential before forwarding the request. Application-level authorization remains necessary for user, tenant and operation rules inside the app. Token formats, scopes, and the broader access model are covered in HTTP tunnel authentication and Fine-grained tokens.

Dial the private variant from Python

Use a hosted Pro or Enterprise project or a direct Engine that supports private bytestreams. Stop the token-protected sample before starting the private mode. With --private, the sample creates a private tunnel and uses only the settings relevant to native dialing. Start that mode, then run the provided client from a second terminal with the same environment and project selected:

python main.py --private
python dial_client.py --path /items/42

The app is reachable by its tunnel name. The client sends an HTTP/1.1 request and prints the response until EOF. Its exchange uses the following operations, with sys imported:

async with (
    rstream.Client.from_env() as client,
    await client.dial("python-fastapi-demo") as stream,
):
    stream.write(b"GET /items/42 HTTP/1.1\r\nHost: python-fastapi-demo\r\nConnection: close\r\n\r\n")
    await stream.drain()
    while chunk := await stream.read(4096):
        sys.stdout.buffer.write(chunk)

The dialed stream is a plain bidirectional byte stream, which is why a minimal HTTP/1.1 exchange is enough. The sample's dial_client.py accepts the tunnel name and request path as arguments. The distinction that matters is the client protocol, not the security model: published endpoints serve standard HTTP clients and can still be protected at the edge, while private tunnels serve rstream dials, as described in Private Tunnels.

Where to go next

The same SDK surface scales from one app to a distributed workload. Run Edge Vision Inference on Your Own Machines with rstream uses tunnel labels, live inventory, and real-time watches to coordinate Python processes across machines. The SDK entrypoint with the full capability table is Python SDK, and the equivalent native-server patterns exist for C++ and Next.js.