# Create and version an agent Source: https://docs.papermap.ai/air/agents/create-agent Bind immutable instructions, model access, approved tools, and limits into an active AIR agent version. An agent is the stable identity your application calls. An agent version is the immutable configuration AIR executes: prompt, model, tools, fallbacks, output contract, and limits. ## Build the first version Save reusable instructions under **Prompts**, or write new instructions directly in the agent composer. Use a Papermap-managed model when available, connect an OpenAI or Anthropic provider key, or use `Testing → fake-echo` for a zero-credential staging smoke test. Open **Advanced — fallback models, tools, output, and limits** and add only tools this version should call. Project-level enablement does not grant an agent access automatically. Leave **Output schema** blank for free-form text, or provide an object-rooted JSON Schema when your application needs predictable fields. Select **Activate immediately** for a new agent, or create an inactive version when you want to test before moving serving traffic. AIR agent composer showing the selected prompt and testing model ## Return structured output Add a JSON Schema under **Advanced → Output schema** when downstream code needs a stable response contract. The schema must declare an object at the root. ```json theme={null} { "type": "object", "properties": { "answer": { "type": "string" }, "needs_human_review": { "type": "boolean" } }, "required": ["answer", "needs_human_review"], "additionalProperties": false } ``` AIR sends the schema to supported model providers and validates the final model response again before completing the run. A successful run stores the parsed object directly: ```json theme={null} { "answer": "Order 1042 is scheduled for delivery tomorrow.", "needs_human_review": false } ``` If the final response is not valid JSON or does not match the schema, AIR marks the run as `failed` and does not publish a successful final output. The raw model response remains available in the run trace for debugging. Without an output schema, AIR preserves the existing free-form response shape with the model response under the `text` field. ## Test before integrating The **Try it** panel creates a real run using the selected agent version. Open the resulting trace to verify the exact configuration and model behavior. AIR agent page showing an active version and successful test transcript ## Change an agent safely Create a new version whenever you change instructions, model, allowed tools, output schema, or limits. Test it, then activate it. Existing runs remain tied to the version with which they started; new runs use the active version. Do not edit production behavior in place. Version first, test the version, and then move serving traffic. # Create and manage runs Source: https://docs.papermap.ai/air/applications/create-runs Start, stream, inspect, wait for, and cancel AIR runs from an application. Install the Python SDK and use a project-scoped app key: ```bash theme={null} python -m pip install papermap-air export AIR_BASE_URL="https://dev.airapi.papermap.ai" export AIR_APP_KEY="" ``` ## Create and wait ```python theme={null} import asyncio import os from air import AirClient async def main() -> None: async with AirClient( os.environ["AIR_BASE_URL"], os.environ["AIR_APP_KEY"], ) as client: run = await client.runs.create( agent_id="support-agent", input={"message": "Where is order 1042?"}, context={"tenant_id": "acme"}, webhook_url="https://example.com/hooks/air", ) result = await client.runs.wait( run.id, timeout=120, poll_interval=0.5, ) print(result.status, result.output) asyncio.run(main()) ``` `input` is the task sent to the agent. `context` carries trusted application data such as a tenant ID; AIR passes it to tools that declare a `context` parameter. `webhook_url` is optional. ## Consume structured output When the active agent version has an output schema, `Run.output` is the parsed, validated object described by that schema: ```python theme={null} result = await client.runs.wait(run.id, timeout=120) if result.status == "failed": raise RuntimeError(result.error) answer = result.output["answer"] needs_review = result.output["needs_human_review"] ``` When the agent version has no output schema, the response remains free-form text and is returned as `result.output["text"]`. Treat a terminal `Run.output` or `run_succeeded` event as authoritative. Streaming model deltas are provisional text; for structured runs they contain the JSON response while it is still being generated and has not yet passed final validation. ## Stream output as it is generated Use `stream()` when a UI or CLI should show the model response before the run finishes: ```python theme={null} run = await client.runs.create( agent_id="support-agent", input={"message": "Write a detailed account summary."}, ) text = "" async for event in client.runs.stream(run.id): if event.output_delta is not None: text += event.output_delta print(event.output_delta, end="", flush=True) elif event.type == "model_output_reset": # AIR retried or used a fallback after a partial response. text = "" # Clear the partial text in your UI before showing the new attempt. final = await client.runs.get(run.id) print(f"\nRun status: {final.status}") ``` The async iterator ends when the run succeeds, fails, or is cancelled. Each `RunEvent` includes `seq`, `type`, `data`, and `created_at`. If the connection drops, the SDK reconnects and requests events after the last sequence number, so missed output is replayed rather than skipped. Use `after_seq` when you persist the last processed sequence number yourself: ```python theme={null} async for event in client.runs.stream(run.id, after_seq=last_seq): last_seq = event.seq ``` After streaming, read the `Run` with `get()` when you need the authoritative final status, validated structured output, error, or cost. ## Read or cancel ```python theme={null} current = await client.runs.get(run.id) if current.status not in {"succeeded", "failed", "cancelled"}: await client.runs.cancel(run.id) ``` The returned `Run` exposes `id`, `status`, `output`, `error`, `cost_usd`, and the complete response as `raw`. ## Inspect the same run visually Open **Runs** in the console to inspect the event sequence, model request and response, token usage, cost, and configuration snapshot. AIR run trace showing a successful model response and usage metadata ## Handle errors ```python theme={null} from air import AirProtocolError, RunTimeoutError try: result = await client.runs.wait(run.id, timeout=30) except RunTimeoutError: # The server-side run may still be active. result = await client.runs.get(run.id) except AirProtocolError as exc: print(exc.status_code) raise ``` Treat `context` as security-sensitive input. A tool must still verify that every requested record belongs to the supplied tenant before reading or changing data. # How AIR works Source: https://docs.papermap.ai/air/concepts/how-air-works Understand projects, agents, runs, workers, tools, and the durable execution loop. AIR separates hosted orchestration from private tool execution. The hosted runtime owns the durable agent loop; your worker owns access to your systems. ## Core objects | Object | Purpose | | ------------- | ------------------------------------------------------------------------- | | Project | Security and configuration boundary for agents, tools, keys, and members. | | Prompt | Reusable, versioned instructions. | | Agent | Stable API identity used to create runs. | | Agent version | Immutable prompt, model, allowed tools, fallbacks, and limits. | | Run | One durable execution of an active agent version. | | Tool | Reviewed capability an agent may request. | | Worker | Outbound process that registers and executes private tools. | ## Run lifecycle `AirClient` sends the agent API ID, input, trusted context, and optional webhook settings using an app key. The run is bound to one agent version so later configuration changes cannot alter an execution already in progress. Output chunks are recorded as durable events and published live. Each request, response, token count, latency, and cost is recorded in the trace. If the model requests an allowed tool, the run waits while an outbound worker claims the task. The tool result enters the transcript and the run continues until it succeeds, fails, or is cancelled. ## Live output and replay The console and Python SDK consume the same ordered run-event stream. AIR saves each event in Postgres before publishing it through Redis: * Redis delivers new events immediately to connected subscribers. * Postgres remains the source of truth and replays events a subscriber missed. * Each sequence number lets a reconnecting client continue without losing or duplicating output. Redis is the live delivery path, not the permanent record. A console or SDK client can therefore join after a run starts, reconnect after a network break, or inspect a completed run and still receive the recorded event sequence. AIR run trace with model response, usage, cost, and configuration snapshot ## Why tools start pending A worker discovers capability; it does not grant policy. Newly registered tools start **awaiting approval** until a project owner reviews their description, schema, timeout, source, and write capability. An agent version can only call tools explicitly included in that version. # Projects and keys Source: https://docs.papermap.ai/air/concepts/projects-and-keys Choose the correct AIR credential and keep every integration scoped to one project. Every AIR credential belongs to a project and has one purpose. | Credential | Used by | Capability | | --------------- | ---------------- | -------------------------------------------------------------- | | App key | Your application | Create, read, wait for, and cancel runs. | | Worker key | Your worker | Register tools, claim tasks, renew leases, and return results. | | Console session | Human users | Configure projects through the AIR console. | AIR project settings showing separate app and worker key controls ## Issue a key Select the project, then open **Settings**. Select **Issue app key** for application code or **Issue worker key** for an outbound worker. AIR shows the complete key once. Put it in a local environment variable for development or a managed secret store for deployment. Never commit a key. Avoid passing worker keys with `air worker start --key` in shared environments because command arguments can appear in shell history and process listings. Prefer `AIR_WORKER_KEY`. ## Roles are not cloud roles * **Owner** manages project configuration, members, credentials, and tool approval. * **Editor** changes agents and prompts. * **Viewer** reads project state and traces. * **Platform admin** is an AIR application role with cross-project access. It is not an Azure role. # Security Source: https://docs.papermap.ai/air/guides/security Protect AIR credentials, tenant data, workers, and tool permissions. ## Use the narrowest credential * Put an **app key** only in the service that creates runs. * Put a **worker key** only in the process that executes private tools. * Never use a console session or platform-admin token in application code. * Use separate credentials for staging and production. * Rotate app and worker keys independently. Store credentials in a managed secret store. Never commit them, bake them into an image, log them, or pass a worker key through `--key` in a shared environment. ## Authorize inside every tool Agent-generated arguments are untrusted. Validate every value before using it in a query, URL, or shell command. When a tool receives `context`, verify that the requested object belongs to the authenticated tenant. ```python theme={null} from air import tool @tool def get_invoice(invoice_id: str, context: dict) -> dict: """Read an invoice owned by the current tenant.""" tenant_id = context["tenant_id"] invoice = load_invoice(invoice_id=invoice_id, tenant_id=tenant_id) return invoice.to_safe_dict() ``` ## Grant capability in layers 1. A worker registers a manifest. 2. A project owner reviews and enables the tool. 3. An agent version explicitly includes the tool. 4. The tool enforces tenant and object authorization at execution time. AIR tool approval dialog with schema and write action control ## Respond to an exposed key Revoke it immediately, issue a replacement, update the affected deployment, and inspect recent runs, worker registrations, and audit events for unexpected activity. # Troubleshooting Source: https://docs.papermap.ai/air/guides/troubleshooting Resolve common run, credential, worker, and tool configuration problems. ## A run is rejected * Confirm `AIR_BASE_URL` is the API URL, not the console URL. * Confirm the app key and agent belong to the same project. * Use the agent API ID—not its display name—as `agent_id`. * Confirm the agent has an active version and usable model access. `AirProtocolError.status_code` contains the HTTP status. `401` usually means the key is missing, invalid, or revoked. `403` usually means it has the wrong scope or project. ## A tool stays awaiting approval Worker registration only discovers capability. A project owner must open **Tools**, review the manifest, and select **Enable tool**. Then add the enabled tool to a new agent version and activate that version. ## A worker receives no tasks * Confirm the worker key and agent belong to the same project. * Confirm the tool is enabled and allowed by the active agent version. * Confirm the model requested the tool in the run trace. * Confirm the worker remains running after registration. * Check outbound HTTPS access to the AIR API. ## A tool fails Every tool must return a dictionary. Inspect the worker log for the original exception and the run trace for the recorded failure. Validate arguments, tenant access, downstream credentials, and timeouts. ## Waiting timed out `RunTimeoutError` only means the local wait deadline expired. The server-side run may still be active. ```python theme={null} try: result = await client.runs.wait(run.id, timeout=30) except RunTimeoutError: current = await client.runs.get(run.id) ``` Read the run again, inspect its trace, or cancel it explicitly. # Papermap AIR Source: https://docs.papermap.ai/air/index Build governed AI agents and connect private tools without opening your infrastructure to inbound traffic. Papermap Agentic Infrastructure Runtime (AIR) hosts your agent loop, prompts, models, policy, traces, and run state. Your private tools stay close to your systems in outbound-only workers. Create a project, activate an agent, and inspect its first successful run. Turn typed Python functions into governed AIR tools. Start, wait for, inspect, and cancel runs with the Python SDK. Reference `AirClient`, workers, tools, errors, and environment variables. AIR console showing an active support agent and a successful test run Select any screenshot in these guides to open the full-resolution view. ## One runtime, two connections ```text theme={null} Your application -- app key --> AIR -- model --> result | | queued tool call v Your worker <--- outbound claim --+--- worker key | +--> your database, APIs, and local MCP servers ``` * Your **application** creates runs with an app key. * AIR executes the active agent version and records its trace. * Your **worker** connects outbound with a worker key and executes approved tools. Staging console: [dev.air.papermap.ai](https://dev.air.papermap.ai). Staging API: `https://dev.airapi.papermap.ai`. Start with the [visual quickstart](/air/quickstart). It walks through the same screens you will use in the console and ends with a real run trace. # Visual quickstart Source: https://docs.papermap.ai/air/quickstart Create a project, prompt, active agent, and first run in the AIR staging console. In about ten minutes, you will create an active agent and see its first run in the AIR trace viewer. You do not need a model-provider key for the staging smoke test. Select a screenshot to zoom. The screenshots use a disposable staging project and contain no API keys or provider credentials. ## Before you begin * Python 3.10 or newer * Access to the [AIR staging console](https://dev.air.papermap.ai) * A model-provider key only when you are ready to use a real OpenAI or Anthropic model Sign in, select **New project**, enter a descriptive name, and select **Create project**. A project is the boundary for agents, tools, members, keys, and provider credentials. New project dialog with Developer quickstart entered as the project name Open **Prompts**, select **New prompt**, and name it `Support assistant`. Open the prompt, select **New version**, and enter: ```text theme={null} You are a concise support assistant. Answer using the information in the run input. If information is missing, explain what you need. ``` Add a short change note and create the version. AIR dialog for creating the first version of a support assistant prompt Open **Agents**, select **New agent**, and name it `Support agent`. Reuse the prompt version you just created. For the first staging smoke test, choose **Bring your own provider key**, then select **Testing** and **fake-echo**. This built-in model requires no key. Leave **Activate immediately** selected and choose **Create & start serving**. AIR agent composer with the support prompt and fake-echo testing model selected For real responses, choose OpenAI or Anthropic and connect the project provider key when prompted. Keys are encrypted and never shown again. In the agent's **Try it** panel, enter `When does support open?` and select **Run test**. The **Output · streaming** panel appears after the first model chunk and grows while the run is active. The transcript records the same event sequence without changing the active configuration. Active support agent with a succeeded test and visible transcript Select **Open full run**. The trace shows the exact agent and prompt versions, token usage, cost, model latency, request, response, and immutable configuration snapshot. AIR trace viewer showing a successful fake-echo model response Open **Settings** and select **Issue app key**. Copy the key once into your local environment or secret manager. Do not put it in source control. AIR project settings showing app key and worker key actions Install the published SDK: ```bash theme={null} python -m pip install papermap-air export AIR_BASE_URL="https://dev.airapi.papermap.ai" export AIR_APP_KEY="" ``` Copy the agent API ID from the agent page and use it as `agent_id`: ```python theme={null} import asyncio import os from air import AirClient async def main() -> None: async with AirClient( os.environ["AIR_BASE_URL"], os.environ["AIR_APP_KEY"], ) as client: run = await client.runs.create( agent_id="support-agent", input={"message": "When does support open?"}, context={"tenant_id": "demo"}, ) result = await client.runs.wait(run.id, timeout=120) print(result.status, result.output) asyncio.run(main()) ``` You now have a project, versioned instructions, an active agent, a successful trace, and application access. Next, [connect a private worker](/air/workers/create-worker). # Environment variables Source: https://docs.papermap.ai/air/reference/environment-variables Configuration used by AIR applications and worker processes. ## Applications The SDK constructor accepts values directly. These conventional names keep application configuration consistent: | Variable | Required | Example | | -------------- | -------- | ------------------------------------ | | `AIR_BASE_URL` | Yes | `https://dev.airapi.papermap.ai` | | `AIR_APP_KEY` | Yes | Project app key from the AIR console | ```python theme={null} import os from air import AirClient client = AirClient( os.environ["AIR_BASE_URL"], os.environ["AIR_APP_KEY"], ) ``` ## Worker CLI | Variable | Required | Default | Purpose | | -------------------------- | -------- | --------- | ---------------------------------------- | | `AIR_BASE_URL` | Yes | None | AIR API origin. | | `AIR_WORKER_KEY` | Yes | None | Project-scoped worker credential. | | `AIR_WORKER_ENV` | No | `default` | Label describing the worker environment. | | `AIR_WORKER_CLAIM_TIMEOUT` | No | `5` | Task long-poll timeout in seconds. | ```bash theme={null} AIR_BASE_URL="https://dev.airapi.papermap.ai" \ AIR_WORKER_KEY="" \ AIR_WORKER_ENV="staging" \ air worker start --module tools ``` Keep keys out of committed `.env` files. In deployed environments, inject them from a managed secret store. # Python SDK Source: https://docs.papermap.ai/air/reference/python-sdk Reference for AIR application clients, runs, workers, tools, and errors. The PyPI distribution is `papermap-air`; the Python import is `air`. Python 3.10 or newer is required and the SDK is async-native. ```bash theme={null} python -m pip install papermap-air ``` ## `AirClient` ```python theme={null} AirClient(base_url: str, api_key: str) ``` Use it as an async context manager or call `await client.aclose()` explicitly. ### `client.runs.create()` Creates a run. `agent_id` is required. `model_id`, `input`, `context`, and `webhook_url` are optional. Returns a `Run`. ### `client.runs.get(run_id)` Returns the latest state of a run. ### `client.runs.wait(run_id, timeout=60, poll_interval=0.2)` Polls until `succeeded`, `failed`, or `cancelled`. Raises `RunTimeoutError` when the local timeout is reached. ### `client.runs.stream(run_id, *, after_seq=0, max_retries=3, retry_delay=0.5)` Returns an async iterator of `RunEvent` objects. It emits existing events after `after_seq`, continues with live events, and stops after a terminal `run_succeeded`, `run_failed`, or `run_cancelled` event. The SDK reconnects after a temporary stream failure and resumes after the last sequence number it received. `max_retries` controls the number of reconnect attempts and `retry_delay` controls the delay between them. ```python theme={null} text = "" async for event in client.runs.stream(run.id): if event.output_delta is not None: text += event.output_delta elif event.type == "model_output_reset": text = "" ``` ### `client.runs.cancel(run_id)` Requests cancellation and returns the server response dictionary. ## `Run` | Field | Type | Meaning | | ---------- | -------------- | ------------------------------------------------------------------------ | | `id` | `str` | Run identifier. | | `status` | `str` | Current lifecycle status. | | `output` | `dict \| None` | Validated schema object, or `{ "text": "..." }` for a schema-less agent. | | `error` | `str \| None` | Failure detail when available. | | `cost_usd` | `str` | Recorded cost as a decimal string. | | `raw` | `dict` | Complete server response. | ## `RunEvent` | Field | Type | Meaning | | -------------- | ------------- | --------------------------------------------------------------------- | | `seq` | `int` | Increasing sequence number within the run. | | `type` | `str` | Event type, such as `model_output_delta` or `run_succeeded`. | | `data` | `dict` | Event-specific payload. | | `created_at` | `str \| None` | Server timestamp when available. | | `output_delta` | `str \| None` | Convenience property containing text for `model_output_delta` events. | When `type` is `model_output_reset`, discard any partial model text already rendered. This event means AIR started another model attempt after a retry or fallback. Terminal run events end the iterator. ## `@tool` ```python theme={null} from air import tool @tool(name="lookup_order", timeout=30) def lookup_order(order_id: str, context: dict) -> dict: """Look up one order.""" return {"order_id": order_id} ``` The decorator derives a JSON schema from type annotations. Synchronous tools run in a thread; async tools are awaited. A `context` parameter receives the run context. Every tool must return a dictionary. Use a separate `ToolRegistry` when you want explicit isolation instead of the process-wide default registry. ## `Worker` ```python theme={null} Worker( base_url: str, worker_key: str, *, registry: ToolRegistry | None = None, environment: str = "default", ) ``` Important methods are `start()`, `poll_once()`, `heartbeat()`, `run()`, `mount_mcp()`, and `aclose()`. ## Errors All SDK errors inherit from `AirError`: * `AirProtocolError` for rejected or unexpected HTTP responses * `RunTimeoutError` when a local wait deadline expires * `ToolDefinitionError` for invalid or duplicate tool definitions * `ToolResultError` when a tool does not return a dictionary * `McpError` for MCP transport or protocol failures # Create a private worker Source: https://docs.papermap.ai/air/workers/create-worker Register typed Python functions as governed tools over an outbound-only worker connection. Workers keep database and API access inside your infrastructure. They make outbound HTTPS requests to AIR; you do not expose an inbound worker port. ```bash theme={null} python -m pip install papermap-air ``` Create `tools.py`: ```python theme={null} from air import tool @tool(timeout=30) def lookup_order(order_id: str, context: dict) -> dict: """Look up an order for the current tenant.""" tenant_id = context["tenant_id"] # Query your system and verify the order belongs to tenant_id. return { "order_id": order_id, "tenant_id": tenant_id, "status": "shipped", } ``` Type annotations become the JSON input schema. The first docstring line is the description shown during review. Every tool must return a dictionary. Open **Settings**, select **Issue worker key**, and store the value in an environment variable or secret manager. AIR settings showing separate app and worker key controls ```bash theme={null} export AIR_BASE_URL="https://dev.airapi.papermap.ai" export AIR_WORKER_KEY="" export AIR_WORKER_ENV="staging" air worker start --module tools ``` The process registers its manifest and begins long-polling for tool calls. Open **Tools**. A newly discovered capability starts **awaiting approval**; registration never grants permission by itself. AIR Tools screen showing lookup_order awaiting approval Select **Review**. Confirm the source, description, timeout, generated input schema, and whether it needs write access. Then select **Enable tool**. AIR tool review dialog showing lookup_order schema and read-only approval Create a new agent version, open **Advanced — fallback models, tools, and limits**, add `lookup_order`, test the version, and activate it. Enabling a project tool does not automatically add it to existing agent versions. Registration answers “what can this worker do?” Tool approval answers “does this project trust it?” The agent version answers “may this agent call it?” # Deploy a worker Source: https://docs.papermap.ai/air/workers/deploy-worker Package and operate AIR workers safely in containers and Kubernetes. A worker is a long-running Python process. Run it anywhere that can reach AIR over HTTPS and the private systems used by its tools. ## Container example ```dockerfile theme={null} FROM python:3.12-slim WORKDIR /app RUN python -m pip install --no-cache-dir papermap-air==0.1.0 COPY tools.py /app/tools.py CMD ["air", "worker", "start", "--module", "tools"] ``` Configure runtime values through your deployment system: ```text theme={null} AIR_BASE_URL=https://dev.airapi.papermap.ai AIR_WORKER_KEY= AIR_WORKER_ENV=staging AIR_WORKER_CLAIM_TIMEOUT=5 ``` ## Kubernetes secret reference ```yaml theme={null} env: - name: AIR_BASE_URL value: https://dev.airapi.papermap.ai - name: AIR_WORKER_KEY valueFrom: secretKeyRef: name: air-worker key: worker-key - name: AIR_WORKER_ENV value: staging ``` ## Operational checklist * Pin the SDK version and test upgrades before rollout. * Give staging and production separate worker keys. * Give the worker's database identity the minimum required permissions. * Let the process receive `SIGTERM`; the CLI stops claiming work and closes its connections. * Start with one staging replica and scale after observing tool latency and throughput. * Rotate a key by deploying the new value, confirming reconnection, and revoking the old key. * Monitor registration, task failure, lease loss, and downstream timeouts. Do not put real credentials in a Dockerfile, image layer, committed `.env` file, or Kubernetes manifest. Sync them from a managed vault at runtime. # Connect MCP tools Source: https://docs.papermap.ai/air/workers/mcp Mount local Model Context Protocol servers into an outbound AIR worker. The Python SDK can mount a local Model Context Protocol server and proxy its tools through the normal AIR worker connection. ## Stdio server ```python theme={null} import asyncio import os from air import Worker async def main() -> None: worker = Worker( os.environ["AIR_BASE_URL"], os.environ["AIR_WORKER_KEY"], environment=os.getenv("AIR_WORKER_ENV", "staging"), ) stop = asyncio.Event() try: names = await worker.mount_mcp( "stdio", command=["python", "my_mcp_server.py"], prefix="inventory", ) print("registered", names) await worker.run(stop) finally: await worker.aclose() asyncio.run(main()) ``` ## Local HTTP server ```python theme={null} names = await worker.mount_mcp( "http", url="http://127.0.0.1:8765/mcp", prefix="internal", timeout=30, ) ``` Call `mount_mcp()` before `start()` or `run()` so mounted tools are included in the registration manifest. AIR normalizes unsupported characters in MCP tool names and adds deterministic suffixes when names collide. Mounted tools use the same review flow as Python tools: inspect the manifest, enable the tool, and add it to a new agent version. Treat an MCP server as executable infrastructure. Pin and review it, restrict its credentials, and expose only the capabilities your project needs. # Create Dashboard Source: https://docs.papermap.ai/api-reference/create-dashboard /api-reference/managing-dashboards/dashboard-openapi.json post /api/v1/external/dashboards Endpoint to create a new dashboard # Generate Embed Token Source: https://docs.papermap.ai/api-reference/generate-embed-token /api-reference/embedding/embed-openapi.json post /api/v1/embed/generate-token Generate a temporary token for testing embedded dashboards. This token allows you to preview and test your dashboard embedding configuration before implementing it in production. # Get Tenant Usage History Source: https://docs.papermap.ai/api-reference/get-tenant-usage-history /api-reference/tenant-usage/tenant-usage-openapi.json get /api/v1/external/workspaces/{workspace_id}/tenant-usage/{tenant_id} Retrieve usage history for a specific tenant # Get Workspace Tenant Usage Source: https://docs.papermap.ai/api-reference/get-workspace-tenant-usage /api-reference/tenant-usage/tenant-usage-openapi.json get /api/v1/external/workspaces/{workspace_id}/tenant-usage Retrieve usage data for all tenants in a workspace # Developer Platform Source: https://docs.papermap.ai/changelog/developer-platform API updates, new endpoints, and SDK releases API updates, new endpoints, SDK releases, and developer-focused features. # Release Notes Source: https://docs.papermap.ai/changelog/release-notes Follow along with updates across Papermap’s API # Basic Embedding Source: https://docs.papermap.ai/documentation/embedding/basic-embedding ## Secure Embedding with JavaScript The recommended way to embed a dashboard is to fetch a secure token from your backend and dynamically create the iframe. This keeps your API credentials safe. Although this guide demonstrates iframe embedding, the same backend pattern of generating a signed token server-side also applies when embedding Papermap through `@papermap/papermap`. If you are embedding `PaperChat`, `PaperCard`, or `PaperBoard`, see [React Components](/documentation/embedding/react-components). **Security Best Practice:** Never expose your API credentials (API Key ID and Secret Key) in your frontend code. Always generate tokens on your backend server and fetch them from your frontend. To generate tokens on your backend, see the [Backend: Generating Embed Tokens](#backend%3A-generating-embed-tokens) section below for implementation examples in Python, TypeScript, PHP, and Go. To get the `dashboardId` for your dashboard, navigate to your Papermap workspace and click the top-left dropdown menu to view all dashboards. Select the "Show All Dashboards" section to view information about all dashboards including the `dashboardId` The same `dashboardId` can also be used by the React components package when rendering `PaperChat`, `PaperCard`, and `PaperBoard`. ### React Example ```tsx theme={null} import { useEffect, useState } from "react"; function DashboardEmbed({ workspaceId, dashboardId }) { const [iframeUrl, setIframeUrl] = useState(""); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { async function fetchToken() { try { const response = await fetch( `/api/embed-token?workspaceId=${workspaceId}&dashboardId=${dashboardId}` ); const data = await response.json(); const url = `https://papermap.ai/embedded/dashboard?embedded-token=${data.token}&workspace-id=${workspaceId}&dashboard-id=${dashboardId}`; setIframeUrl(url); setLoading(false); } catch (err) { setError(err.message); setLoading(false); } } fetchToken(); }, [workspaceId, dashboardId]); if (loading) return
Loading dashboard...
; if (error) return
Error: {error}
; return ( ``` **When to Use Frontend Generation:** - ✅ Local development and testing - ✅ Internal tools with restricted access - ✅ Quick prototypes and demos - ❌ **Never in production** (credentials exposed to users) - ❌ Public-facing applications - ❌ Applications requiring authentication ## Simple iframe Embedding For testing purposes, you can also use a static iframe with a pre-generated token: ```html theme={null} ``` ### Complete Example Here's a full HTML example using kebab-case naming: ```html theme={null} My Dashboard

Sales Dashboard

``` ## Responsive Design ### CSS Styling Make your embedded dashboards responsive: ```css theme={null} .dashboard-container { width: 100%; height: 600px; border: 1px solid #ddd; border-radius: 8px; } @media (max-width: 768px) { .dashboard-container { height: 400px; } } @media (max-width: 480px) { .dashboard-container { height: 300px; border-radius: 4px; } } ``` ## Backend: Generating Embed Tokens To securely embed dashboards, you need to generate a signed token from your backend. Here's how to create the token: ### Token Generation ```python Python theme={null} import hmac import hashlib import json import base64 import time def generate_embed_token(workspace_id: str, dashboard_id: str, api_key_id: str, secret_key: str): # Token valid for 1 hour valid_until = int(time.time()) + 3600 # Create HMAC signature payload = f"{workspace_id}{valid_until}" signature = hmac.new( secret_key.encode(), payload.encode(), hashlib.sha256 ).hexdigest() # Create token data token_data = { "api_key_id": api_key_id, "workspace_id": workspace_id, "dashboard_id": dashboard_id, "valid_until": valid_until, "signature": signature } # Encode token token_json = json.dumps(token_data) encoded_token = base64.urlsafe_b64encode(token_json.encode()).decode() return encoded_token ``` ```typescript TypeScript/Node.js theme={null} import crypto from "crypto"; function generateEmbedToken( workspaceId: string, dashboardId: string, apiKeyId: string, secretKey: string ): string { // Token valid for 1 hour const validUntil = Math.floor(Date.now() / 1000) + 3600; // Create HMAC signature const payload = `${workspaceId}${validUntil}`; const signature = crypto .createHmac("sha256", secretKey) .update(payload) .digest("hex"); // Create token data const tokenData = { api_key_id: apiKeyId, workspace_id: workspaceId, dashboard_id: dashboardId, valid_until: validUntil, signature: signature, }; // Encode token return Buffer.from(JSON.stringify(tokenData)).toString("base64url"); } ``` ```php PHP theme={null} $apiKeyId, 'workspace_id' => $workspaceId, 'dashboard_id' => $dashboardId, 'valid_until' => $validUntil, 'signature' => $signature ]; // Encode token $token = base64_encode(json_encode($tokenData)); return str_replace(['+', '/', '='], ['-', '_', ''], $token); } ?> ``` ```go Go theme={null} package main import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "time" ) func generateEmbedToken(workspaceID, dashboardID, apiKeyID, secretKey string) string { // Token valid for 1 hour validUntil := time.Now().Unix() + 3600 // Create HMAC signature payload := workspaceID + fmt.Sprintf("%d", validUntil) h := hmac.New(sha256.New, []byte(secretKey)) h.Write([]byte(payload)) signature := hex.EncodeToString(h.Sum(nil)) // Create token data tokenData := map[string]interface{}{ "api_key_id": apiKeyID, "workspace_id": workspaceID, "dashboard_id": dashboardID, "valid_until": validUntil, "signature": signature, } // Encode token jsonData, _ := json.Marshal(tokenData) encoded := base64.URLEncoding.EncodeToString(jsonData) return strings.TrimRight(encoded, "=") } ``` ### Usage Example ```python Python (FastAPI) theme={null} from fastapi import APIRouter router = APIRouter() @router.get("/embed-token") async def get_embed_token(workspace_id: str, dashboard_id: str): token = generate_embed_token( workspace_id=workspace_id, dashboard_id=dashboard_id, api_key_id="your-api-key-id", secret_key="your-secret-key" ) return {"token": token} ``` ```typescript TypeScript (Express) theme={null} import express from "express"; const router = express.Router(); router.get("/embed-token", (req, res) => { const { workspaceId, dashboardId } = req.query; const token = generateEmbedToken( workspaceId as string, dashboardId as string, "your-api-key-id", "your-secret-key" ); res.json({ token }); }); ``` **Security Note:** Always store your API credentials in environment variables, never hardcode them in your source code. The token is valid for how long you set it for but it is recommended to be 1 hour for security sake. ## Next Steps Learn about advanced configuration options and customization parameters for your embedded dashboards Explore common parameter combinations and use cases for different embedding scenarios Common issues and solutions for embedding Papermap dashboards in your application # Configuration Source: https://docs.papermap.ai/documentation/embedding/configuration Learn the various configuation and personalization options availiable when embedding Papermap ## URL Parameters The embedding URL supports various parameters to customize the dashboard appearance and functionality. All parameters use kebab-case naming convention. ### Required Parameters | Parameter | Description | Example | | ----------------- | ------------------------ | -------------- | | `embedding-token` | Embedding token | `Z0FBQ...` | | `workspace-id` | The workspace identifier | `dIwIBPYdGmWS` | | `dashboard-id` | The dashboard id | `dIwIBPYmWS` | ### Display Options | Parameter | Type | Default | Description | | ----------------- | ------- | ------- | --------------------------------------- | | `show-toolbar` | boolean | `true` | Show/hide the chat toolbar | | `show-header` | boolean | `true` | Show/hide the dashboard header | | `show-nav` | boolean | `false` | Show/hide navigation elements | | `show-screenshot` | boolean | `true` | Enable/disable screenshot functionality | ### Dashboard Controls | Parameter | Type | Default | Description | | ----------------------- | ------- | ------- | ------------------------------------ | | `show-dashboard-select` | boolean | `false` | Show dashboard selector dropdown | | `generate-dashboard` | boolean | `false` | Enable dashboard generation features | | `edit-mode` | boolean | `false` | Enable edit mode for dashboard | | `edit-layout` | boolean | `false` | Enable layout editing | | `edit-chart` | boolean | `false` | Enable chart editing | | `delete-chart` | boolean | `false` | Enable chart deletion | | `pin-chart` | boolean | `false` | Enable chart pinning | ### Chat Features | Parameter | Type | Default | Description | | ------------------- | ------- | ------- | ------------------ | | `chat-composer` | boolean | `true` | Show chat composer | | `show-chat-toolbar` | boolean | `true` | Show chat toolbar | ### Appearance | Parameter | Type | Options | Default | Description | | --------- | ------ | ------------------------- | ------- | --------------- | | `theme` | string | `light`, `dark`, `system` | `light` | Dashboard theme | ## Next Steps Explore common parameter combinations and use cases for different embedding scenarios Common issues and solutions for embedding Papermap dashboards in your application # Getting Your API Key Source: https://docs.papermap.ai/documentation/embedding/get-api-key API Keys in Papermap are scoped to workspaces. A workspace is a secure environment connected to a specific data source where you can chat with our AI to obtain insights from your data and build multiple live dashboards. The API key you create here can be used for both iframe embedding and React component embedding with `@papermap/papermap`. For the React integration path, see [React Components](/documentation/embedding/react-components). Follow the steps below to obtain an API key: Visit [papermap.ai](https://www.papermap.ai) and sign in with your credentials. Navigate to your workspace and click the options icon (three dots) in the workspace card, then select **Settings** from the dropdown menu. Navigate to **API Keys** from the sidebar and click **Create New Key** to generate a new API key. Copy the generated API key (starts with `ak_`) and SECRET key also. Store it securely! ## Security Considerations **Never expose your API key in client-side code or public repositories.** Your API key provides full access to your Papermap data and should be treated as a password. ### Best Practices * **Store securely**: Use environment variables or secure configuration management * **Never commit**: Add your API key to `.gitignore` and never commit it to version control * **Rotate regularly**: Generate new API keys periodically and revoke old ones * **Monitor usage**: Check your API key usage in the Papermap dashboard for any suspicious activity * **Use HTTPS**: Always use HTTPS when embedding dashboards to protect data in transit ### For Production Applications * Implement server-side proxy endpoints that generate temporary tokens * Use proper authentication and authorization before serving embedded content ## Next Steps Embed `PaperChat`, `PaperCard`, and `PaperBoard` directly in your React application Start with simple iframe embedding to get your first dashboard up and running Learn about advanced configuration options and customization parameters for your embedded dashboards Explore common parameter combinations and use cases for different embedding scenarios Common issues and solutions for embedding Papermap dashboards in your application # Embedding Overview Source: https://docs.papermap.ai/documentation/embedding/overview Papermap provides powerful embedding capabilities that allow you to integrate conversational analytics, interactive dashboards and visualizations directly into your website or web application. ## Overview Embedding allows you to: * Include Papermap conversational analytics directly into your web application * Display live dashboards in your website * Customize the appearance and functionality * Control user interactions and permissions * Maintain consistent branding with your application This guide will walk you through the various embedding options and implementation methods. ## Next Steps Learn how to obtain and configure your API key for embedding Papermap dashboards Embed `PaperChat`, `PaperCard`, and `PaperBoard` directly in your React application Start with simple iframe embedding to get your first dashboard up and running Learn about advanced configuration options and customization parameters for your embedded dashboards Explore common parameter combinations and use cases for different embedding scenarios Common issues and solutions for embedding Papermap dashboards in your application # Parameter Usecases Source: https://docs.papermap.ai/documentation/embedding/parameter-usecases ### Dashboard Selection Parameters * **`dashboard-id`**: Use when you want to embed a specific dashboard instead of the default one * **`show-dashboard-select`**: Enable this to allow users to switch between different dashboards within the embedded view ### Navigation Control * **`show-nav`**: Set to `true` to show the main navigation sidebar (useful for full-featured embeds) ### Chat Integration * **`chat-composer`**: Show the AI chat interface for data queries * **`show-toolbar`**: Control the visibility of the chat toolbar * **`show-chat-toolbar`**: Control the visibility of the chat toolbar specifically ### Editing and Generation Features * **`generate-dashboard`**: Enable dashboard generation features for creating new dashboards * **`edit-mode`**: Enable edit mode to allow users to modify dashboard content * **`edit-layout`**: Enable layout editing to rearrange dashboard components * **`edit-chart`**: Enable chart editing to modify individual charts * **`delete-chart`**: Enable chart deletion functionality * **`pin-chart`**: Enable chart pinning to keep important charts visible ### Parameter Examples Here are some common parameter combinations: Replace `YOUR_TOKEN` with the embedded token generated from your backend. See the [Get API Key](/documentation/embedding/get-api-key) guide for details. ```html theme={null} ``` ## Next Steps Common issues and solutions for embedding Papermap dashboards in your application # React Components Source: https://docs.papermap.ai/documentation/embedding/react-components Papermap also supports embedding with React components through `@papermap/papermap`. This package lets you embed Papermap-native chat, chart cards, and board layouts directly in your application instead of embedding the full dashboard iframe. ## Main Components * **`PaperChat`**: Full AI chat assistant with streaming, conversation history, and chart generation. * **`PaperCard`**: Standalone chart card with toolbar actions. Use `variant="streaming"` for an embedded chart and conversation dialog without the floating assistant. * **`PaperBoard`**: Responsive grid layout of chart cards, toolbar actions, optional chat assistant, and controlled or uncontrolled layouts. Each top-level component handles API calls, authentication, and UI internally unless you compose lower-level exports yourself. ### `PaperChat` Use `PaperChat` when you want the embedded AI assistant experience with chat history, chart generation, and streaming responses. ```tsx theme={null} import { PaperChat } from '@papermap/papermap' ``` PaperChat embedded in a React application ### `PaperCard` Use `PaperCard` when you want to render a single chart card with Papermap toolbar actions inside your own page layout. ```tsx theme={null} import { PaperCard } from '@papermap/papermap' ``` PaperCard rendering a standalone chart card ### `PaperCard` streaming variant Use `variant="streaming"` when you want the chart card and the expanded conversation flow together in the same embedded surface. ```tsx theme={null} import { PaperCard } from '@papermap/papermap' ``` PaperCard streaming variant showing chart and conversation together ### `PaperBoard` Use `PaperBoard` when you want a dashboard-style layout with multiple cards, optional chat assistant, and responsive board behavior. ```tsx theme={null} import { PaperBoard } from '@papermap/papermap' ``` PaperBoard overview with multiple embedded chart cards PaperBoard expanded dashboard view ## Quick Start ### 1. Install ```bash npm theme={null} npm install @papermap/papermap ``` ```bash pnpm theme={null} pnpm add @papermap/papermap ``` **Requirements:** React 18+ and React DOM 18+. ### 2. Import styles once ```tsx theme={null} import '@papermap/papermap/styles.css' ``` ### 3. Before you start You will need a few Papermap values before the components can render successfully: * **API key**: Generate this in Papermap before wiring up your app. See [Getting Your API Key](/documentation/embedding/get-api-key). * **`workspaceId`**: Use the workspace that owns the charts and dashboards you want to embed. * **`dashboardId`**: Use the dashboard context you want the embedded components to read from and save into. See [Basic Embedding](/documentation/embedding/basic-embedding). * **Frontend token**: Your app should fetch a signed, base64-encoded token from your backend. See [Basic Embedding](/documentation/embedding/basic-embedding#backend%3A-generating-embed-tokens) for the backend token generation flow. * **Optional `apiUrl`**: Only set this if your environment uses a non-default Papermap API base URL. `token` is not the raw API key. Keep the API key and secret on your backend, and return a short-lived signed token to your frontend instead. ### 4. Minimal integration flow 1. Create an API key in Papermap. 2. Identify the `workspaceId` and `dashboardId` you want to use. 3. Add a backend endpoint that returns a signed token to your frontend. 4. Wrap your app with `PapermapConfigProvider` or pass the values directly to each component. 5. Render `PaperChat`, `PaperCard`, or `PaperBoard`. If you are implementing tenant-aware dashboard provisioning or server-side dashboard creation, see [Creating Dashboards](/documentation/multi-tenancy/creating-dashboards) and [Iframe Embed Tokens](/documentation/multi-tenancy/iframe-tokens). ### 5. Choose an integration pattern #### Recommended: provider at app root `PapermapConfigProvider` is an alias for `PapermapProvider`. ```tsx theme={null} import { PapermapConfigProvider, PaperChat, PaperCard, } from '@papermap/papermap' function App() { return ( ) } ``` #### Standalone components Pass `token`, `workspaceId`, and `dashboardId` on each component when you are not using a provider. ```tsx theme={null} import { PaperChat, PaperCard } from '@papermap/papermap' function App() { return ( <> ) } ``` ## Props ### `PaperChat` | Prop | Type | Required | Default | Description | | ------------- | ------------------- | -------- | ----------------------------- | ---------------------------------------- | | `token` | `string` | Yes\* | -- | Base64-encoded API token | | `workspaceId` | `string` | Yes\* | -- | Workspace ID | | `dashboardId` | `string` | Yes\* | -- | Dashboard ID | | `apiUrl` | `string` | No | `https://dataapi.papermap.ai` | API base URL | | `theme` | `'light' \| 'dark'` | No | -- | Force light or dark theme | | `placeholder` | `string` | No | `"Ask anything..."` | Input placeholder text | | `shortcutKey` | `string` | No | `"k"` | Keyboard shortcut key | | `autoFade` | `boolean` | No | `false` | Fade toolbar after inactivity | | `fadeDelay` | `number` | No | `5000` | Delay before auto-fade in milliseconds | | `className` | `string` | No | -- | Extra CSS class on the toolbar container | \*Omit these on the component when values come from `PapermapConfigProvider` or `PapermapProvider`. ### `PaperCard` | Prop | Type | Required | Default | Description | | -------------- | -------------------------------------------- | -------- | ----------------------------- | ------------------------------------------------------------- | | `token` | `string` | Yes\* | -- | Base64-encoded API token | | `workspaceId` | `string` | Yes\* | -- | Workspace ID | | `dashboardId` | `string` | Yes\* | -- | Dashboard ID | | `apiUrl` | `string` | No | `https://dataapi.papermap.ai` | API base URL | | `chartId` | `string` | No | -- | Backend chat ID to load the latest chart for | | `chart` | `TChartResponse` | No | -- | Pre-loaded chart data that skips API fetch | | `theme` | `'light' \| 'dark'` | No | -- | Force light or dark theme | | `onEditClick` | `(chartId: string) => void` | No | -- | Called when the edit button is clicked | | `onDelete` | `(chartId: string) => void` | No | -- | Called when chart deletion is confirmed | | `onPinChange` | `(chartId: string, pinned: boolean) => void` | No | -- | Called when pin state changes | | `wide` | `boolean` | No | `false` | Wide mode for table charts | | `hideVariants` | `boolean` | No | `true` | Hide the chart variation selector | | `showToolbar` | `boolean` | No | `true` | Show toolbar actions | | `className` | `string` | No | -- | Extra CSS class on the card container | | `variant` | `'default' \| 'streaming'` | No | `'default'` | Embedded streaming mode opens chart and conversation together | ### Pre-loaded chart example ```tsx theme={null} import { PaperCard } from '@papermap/papermap' import type { TChartResponse } from '@papermap/papermap' const chart: TChartResponse = { llm_data_chat_id: 'my-chart-id', name: 'Revenue', meta: { title: 'Revenue by Quarter', variant: 'default' }, pin: false, chart_response: { chart_type: 'bar', data: [ { quarter: 'Q1', revenue: 42000 }, { quarter: 'Q2', revenue: 55000 }, ], response_type: 'chart', schema_hints: { x_key: 'quarter', y_key: 'revenue', label_key: 'quarter' }, visualization_config: { colors: ['#3b82f6'], width: 600, height: 400 }, }, } console.log('Edit', id)} onDelete={(id) => console.log('Delete', id)} /> ``` ### `PaperBoard` | Prop | Notes | | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ | | `token`, `workspaceId`, `dashboardId`, `apiUrl` | Same configuration as the other components; can come from a provider | | `charts` | Optional pre-loaded charts; otherwise fetched when `enableFetch` is true | | `layouts` / `onLayoutsChange` | Controlled grid layouts per breakpoint | | `isEditMode`, `editLayout`, `isViewer` | Edit and view behavior controls | | `showToolbar`, `showScreenshot`, `showGenerateDashboard`, `showHeader`, `showChatAssistant` | Feature toggles | | `variant` | `'default' \| 'streaming'` for embedded chart cards | | `dashboardTheme`, `onDashboardThemeChange`, `persistWorkspaceTheme`, `renderThemeModal` | Theming controls | | `onEditChart`, `onDeleteChart`, `onPinChange`, `onGenerateDashboard`, `onTakeScreenshot`, `onThemeModalOpen` | Lifecycle and UI callbacks | See the TypeScript types for `PaperBoardProps` for the full API surface. ### Streaming chart card variant With `variant="streaming"`, the edit action opens an embedded expanded view with chart, conversation, SSE streaming, save-to-dashboard actions, maximize actions, and assistant audit history. ```tsx theme={null} import { PaperCard } from '@papermap/papermap' export function EmbeddedStreamingChart() { return (
) } ``` Supported chart types: `bar`, `line`, `area`, `pie`, `radar`, `scatter`, `table`, `tile`. ## Advanced Exports For custom layouts, the package also exports subcomponents such as `ChatAssistant`, `StreamingChartDialog`, `ChartView`, and `DataTable`, along with Zustand store helpers, hooks like `useAnalyticsStream`, API helpers such as `createApiClient`, `decodeToken`, and `buildAuthHeaders`, plus streaming and chart types. ## Troubleshooting ### Cannot find module `@papermap/papermap/styles.css` * Use the scoped package name and the `./styles.css` export. * Reinstall after upgrading. ### Papermap requires `token`, `workspaceId`, or `dashboardId` * Provide the values once via `PapermapConfigProvider` or `PapermapProvider`. * Or pass them directly on each component. ### Requests hit the wrong backend * Set `apiUrl` on the provider or per component. The default is `https://dataapi.papermap.ai`. ### Charts do not appear in `PaperCard` * Pass a valid backend `chartId`. * Or provide pre-loaded `chart` data directly. ## How It Works ### Authentication The `token` prop is base64-encoded JSON: ```json theme={null} { "api_key_id": "ak_...", "workspace_id": "...", "valid_until": 1773246356, "signature": "88b34e..." } ``` The library decodes the token and sends these headers on API requests: * `X-API-Key-ID` * `X-Workspace-ID` * `X-Valid-Until` * `X-Signature` * `X-Tenant-ID: da-app` ### Chat data flow 1. The first user message may create a chat via `POST /api/v1/analytics/chats`. 2. Messages are sent to `POST /api/v1/analytics/charts/stream`. 3. SSE connects to `POST /api/v1/analytics/requests/stream` for live updates, with HTTP fallback when needed. 4. History is loaded from chat conversations, dashboard recent chats, and chart history endpoints. ### What users see in `PaperChat` * Floating input bar with keyboard shortcut support. * Conversation panel with streaming states, stop action, and new chat flow. * Recent conversations, per-chat history, feedback, optional execution view, and model selection. ## Next Steps Generate the API credentials you need before wiring up the React package. Use iframe embedding if you want the full Papermap dashboard surface instead. Review common integration issues and fixes. # Troubleshoot Source: https://docs.papermap.ai/documentation/embedding/troubleshooting ### Common Issues * Verify your API key is correct and active * Check that the workspace ID exists and is accessible * Ensure you're using HTTPS for the iframe source * Use CSS to customize the iframe appearance * Try different theme options (`light`, `dark`, `system`) * Check for CSS conflicts with your site's styles * Check if you're using the correct dashboard ID * Verify your workspace has the latest data * Clear your browser cache and refresh ### Getting Help If you're still having issues: * Verify all required parameters are included in your URL * Check the browser console for error messages * Contact [support](mailto:team@papermap.ai) with your specific error details # API Endpoints Source: https://docs.papermap.ai/documentation/multi-tenancy/api-endpoints This guide provides example REST API endpoints for dashboard operations in your backend. ## Overview Your API should expose endpoints for: * Creating dashboards for tenants * Retrieving tenant dashboards * Generating iframe embed tokens * Managing dashboard access ## Authentication Middleware All endpoints should require authentication. Here's an example middleware: ```python Python (FastAPI) theme={null} from fastapi import Depends, HTTPException, Header from jose import jwt, JWTError async def get_authenticated_user( authorization: str = Header(None) ) -> dict: """Verify JWT token and return user info""" if not authorization or not authorization.startswith("Bearer "): raise HTTPException(status_code=401, detail="Missing authorization") token = authorization.replace("Bearer ", "") try: payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"]) return payload except JWTError: raise HTTPException(status_code=401, detail="Invalid token") ``` ```typescript TypeScript (Express) theme={null} import jwt from "jsonwebtoken"; function authenticateUser(req, res, next) { const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith("Bearer ")) { return res.status(401).json({ error: "Missing authorization" }); } const token = authHeader.replace("Bearer ", ""); try { const payload = jwt.verify(token, process.env.SECRET_KEY); req.user = payload; next(); } catch (error) { return res.status(401).json({ error: "Invalid token" }); } } ``` ## Create Dashboard Endpoint The `create_dashboard` function being called in the endpoint below should have already been created in the [Creating Dashboards](/documentation/multi-tenancy/creating-dashboards#creating-a-dashboard) guide. Create a new dashboard for a tenant. ```python Python (FastAPI) theme={null} from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel router = APIRouter(prefix="/api/v1/dashboards", tags=["dashboards"]) class DashboardCreate(BaseModel): tenant_id: str workspace_id: str name: str description: Optional[str] = None @router.post("/") async def create_dashboard( dashboard: DashboardCreate, current_user: Dict = Depends(get_authenticated_user), db: Session = Depends(get_db) ): """Create a dashboard for a tenant""" # Verify user has permission to create dashboard for this tenant if not has_access(current_user, dashboard.tenant_id): raise HTTPException(status_code=403, detail="Access denied") handler = DashboardHandler(db) result = await handler.create_dashboard( tenant_id=dashboard.tenant_id, workspace_id=dashboard.workspace_id, name=dashboard.name, description=dashboard.description, created_by=current_user["user_id"] ) return { "success": True, "data": result } ``` ```typescript TypeScript (Express) theme={null} import express from "express"; const router = express.Router(); router.post("/dashboards", authenticateUser, async (req, res) => { const { tenantId, workspaceId, name, description } = req.body; // Verify user has permission if (!hasAccess(req.user, tenantId)) { return res.status(403).json({ error: "Access denied" }); } try { const dashboard = await createDashboard( tenantId, workspaceId, name, description ); res.json({ success: true, data: dashboard, }); } catch (error) { res.status(500).json({ error: error.message, }); } }); ``` ```php PHP (Laravel) theme={null} validate([ 'tenant_id' => 'required|string', 'workspace_id' => 'required|string', 'name' => 'required|string', 'description' => 'nullable|string', ]); // Verify user has permission if (!hasAccess(Auth::user(), $validated['tenant_id'])) { return response()->json(['error' => 'Access denied'], 403); } $dashboard = createDashboardForTenant( $validated['tenant_id'], $validated['workspace_id'], $validated['name'], $validated['description'] ?? null ); return response()->json([ 'success' => true, 'data' => $dashboard ]); })->middleware('auth:api'); ?> ``` **Request:** ```bash theme={null} POST /api/v1/dashboards Authorization: Bearer YOUR_JWT_TOKEN { "tenant_id": "org-123", "workspace_id": "workspace-456", "name": "Sales Dashboard", "description": "Q4 Sales Analytics" } ``` **Response:** ```json theme={null} { "success": true, "data": { "id": "dashboard-789", "tenant_id": "org-123", "workspace_id": "workspace-456", "dashboard_id": "dashboard-789", "created_at": "2024-01-15T10:30:00Z" } } ``` ## Get Dashboard by Tenant Retrieve the dashboard for a specific tenant. ```python Python (FastAPI) theme={null} @router.get("/{tenant_id}") def get_dashboard_by_tenant( tenant_id: str, current_user: Dict = Depends(get_authenticated_user), db: Session = Depends(get_db) ): """Get dashboard for a specific tenant""" # Verify access if not has_access(current_user, tenant_id): raise HTTPException(status_code=403, detail="Access denied") handler = DashboardHandler(db) dashboard = handler.get_dashboard_by_tenant(tenant_id) if not dashboard: raise HTTPException(status_code=404, detail="Dashboard not found") return { "success": True, "data": dashboard } ``` ```typescript TypeScript (Express) theme={null} router.get("/dashboards/:tenantId", authenticateUser, async (req, res) => { const { tenantId } = req.params; // Verify access if (!hasAccess(req.user, tenantId)) { return res.status(403).json({ error: "Access denied" }); } const dashboard = await db.tenantDashboards.findOne({ where: { tenant_id: tenantId }, }); if (!dashboard) { return res.status(404).json({ error: "Dashboard not found" }); } res.json({ success: true, data: dashboard, }); }); ``` **Request:** ```bash theme={null} GET /api/v1/dashboards/org-123 Authorization: Bearer YOUR_JWT_TOKEN ``` **Response:** ```json theme={null} { "success": true, "data": { "id": "dashboard-789", "tenant_id": "org-123", "workspace_id": "workspace-456", "dashboard_id": "dashboard-789", "created_at": "2024-01-15T10:30:00Z" } } ``` ## Generate Iframe Token Generate a secure token for embedding a dashboard. ```python Python (FastAPI) theme={null} class DashboardIframeTokenRequest(BaseModel): tenant_id: str workspace_id: str dashboard_id: str valid_until: Optional[int] = None @router.post("/iframe-token") def create_iframe_token( request: DashboardIframeTokenRequest, current_user: Dict = Depends(get_authenticated_user), db: Session = Depends(get_db) ): """Generate secure token for embedding dashboard in iframe""" # Verify tenant belongs to user if not has_access(current_user, request.tenant_id): raise HTTPException(status_code=403, detail="Access denied") handler = DashboardHandler(db) token_data = handler.generate_iframe_token( tenant_id=request.tenant_id, workspace_id=request.workspace_id, dashboard_id=request.dashboard_id, valid_until=request.valid_until ) return { "success": True, "data": token_data } ``` ```typescript TypeScript (Express) theme={null} router.post("/dashboards/iframe-token", authenticateUser, async (req, res) => { const { tenantId, workspaceId, dashboardId, validUntil } = req.body; // Verify tenant belongs to user if (!hasAccess(req.user, tenantId)) { return res.status(403).json({ error: "Access denied" }); } const tokenData = generateIframeToken( tenantId, workspaceId, dashboardId, validUntil ); res.json({ success: true, data: tokenData, }); }); ``` **Request:** ```bash theme={null} POST /api/v1/dashboards/iframe-token Authorization: Bearer YOUR_JWT_TOKEN { "tenant_id": "org-123", "workspace_id": "workspace-456", "dashboard_id": "dashboard-789", "valid_until": 1700000000 // Optional: Unix timestamp } ``` **Response:** ```json theme={null} { "success": true, "data": { "token": "eyJhcGlfa2V5X2lkIjoieW91ci1hcGkta2V5IiwidGVuYW50X2lkIjoib3JnLTEyMyIsImRhc2hib2FyZF9pZCI6ImRhc2hib2FyZC03ODkiLCJ2YWxpZF91bnRpbCI6MTcwMDAwMDAwMCwic2lnbmF0dXJlIjoiYWJjMTIzLi4uIn0=", "dashboard_id": "dashboard-789", "expires_at": 1700000000 } } ``` ## List All Dashboards (Optional) List all dashboards for the authenticated user's organization. ```python Python (FastAPI) theme={null} @router.get("/") def list_dashboards( current_user: Dict = Depends(get_authenticated_user), db: Session = Depends(get_db), skip: int = 0, limit: int = 100 ): """List all dashboards for user's organization""" organization_id = current_user.get("organization_id") handler = DashboardHandler(db) dashboards = handler.list_dashboards( organization_id=organization_id, skip=skip, limit=limit ) return { "success": True, "data": dashboards, "total": len(dashboards) } ``` ```typescript TypeScript (Express) theme={null} router.get("/dashboards", authenticateUser, async (req, res) => { const organizationId = req.user.organizationId; const { skip = 0, limit = 100 } = req.query; const dashboards = await db.tenantDashboards.findAll({ where: { organization_id: organizationId }, offset: parseInt(skip), limit: parseInt(limit), }); res.json({ success: true, data: dashboards, total: dashboards.length, }); }); ``` ## Delete Dashboard (Optional) Delete a dashboard for a tenant. ```python Python (FastAPI) theme={null} @router.delete("/{tenant_id}") async def delete_dashboard( tenant_id: str, current_user: Dict = Depends(get_authenticated_user), db: Session = Depends(get_db) ): """Delete dashboard for a tenant""" # Verify access if not has_access(current_user, tenant_id): raise HTTPException(status_code=403, detail="Access denied") handler = DashboardHandler(db) success = await handler.delete_dashboard(tenant_id) if not success: raise HTTPException(status_code=404, detail="Dashboard not found") return { "success": True, "message": "Dashboard deleted successfully" } ``` ```typescript TypeScript (Express) theme={null} router.delete("/dashboards/:tenantId", authenticateUser, async (req, res) => { const { tenantId } = req.params; // Verify access if (!hasAccess(req.user, tenantId)) { return res.status(403).json({ error: "Access denied" }); } const deleted = await db.tenantDashboards.destroy({ where: { tenant_id: tenantId }, }); if (!deleted) { return res.status(404).json({ error: "Dashboard not found" }); } res.json({ success: true, message: "Dashboard deleted successfully", }); }); ``` ## Error Handling Implement consistent error handling across all endpoints: ```json theme={null} // Success Response { "success": true, "data": { ... } } // Error Response { "success": false, "error": "Error message here", "code": "ERROR_CODE" } ``` ### Common Error Codes | Code | Status | Description | | ------------------ | ------ | ------------------------------------ | | `UNAUTHORIZED` | 401 | Missing or invalid authentication | | `FORBIDDEN` | 403 | User doesn't have access to resource | | `NOT_FOUND` | 404 | Resource not found | | `VALIDATION_ERROR` | 422 | Invalid request parameters | | `SERVER_ERROR` | 500 | Internal server error | ## Rate Limiting Implement rate limiting to prevent abuse: ```python Python (FastAPI) theme={null} from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address limiter = Limiter(key_func=get_remote_address) @router.post("/iframe-token") @limiter.limit("10/minute") async def create_iframe_token(...): # ... implementation ``` ```typescript TypeScript (Express) theme={null} import rateLimit from "express-rate-limit"; const tokenLimiter = rateLimit({ windowMs: 60 * 1000, // 1 minute max: 10, // 10 requests per minute message: "Too many token requests, please try again later", }); router.post( "/dashboards/iframe-token", tokenLimiter, authenticateUser, async (req, res) => { // ... implementation } ); ``` ## Next Steps Learn about security considerations for production Set up the frontend to embed dashboards # HMAC Authentication Source: https://docs.papermap.ai/documentation/multi-tenancy/authentication This guide covers the HMAC signature authentication pattern used to secure requests to the Papermap Dashboard API. ## How HMAC Authentication Works The core security pattern uses HMAC-SHA256 to sign requests to the Papermap API: 1. Concatenate `workspace_id` + `valid_until` timestamp 2. Create HMAC-SHA256 hash using your secret key 3. Send signature + timestamp in headers 4. Papermap API verifies signature with the same secret ### Authentication Flow ``` Your API → Generate HMAC Signature payload = "workspace-456" + "1699999999" signature = HMAC-SHA256(payload, secret_key) Your API → Call Papermap Dashboard API POST ${PAPERMAP_API_URL}/api/v1/external/dashboards Headers: X-API-Key-ID: your-api-key X-Workspace-ID: workspace-456 X-Valid-Until: 1699999999 X-Signature: abc123... Papermap API → Verifies Signature - Extracts workspace_id and valid_until - Computes: HMAC-SHA256(workspace_id + valid_until, secret_key) - Compares computed signature with X-Signature header - Checks valid_until hasn't expired ``` If the signature doesn't match or the timestamp has expired, the request is rejected with a 401 Unauthorized error. ## Implementation by Language ```python Python theme={null} import hmac import hashlib import time def _create_signature(workspace_id: str, valid_until: str, secret_key: str) -> str: """Create HMAC signature for authentication""" payload = f"{workspace_id}{valid_until}" signature = hmac.new( secret_key.encode(), payload.encode(), hashlib.sha256 ).hexdigest() return signature def _get_auth_headers(workspace_id: str, api_key_id: str, secret_key: str) -> dict: """Generate authentication headers with HMAC signature""" valid_until = str(int(time.time()) + 300) # Valid for 5 minutes signature = _create_signature(workspace_id, valid_until, secret_key) return { "X-API-Key-ID": api_key_id, "X-Workspace-ID": workspace_id, "X-Valid-Until": valid_until, "X-Signature": signature, "Content-Type": "application/json" } ``` ```typescript TypeScript/Node.js theme={null} import crypto from "crypto"; class DashboardAPIService { private config: { apiKeyId: string; secretKey: string; workspaceId: string; baseUrl: string; }; constructor(config: any) { this.config = config; } private createSignature(workspaceId: string, validUntil: string): string { const payload = `${workspaceId}${validUntil}`; return crypto .createHmac("sha256", this.config.secretKey) .update(payload) .digest("hex"); } private getAuthHeaders(): Record { const validUntil = String(Math.floor(Date.now() / 1000) + 300); const signature = this.createSignature(this.config.workspaceId, validUntil); return { "X-API-Key-ID": this.config.apiKeyId, "X-Workspace-ID": this.config.workspaceId, "X-Valid-Until": validUntil, "X-Signature": signature, "Content-Type": "application/json", }; } } ``` ```php PHP theme={null} $apiKeyId, 'X-Workspace-ID' => $workspaceId, 'X-Valid-Until' => (string)$validUntil, 'X-Signature' => $signature, 'Content-Type' => 'application/json' ]; } ?> ``` ```java Java theme={null} import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.time.Instant; @Service public class DashboardAPIService { @Value("${dashboard.api.key}") private String apiKeyId; @Value("${dashboard.secret.key}") private String secretKey; private String createSignature(String workspaceId, String validUntil) throws Exception { String payload = workspaceId + validUntil; Mac hmac = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKeySpec = new SecretKeySpec( secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256" ); hmac.init(secretKeySpec); byte[] hash = hmac.doFinal(payload.getBytes(StandardCharsets.UTF_8)); return bytesToHex(hash); } private HttpHeaders getAuthHeaders(String workspaceId) throws Exception { long validUntil = Instant.now().getEpochSecond() + 300; String signature = createSignature(workspaceId, String.valueOf(validUntil)); HttpHeaders headers = new HttpHeaders(); headers.set("X-API-Key-ID", apiKeyId); headers.set("X-Workspace-ID", workspaceId); headers.set("X-Valid-Until", String.valueOf(validUntil)); headers.set("X-Signature", signature); headers.setContentType(MediaType.APPLICATION_JSON); return headers; } private String bytesToHex(byte[] bytes) { StringBuilder result = new StringBuilder(); for (byte b : bytes) { result.append(String.format("%02x", b)); } return result.toString(); } } ``` ```csharp C# theme={null} using System; using System.Security.Cryptography; using System.Text; public class DashboardAPIService { private readonly string _apiKeyId; private readonly string _secretKey; private readonly string _baseUrl; public DashboardAPIService(string apiKeyId, string secretKey, string baseUrl) { _apiKeyId = apiKeyId; _secretKey = secretKey; _baseUrl = baseUrl; } private string CreateSignature(string workspaceId, string validUntil) { var payload = $"{workspaceId}{validUntil}"; var keyBytes = Encoding.UTF8.GetBytes(_secretKey); var payloadBytes = Encoding.UTF8.GetBytes(payload); using (var hmac = new HMACSHA256(keyBytes)) { var hash = hmac.ComputeHash(payloadBytes); return BitConverter.ToString(hash).Replace("-", "").ToLower(); } } private Dictionary GetAuthHeaders(string workspaceId) { var validUntil = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 300; var signature = CreateSignature(workspaceId, validUntil.ToString()); return new Dictionary { { "X-API-Key-ID", _apiKeyId }, { "X-Workspace-ID", workspaceId }, { "X-Valid-Until", validUntil.ToString() }, { "X-Signature", signature }, { "Content-Type", "application/json" } }; } } ``` ```go Go theme={null} package dashboard import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "time" ) type DashboardAPIService struct { APIKeyID string SecretKey string BaseURL string } func (s *DashboardAPIService) createSignature(workspaceID, validUntil string) string { payload := workspaceID + validUntil h := hmac.New(sha256.New, []byte(s.SecretKey)) h.Write([]byte(payload)) return hex.EncodeToString(h.Sum(nil)) } func (s *DashboardAPIService) getAuthHeaders(workspaceID string) map[string]string { validUntil := fmt.Sprintf("%d", time.Now().Unix()+300) signature := s.createSignature(workspaceID, validUntil) return map[string]string{ "X-API-Key-ID": s.APIKeyID, "X-Workspace-ID": workspaceID, "X-Valid-Until": validUntil, "X-Signature": signature, "Content-Type": "application/json", } } ``` ## Token Expiration * **API requests**: 5 minutes validity(advisable) based on the example above (`valid_until = now + 300`) * Expired tokens are automatically rejected ## Security Best Practices **Never hardcode API credentials:** - Always use environment variables or a secrets management system - The API endpoint URL should be treated as sensitive configuration - Store credentials securely and rotate them regularly ### Environment Configuration Store your credentials securely: ```bash .env theme={null} PAPERMAP_API_KEY_ID=your-api-key-id PAPERMAP_SECRET_KEY=your-secret-key-never-share PAPERMAP_API_URL= ``` **Obtaining Your Configuration:** - **API Credentials**: Available in your Papermap dashboard under **Settings → API Keys** - **API Endpoint**: Available in **Settings → API Configuration** - Always use the values provided in your dashboard for your specific workspace ## Next Steps Learn how to create and manage dashboards for your tenants Generate secure tokens for embedding dashboards # Backend Implementation Source: https://docs.papermap.ai/documentation/multi-tenancy/backend This guide provides an overview of implementing secure tenant dashboard management using HMAC signature authentication for enterprise-grade multi-tenant security. ## Architecture Overview ``` Your API (Tenant Management) ↓ HMAC Signed Request → Papermap Dashboard API ↓ Dashboard Created/Retrieved ↓ Generate Iframe Token (HMAC Signed) ↓ Frontend Embeds Dashboard ``` ### Key Components 1. **TenantDashboard Model** - Maps tenants to Papermap dashboards 2. **HMAC Signature Service** - Securely authenticates API requests 3. **Dashboard Handler** - Creates dashboards and generates embed tokens 4. **Dashboard Router** - API endpoints for dashboard operations ## Quick Start Follow these guides in order to implement the backend: Implement HMAC signature authentication to securely communicate with the Papermap API. Learn how to implement HMAC-SHA256 signature authentication Set up the ability to create and manage dashboards for your tenants. Learn how to create dashboards via the Papermap API Generate secure tokens to embed dashboards in your frontend. Learn how to generate secure embed tokens Create REST API endpoints for your frontend to interact with. Example REST API endpoints for dashboard operations Follow security best practices for production deployment. Learn about security considerations and best practices ## Database Model First, create a model to link your tenants to their Papermap dashboards: It is not required to save it this way, but you need to have a way to map your tenant to their dashboards. ```python Python theme={null} from sqlalchemy import Column, String from .database import Base class TenantDashboard(BaseModel): __tablename__ = 'tenant_dashboards' tenant_id = Column(String(255), nullable=False, index=True) workspace_id = Column(String(255), nullable=False) dashboard_id = Column(String(255), nullable=False) ``` ```sql POSTGRESQL theme={null} CREATE TABLE tenant_dashboards ( id SERIAL PRIMARY KEY, tenant_id VARCHAR(255) NOT NULL, workspace_id VARCHAR(255) NOT NULL, dashboard_id VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_tenant_id ON tenant_dashboards (tenant_id); ``` ```sql MYSQL theme={null} CREATE TABLE tenant_dashboards ( id INT AUTO_INCREMENT PRIMARY KEY, tenant_id VARCHAR(255) NOT NULL, workspace_id VARCHAR(255) NOT NULL, dashboard_id VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_tenant_id (tenant_id) ); ``` **Purpose**: Links your tenant to a Papermap dashboard ID for secure access and isolation. ## Prerequisites Before implementing, ensure you have: * Papermap API credentials (API Key ID and Secret Key) * Your workspace ID * API endpoint URL (obtain from your Papermap dashboard settings) **Security Best Practices:** - Never hardcode API endpoints, keys, or secrets in your code - Always use environment variables or a secrets management system * The API endpoint URL should be treated as sensitive configuration - Store credentials securely and rotate them regularly ## Environment Configuration Store your credentials securely in environment variables: ```bash .env theme={null} PAPERMAP_API_KEY_ID=your-api-key-id PAPERMAP_SECRET_KEY=your-secret-key-never-share PAPERMAP_API_URL= ``` **Obtaining Your Configuration:** - **API Credentials**: Available in your Papermap dashboard under **Settings → API Keys** - **API Endpoint**: Available in **Settings → API Configuration** - Always use the values provided in your dashboard for your specific workspace ## Implementation Guides Implement secure HMAC signature authentication Create and manage dashboards for tenants Generate secure embed tokens Build REST API endpoints Track per-tenant credit consumption Security best practices Performance and scalability tips ## Common Pattern Reference The HMAC signature pattern for tenant dashboards follows this flow: ``` 1. Create Payload payload = workspace_id + valid_until 2. Generate Signature signature = HMAC-SHA256(payload, secret_key) 3. Send Request with Headers X-API-Key-ID: X-Workspace-ID: X-Valid-Until: X-Signature: 4. Store Result tenant_id → dashboard_id mapping 5. Generate Embed Token Encode {tenant_id, dashboard_id, signature, expires} as base64 ``` This pattern ensures secure, time-limited access to tenant-specific dashboards. ## Next Steps Learn how to embed dashboards in your frontend application # Best Practices Source: https://docs.papermap.ai/documentation/multi-tenancy/best-practices This guide covers security, performance, scalability, and troubleshooting best practices for production multi-tenant applications. ### Performance Optimization 1. **Cache tenant configurations**: Reduce API calls by caching tenant settings 2. **Use CDN for embeds**: Serve embedded dashboards through a CDN 3. **Implement lazy loading**: Load dashboards only when needed 4. **Monitor performance per tenant**: Track load times and API response times ### Security Best Practices 1. **Never expose API keys**: Always generate tokens server-side 2. **Implement CORS**: Restrict embed domains per tenant 3. **Use HTTPS everywhere**: Enforce secure connections 4. **Audit trail**: Log all tenant access and modifications 5. **Regular security audits**: Review tenant access patterns ### Scalability Considerations 1. **Database per tenant**: For large clients, consider dedicated databases 2. **Implement rate limiting**: Prevent resource exhaustion 3. **Queue background jobs**: Process tenant tasks asynchronously 4. **Monitor resource usage**: Alert on unusual patterns 5. **Plan for growth**: Design for 10x current tenant count ## Troubleshooting ### Common Issues **1. Tenant data mixing** * Verify workspace IDs are correct * Check API key scoping * Review query filters **2. Branding not applying** * Clear browser cache * Verify branding configuration * Check embed parameter syntax **3. Performance degradation** * Review tenant resource usage * Implement query optimization * Consider tenant database sharding **4. Authentication failures** * Verify API keys are active * Check token expiration * Review CORS configuration ### Debugging Multi-Tenant Issues Enable debug mode in embeds: ```html theme={null} ``` Check browser console for detailed error messages and network requests. ## Migration Guide ### Moving from Single to Multi-Tenant If you're migrating from a single-tenant to multi-tenant architecture: 1. **Audit current setup**: Document existing data sources and dashboards 2. **Plan tenant structure**: Decide how to split existing data 3. **Create tenant workspaces**: Set up workspaces for each tenant 4. **Migrate data**: Export and import data to appropriate tenants 5. **Update embed codes**: Replace single workspace with tenant-specific embeds 6. **Test thoroughly**: Verify data isolation and permissions 7. **Deploy gradually**: Roll out to tenants in phases ## Next Steps * Read the [Embedding Guide](/documentation/embedding) for more on embedding * Join our [Community Forum](https://discord.gg/BbjGm8jW) for discussions * Contact [team@papermap.ai](mailto:team@papermap.ai) for enterprise guidance *** *Ready to build a multi-tenant analytics platform? [Book a session](https://calendly.com/admin-pappermap/30min) and we will help you enable multi-tenancy.* # Creating Dashboards Source: https://docs.papermap.ai/documentation/multi-tenancy/creating-dashboards This guide covers how to create dashboards for your tenants using the Papermap Dashboard API. The `dashboardId` created through this flow can be used in both iframe embedding and React component embedding with [`@papermap/papermap`](/documentation/embedding/react-components). ## Prerequisites Before implementing, ensure you have: * Papermap API credentials (API Key ID and Secret Key) * Your workspace ID * API endpoint URL (obtain from your Papermap dashboard settings) * HMAC authentication implemented (see [Authentication](/documentation/multi-tenancy/authentication)) ## Database Model First, you should have created a table in your database to store the mapping between your tenant and the dashboard ID. See the [Database Model section in Backend Implementation](/documentation/multi-tenancy/backend#database-model) for details. **Purpose**: Links your tenant to a Papermap dashboard ID for secure access and isolation. ## Creating a Dashboard The base URL for the Papermap API is `https://prod.dataapi.papermap.ai/`. The `get_auth_headers` function is a helper function that generates the HMAC signature for the API request found in the [HMAC Authentication](/documentation/multi-tenancy/authentication) Create a dashboard via the Papermap API for each tenant: ```python Python theme={null} import httpx async def create_dashboard( tenant_id: str, workspace_id: str, name: str, description: Optional[str] = None, created_by: Optional[str] = None ): # 1. Call Papermap API with HMAC signature headers = _get_auth_headers(workspace_id, API_KEY_ID, SECRET_KEY) payload = { "workspace_id": workspace_id, "title": name, "description": description } async with httpx.AsyncClient() as client: response = await client.post( f"{PAPERMAP_API_URL}/api/v1/external/dashboards", headers=headers, json=payload ) external_dashboard = response.json() dashboard_id = external_dashboard["data"]["data"]["dashboard_id"] # 2. Store mapping in your database tenant_dashboard = TenantDashboard.create( session=db, tenant_id=tenant_id, workspace_id=workspace_id, dashboard_id=dashboard_id, created_by=created_by ) return tenant_dashboard ``` ```typescript TypeScript/Node.js theme={null} import axios from "axios"; async function createDashboard( tenantId: string, workspaceId: string, name: string, description?: string ) { const service = new DashboardAPIService({ apiKeyId: process.env.PAPERMAP_API_KEY_ID, secretKey: process.env.PAPERMAP_SECRET_KEY, workspaceId: workspaceId, baseUrl: process.env.PAPERMAP_API_URL, }); const headers = service.getAuthHeaders(); const response = await axios.post( `${service.config.baseUrl}/api/v1/external/dashboards`, { workspace_id: workspaceId, title: name, description, }, { headers } ); const dashboardId = response.data.data.dashboard_id; // Store mapping in your database await db.tenantDashboards.create({ tenant_id: tenantId, workspace_id: workspaceId, dashboard_id: dashboardId, }); return { dashboardId, ...response.data }; } ``` ```php PHP theme={null} $workspaceId, 'title' => $name, 'description' => $description ]; $ch = curl_init(getenv('PAPERMAP_API_URL') . '/api/v1/external/dashboards'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload)); $headerArray = []; foreach ($headers as $key => $value) { $headerArray[] = "$key: $value"; } curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response, true); $dashboardId = $data['data']['data']['id']; // Store mapping in your database DB::table('tenant_dashboards')->insert([ 'tenant_id' => $tenantId, 'workspace_id' => $workspaceId, 'dashboard_id' => $dashboardId ]); return ['dashboard_id' => $dashboardId, 'data' => $data]; } ?> ``` ```java Java theme={null} public DashboardResponse createDashboard( String workspaceId, String name, String description ) throws Exception { HttpHeaders headers = getAuthHeaders(workspaceId); Map payload = new HashMap<>(); payload.put("workspace_id", workspaceId); payload.put("title", name); payload.put("description", description); HttpEntity> request = new HttpEntity<>(payload, headers); ResponseEntity response = restTemplate.exchange( baseUrl + "/api/v1/external/dashboards", HttpMethod.POST, request, DashboardResponse.class ); return response.getBody(); } ``` ```csharp C# theme={null} public async Task CreateDashboard( string workspaceId, string name, string description = null ) { var headers = GetAuthHeaders(workspaceId); var request = new HttpRequestMessage( HttpMethod.Post, $"{_baseUrl}/api/v1/external/dashboards" ); foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } var payload = new { workspace_id = workspaceId, title = name, description }; request.Content = new StringContent( JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json" ); var response = await _httpClient.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize(content); } ``` ```go Go theme={null} func (s *DashboardAPIService) CreateDashboard( workspaceID, name, description string, ) (*Dashboard, error) { headers := s.getAuthHeaders(workspaceID) payload := map[string]string{ "workspace_id": workspaceID, "title": name, "description": description, } jsonData, _ := json.Marshal(payload) req, _ := http.NewRequest( "POST", s.BaseURL+"/api/v1/external/dashboards", strings.NewReader(string(jsonData)), ) for key, value := range headers { req.Header.Set(key, value) } resp, err := s.Client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() var result Dashboard json.NewDecoder(resp.Body).Decode(&result) return &result, nil } ``` ## Workflow Diagram ``` 1. Client Request → POST /api/v1/dashboards { "tenant_id": "org-123", "workspace_id": "workspace-456", "name": "Sales Dashboard" } 2. Your API → Generate HMAC Signature payload = "workspace-456" + "1699999999" signature = HMAC-SHA256(payload, secret_key) 3. Your API → Call Papermap Dashboard API POST ${PAPERMAP_API_URL}/api/v1/external/dashboards Headers: X-API-Key-ID: your-api-key X-Workspace-ID: workspace-456 X-Valid-Until: 1699999999 X-Signature: abc123... 4. Papermap API → Returns Dashboard {data:... {data: {dashboard_id: "dashboard-789", ...}}} 5. Your API → Store Mapping in Database TenantDashboard: tenant_id: org-123 workspace_id: workspace-456 dashboard_id: dashboard-789 6. Return to Client { "success": true, "data": {...} } ``` ## Key Considerations ### Tenant Isolation Each tenant should have their own dashboard: * One dashboard per tenant ensures data isolation * Store the tenant-to-dashboard mapping in your database * Verify tenant ownership before allowing access ### Dashboard Naming Use clear, consistent naming conventions: * Include tenant identifier in dashboard name * Example: `"Dashboard - Acme Corp"` or `"Acme Corp Analytics"` * Makes management easier in the Papermap admin panel ### Error Handling Handle common errors gracefully: ```python theme={null} try: dashboard = await create_dashboard(tenant_id, workspace_id, name) except httpx.HTTPStatusError as e: if e.response.status_code == 401: # Invalid credentials or expired signature raise Exception("Authentication failed") elif e.response.status_code == 409: # Dashboard already exists raise Exception("Dashboard already exists for this tenant") else: # Other errors raise Exception(f"Failed to create dashboard: {e}") ``` ## Next Steps Learn how to generate secure embed tokens for your dashboards Set up REST API endpoints for dashboard operations # Iframe Embed Tokens Source: https://docs.papermap.ai/documentation/multi-tenancy/iframe-tokens This guide covers how to generate secure, time-limited tokens for embedding dashboards in your application. This page is specifically about the multi-tenant iframe token flow. If you are embedding Papermap through `@papermap/papermap`, see [React Components](/documentation/embedding/react-components) for the component integration flow and how it uses `workspaceId`, `dashboardId`, and backend token generation. ## Overview Iframe tokens allow you to securely embed Papermap dashboards in your application. Each token: * Is signed with HMAC-SHA256 for security * Has a configurable expiration time * Is specific to a tenant and dashboard * Can only be used for the specified dashboard ## Token Structure The token contains: * `api_key_id`: Your API key identifier * `workspace_id`: Your workspace ID * `tenant_id`: The tenant identifier * `dashboard_id`: The specific dashboard ID * `valid_until`: Unix timestamp when token expires * `signature`: HMAC signature for verification ## Generating Iframe Tokens This token generation is different from the one in the [Basic Embedding](/documentation/embedding/basic-embedding#backend%3A-generating-embed-tokens) section. The token generation in this section is for multi-tenant iframe embedding. The tenant-aware `dashboardId` and backend provisioning model described here can still be relevant when your application uses React components, but this page documents the iframe-specific token flow. ```python Python theme={null} import json import base64 import time def generate_iframe_token( tenant_id: str, workspace_id: str, dashboard_id: str, valid_until: Optional[int] = None ): # 1. Get tenant's dashboard tenant_dashboard = TenantDashboard.read( session=db, filter_by={"tenant_id": tenant_id} ) if not tenant_dashboard: raise Exception("Dashboard not found for tenant") # 2. Set expiration (default 1 hour) if valid_until is None: valid_until = int(time.time()) + 3600 # 3. Create HMAC signature payload = f"{workspace_id}{valid_until}" signature = hmac.new( SECRET_KEY.encode(), payload.encode(), hashlib.sha256 ).hexdigest() # 4. Encode token token_data = { "api_key_id": API_KEY_ID, "workspace_id": workspace_id, "tenant_id": tenant_id, "dashboard_id": dashboard_id, "valid_until": valid_until, "signature": signature } token_json = json.dumps(token_data) encoded_token = base64.urlsafe_b64encode(token_json.encode()).decode() return { "token": encoded_token, "dashboard_id": dashboard_id, "expires_at": valid_until } ``` ```typescript TypeScript/Node.js theme={null} function generateIframeToken( tenantId: string, workspaceId: string, dashboardId: string, validUntil?: number ): string { const expiresAt = validUntil || Math.floor(Date.now() / 1000) + 3600; const validUntilStr = String(expiresAt); const signature = this.createSignature(workspaceId, validUntilStr); const tokenData = { api_key_id: this.config.apiKeyId, workspace_id: workspaceId, tenant_id: tenantId, dashboard_id: dashboardId, valid_until: expiresAt, signature, }; return Buffer.from(JSON.stringify(tokenData)).toString("base64url"); } // Express endpoint app.post("/api/dashboards/iframe-token", authenticateUser, async (req, res) => { const { tenantId, workspaceId, dashboardId } = req.body; // Verify tenant belongs to user if (req.user.tenantId !== tenantId) { return res.status(403).json({ error: "Access denied" }); } const token = generateIframeToken(tenantId, workspaceId, dashboardId); res.json({ token, dashboard_id: dashboardId }); }); ``` ```php PHP theme={null} getenv('PAPERMAP_API_KEY_ID'), 'workspace_id' => $workspaceId, 'tenant_id' => $tenantId, 'dashboard_id' => $dashboardId, 'valid_until' => $expiresAt, 'signature' => $signature ]; $token = base64_encode(json_encode($tokenData)); $token = str_replace(['+', '/', '='], ['-', '_', ''], $token); return [ 'token' => $token, 'dashboard_id' => $dashboardId, 'expires_at' => $expiresAt ]; } ?> ``` ```java Java theme={null} public String generateIframeToken( String tenantId, String workspaceId, String dashboardId, Long validUntil ) throws Exception { if (validUntil == null) { validUntil = Instant.now().getEpochSecond() + 3600; } String signature = createSignature(workspaceId, String.valueOf(validUntil)); Map tokenData = new HashMap<>(); tokenData.put("api_key_id", apiKeyId); tokenData.put("workspace_id", workspaceId); tokenData.put("tenant_id", tenantId); tokenData.put("dashboard_id", dashboardId); tokenData.put("valid_until", validUntil); tokenData.put("signature", signature); String json = objectMapper.writeValueAsString(tokenData); return Base64.getUrlEncoder() .withoutPadding() .encodeToString(json.getBytes(StandardCharsets.UTF_8)); } ``` ```csharp C# theme={null} public string GenerateIframeToken( string tenantId, string workspaceId, string dashboardId, long? validUntil = null ) { var expiresAt = validUntil ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 3600; var signature = CreateSignature(workspaceId, expiresAt.ToString()); var tokenData = new { api_key_id = _apiKeyId, workspace_id = workspaceId, tenant_id = tenantId, dashboard_id = dashboardId, valid_until = expiresAt, signature }; var json = JsonSerializer.Serialize(tokenData); var bytes = Encoding.UTF8.GetBytes(json); return Convert.ToBase64String(bytes) .Replace('+', '-') .Replace('/', '_') .TrimEnd('='); } ``` ```go Go theme={null} func (s *DashboardAPIService) GenerateIframeToken( tenantID, workspaceID, dashboardID string, validUntil *int64, ) (string, error) { var expiresAt int64 if validUntil == nil { expiresAt = time.Now().Unix() + 3600 } else { expiresAt = *validUntil } signature := s.createSignature( workspaceID, fmt.Sprintf("%d", expiresAt), ) tokenData := map[string]interface{}{ "api_key_id": s.APIKeyID, "workspace_id": workspaceID, "tenant_id": tenantID, "dashboard_id": dashboardID, "valid_until": expiresAt, "signature": signature, } jsonData, _ := json.Marshal(tokenData) encoded := base64.URLEncoding.EncodeToString(jsonData) return strings.TrimRight(encoded, "="), nil } ``` ## Using the Token in Frontend Once you have the token, embed the dashboard using an iframe: ```html theme={null} ``` ### React Example ```tsx theme={null} import React, { useState, useEffect } from "react"; function DashboardEmbed({ tenantId, workspaceId, dashboardId }) { const [token, setToken] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchToken() { const response = await fetch("/api/dashboards/iframe-token", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ tenantId, workspaceId, dashboardId }), }); const data = await response.json(); setToken(data.token); setLoading(false); } fetchToken(); }, [tenantId, workspaceId, dashboardId]); if (loading) return
Loading dashboard...
; return (