# FastAPI

> Embed the Muzekit editor in FastAPI: an async route with your auth dependency opens the session through httpx.

<Callout title="Let your coding agent do it">Connect Claude Code, Cursor or Codex to the [MCP server](/docs/mcp#set-up-the-editor-in-your-app) and ask: "Set up the Muzekit editor in this FastAPI app." It writes these same files.</Callout>

## How it works in FastAPI

The `current_user` dependency is whatever you already use: OAuth2 with JWT, fastapi-users or a session cookie. Return a dict and FastAPI serializes it. When FastAPI also serves the page, render it with `Jinja2Templates`; when your front end is a separate app, take the component from the React or Vue example.

## 1. Add your secret key

[Create an editor](/signup) and copy its Test key (`mk_test_…`) from **API keys** in the dashboard. Put it in `.env` on your server:

```bash tab=".env"
MUZEKIT_SECRET_KEY=mk_test_…
```

<Screenshot src="/docs/1-embed-code.webp" original="/docs/raw/1-embed-code.png" alt="The Embed code page in the Muzekit dashboard: the Test key for the server, then the session route and mount code" />

## 2. Open a session on your server

Opens a session for the signed-in user, in `app.py (or your routes module)`:

```python tab="app.py (or your routes module)"
import os, httpx
from fastapi import Depends, HTTPException

@app.post("/api/muzekit-session")
async def muzekit_session(user=Depends(current_user)):  # Your signed-in user: replace with your own auth
    if not user:
        raise HTTPException(401)
    async with httpx.AsyncClient(timeout=15) as client:
        res = await client.post("https://api.muzekit.com/v1/sessions",
            headers={"Authorization": f"Bearer {os.environ['MUZEKIT_SECRET_KEY']}"},
            json={"user": {"id": str(user.id), "name": user.name, "email": user.email}, "mode": "design"})
    res.raise_for_status()
    return {"client_secret": res.json()["client_secret"]}
```

## 3. Mount the editor

The editor, in `templates/editor.html`:

```html tab="templates/editor.html"
<div id="muzekit-editor" style="height: 720px"></div>
<script src="https://muzekit.com/sdk/v1.js"></script>
<script>
  const editor = Muzekit.mount("#muzekit-editor", {
    fetchClientSecret: () =>
      fetch("/api/muzekit-session", { method: "POST" })
        .then((r) => r.json())
        .then((s) => s.client_secret),
    on: {
      ready: () => console.log("Muzekit editor ready"),
      save: (e) => console.log("Saved", e.template, e.revision),
      error: (e) => console.error("Muzekit", e.code, e.message),
    },
  });
</script>
```

## 4. Run it

```bash
fastapi dev main.py
```

Sign in, then open `http://127.0.0.1:8000/editor`. The editor loads in its container and the first session shows on your dashboard's Home. With a Test key, sessions on `localhost` and `127.0.0.1` are free.

## Common problems

### CORS with a separate front end

Add `CORSMiddleware` with your front end's origin and `allow_credentials=True`, or proxy `/api` through the front end's dev server.

### No module named httpx

Run `pip install httpx`.

### A client per request

Under load, create one `httpx.AsyncClient` in the app's lifespan and reuse it.

## Notes

- Secret key: MUZEKIT_SECRET_KEY goes in .env (or your secret store) on the server only. Never in browser code, never committed.
- Every user.id is your own id for that person: their designs and uploads follow it across sessions.
- mode: "design" opens the full editor; "fill" opens a form over a template (send template: "`<key or tpl_ id>`" too).
- Give the container a real height: the editor fills it.

## Deploy and go live

Set `MUZEKIT_SECRET_KEY` for Uvicorn or Gunicorn workers: Docker `ENV`, or Railway and Render variables. pydantic-settings can read it into your settings object.

Then make a Live key (`mk_live_…`), add your domain to Live under [Allowed domains](/docs/allowed-domains) and use **Copy to Live** for your templates, look and features.

## Questions

### Can it be a plain def route?

Yes: with `requests` in a regular `def`, FastAPI runs it in a thread pool.

<Cards>
  <Card title="Editor modes" description="Design, fill-in and view, and what each shows." href="/docs/editor-modes" />
  <Card title="Browser SDK" description="Events, saving from your own button, and destroy." href="/docs/embed-sdk" />
</Cards>
