Skip to content

Commit

Permalink
Configure mounts dispatch app
Browse files Browse the repository at this point in the history
  • Loading branch information
pelletier committed Jan 29, 2024
1 parent c5d4ded commit 601f438
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
39 changes: 36 additions & 3 deletions src/dispatch/fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,42 @@
"""

import os
import fastapi
from fastapi.responses import PlainTextResponse


def configure(app: fastapi.FastAPI):
"""Configure the FastAPI app to use Dispatch programmable endpoints."""
...
def configure(
app: fastapi.FastAPI,
api_key: None | str = None,
api_url: str = "https://api.stealthrocket.cloud",
mount_path: str = "/dispatch",
):
"""Configure the FastAPI app to use Dispatch programmable endpoints.
Args:
app: The FastAPI app to configure.
api_key: Dispatch API key to use for authentication. Uses the value of
the DISPATCH_API_KEY environment variable by default.
api_url: URL of the Dispatch service.
mount_path: The path to mount Dispatch programmable endpoints at.
"""
api_key = api_key or os.environ.get("DISPATCH_API_KEY")
api_url = api_url or "https://api.stealthrocket.cloud"

if not app:
raise ValueError("app is required")
if not api_key:
raise ValueError("api_key is required")
if not api_url:
raise ValueError("api_url is required")
if not mount_path:
raise ValueError("mount_path is required")

dispatch_app = fastapi.FastAPI()

@dispatch_app.get("/", response_class=PlainTextResponse)
def read_root():
return "ok"

app.mount(mount_path, dispatch_app)
9 changes: 8 additions & 1 deletion tests/test_fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,19 @@ class TestFastAPI(unittest.TestCase):
def test_fastapi(self):
app = fastapi.FastAPI()

dispatch.fastapi.configure(app)
dispatch.fastapi.configure(app, api_key="test-key")

@app.get("/")
def read_root():
return {"Hello": "World"}

client = TestClient(app)

# Ensure existing routes are still working.
resp = client.get("/")
self.assertEqual(resp.status_code, 200)

# Ensure Dispatch root is working.
resp = client.get("/dispatch/")
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.text, "ok")

0 comments on commit 601f438

Please sign in to comment.