---
name: fastapi-server
description: Scaffold and run a minimal FastAPI server inside the dev container on port 8888. Use when the user asks for a Python web API, REST endpoints, or to expose something over HTTP.
---

# FastAPI Server

Follow these steps in order. Use `ToolRunCommandInDevContainer` for shell commands and `ToolUpsertFile` for file contents.

## 1. Install dependencies

```bash
pip install --quiet fastapi 'uvicorn[standard]'
```

## 2. Write the app

Create `/app/main.py` with `ToolUpsertFile`:

```python
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def root():
    return {"status": "ok"}


@app.get("/health")
def health():
    return {"healthy": True}
```

Add additional routes the user requested before moving on.

## 3. Run the server (non-blocking)

The dev container is interactive, so the server must run detached or it will
block the tool call. Use `tmux` so it survives the exec:

```bash
apt-get update -qq && apt-get install -y -qq tmux
tmux kill-session -t api 2>/dev/null || true
tmux new-session -d -s api "cd /app && uvicorn main:app --host 0.0.0.0 --port 8888"
```

## 4. Verify it's reachable

Give the server a second to bind, then probe it from inside the container:

```bash
sleep 1 && curl -sf http://localhost:8888/health
```

If the curl succeeds, tell the user the server is live at `http://localhost:8888`
(the host port mapping is already configured in `clients.py`/`tools.py`).

## 5. Iterating

To change routes, update `/app/main.py` with `ToolUpsertFile`, then reload by
restarting the tmux session:

```bash
tmux kill-session -t api && tmux new-session -d -s api "cd /app && uvicorn main:app --host 0.0.0.0 --port 8888"
```

## Notes

- Never run `uvicorn` in the foreground from a tool call — it will hang.
- Do not bind to `127.0.0.1`; the host port mapping needs `0.0.0.0`.
- If the user wants auto-reload during development, add `--reload` to the
  uvicorn command inside the tmux session.
