# Flask

> Embed the Muzekit editor in Flask: an @app.post route opens the session with requests, and a Jinja template mounts the editor.

<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 Flask app." It writes these same files.</Callout>

## How it works in Flask

Flask-Login's `current_user`, or your own lookup from `session`, gives the signed-in user. `requests.post(..., json=...)` sets the JSON header for you, and `raise_for_status` turns a Muzekit error into an exception you can log. In a blueprint, use `@bp.post` with the same body.

## 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, requests
from flask import jsonify, abort

@app.post("/api/muzekit-session")
def muzekit_session():
    user = current_user()  # Your signed-in user: replace with your own auth
    if not user:
        abort(401)
    res = requests.post("https://api.muzekit.com/v1/sessions", timeout=15,
        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 jsonify(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
flask --app app run --debug
```

Sign in, then open `http://127.0.0.1:5000/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

### Flask-WTF rejects the POST

CSRFProtect checks every POST: send `csrf_token()` from the template in an `X-CSRFToken` header, or exempt this route with `@csrf.exempt`, since a page on another site can't read its answer.

### current_user is anonymous

Add `@login_required` from Flask-Login above the route.

### No module named requests

Run `pip install requests`: it isn't part of Flask.

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

With Gunicorn behind Nginx, set the key in the systemd unit or your container's environment. Locally, python-dotenv lets `flask run` read it from a file.

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

### Should the route be async?

Flask 2 supports `async def` views, but `requests` is synchronous, and one call per editor open doesn't need it.

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