PlaySpace

Guide: Using the API from other languages

Nothing in the integration needs JavaScript on your server. The server half is plain HTTPS against the Partner API, and the browser half is one iframe and a few messages. A page rendered by Python, PHP, Java, C# or Ruby frames the same dashboard as a React application.

This guide covers both halves without npm: generating or writing the server calls, then framing the dashboard either with @playspace-health/embed loaded from a CDN or with no package at all.


The server half

Generate a client

The Partner API is described by an OpenAPI document, published on this site as openapi.json and openapi.yaml. Any OpenAPI generator turns it into a typed client:

# Python
npx @openapitools/openapi-generator-cli generate \
  -i https://docs.playspace.health/openapi.json -g python -o playspace_client

# PHP (the generator itself needs Java 11 or later)
npx @openapitools/openapi-generator-cli generate \
  -i https://docs.playspace.health/openapi.json -g php -o playspace-client

Regenerate when the changelog announces a change. Within /v1 new fields and values are added without notice, so configure the generated client to ignore fields it does not recognise rather than fail on them.

What no generator gives you

Four things are yours whichever language you use:

  • The access token. Exchange your client credentials on the authorisation server, cache the token, and reuse it until shortly before it expires. See authentication.
  • Idempotency keys. Every POST, PATCH and DELETE carries an Idempotency-Key, except minting a sign-in code, creating a webhook endpoint and rotating its secret. Generate one per logical operation and keep it across that operation's retries.
  • Who the clinician is. Your sign-in code route decides it from your own session. No generated client can.
  • The browser half, below.

Mint a sign-in code without a client

The whole server half is one route that calls one operation. In Python, with Flask and requests:

import requests
from flask import Flask, jsonify, request, session

PLAYSPACE = "https://agentic-ps.playspace.health"
app = Flask(__name__)

@app.post("/playspace/sign-in-code")
def sign_in_code():
    practitioner_id = session.get("playspace_practitioner_id")  # from your own sign-in, never the request
    if not practitioner_id:
        return "Not signed in", 401

    body = request.get_json(silent=True) or {}
    payload = {"path": body["path"]} if body.get("path") else {}

    response = requests.post(
        f"{PLAYSPACE}/v1/partner/practitioners/{practitioner_id}/sign-in-codes",
        headers={"Authorization": f"Bearer {cached_access_token()}"},
        json=payload,
        timeout=5,
    )
    if response.status_code != 201:
        app.logger.warning("sign-in code refused: %s %s", response.status_code, response.headers.get("X-Request-Id"))
        return "PlaySpace sign-in unavailable", 502

    reply = jsonify({"code": response.json()["data"]["code"]})
    reply.headers["Cache-Control"] = "no-store"
    return reply

The same in PHP:

<?php
// POST /playspace/sign-in-code
$practitionerId = $_SESSION['playspace_practitioner_id'] ?? null; // from your own sign-in
if ($practitionerId === null) { http_response_code(401); exit; }

$input = json_decode(file_get_contents('php://input'), true) ?: [];
$payload = isset($input['path']) && $input['path'] !== '' ? ['path' => $input['path']] : new stdClass();

$ch = curl_init("https://agentic-ps.playspace.health/v1/partner/practitioners/{$practitionerId}/sign-in-codes");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 5,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . cachedAccessToken(), 'Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

if ($status !== 201) { http_response_code(502); exit; }

header('Content-Type: application/json');
header('Cache-Control: no-store');
echo json_encode(['code' => json_decode($body, true)['data']['code']]);

Return only the code. The response also carries start_url and expires_at, which your page does not need. Log the status and the X-Request-Id of a refusal, never the body of a success: the code is a credential until it is spent.


The browser half: load the package from a CDN

@playspace-health/embed is one dependency-free ES module, so a server-rendered page loads it from any CDN that mirrors npm:

<div id="playspace" style="height: 820px"></div>

<script type="module">
  import { mount } from 'https://cdn.jsdelivr.net/npm/@playspace-health/embed@2.0.0/dist/index.js'

  mount({
    container: document.getElementById('playspace'),
    ehrOrigin: 'https://agentic-ps.playspace.health',
    getCode: ({ path }) =>
      fetch('/playspace/sign-in-code', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ path }),
      })
        .then((response) => {
          if (!response.ok) throw new Error(`sign-in code request failed: ${response.status}`)
          return response.json()
        })
        .then((body) => body.code),
    path: '/dashboard',
  })
</script>

Keep the version in the URL. A URL without one follows the newest release, and an upgrade should be your decision. If your page sends a Content Security Policy, its script-src must allow the CDN.


The browser half with no package

The package is a thin layer over a small message protocol, and a page can speak it directly. This is the whole of it:

<div id="playspace" style="height: 820px"></div>

<script>
  const PLAYSPACE = 'https://agentic-ps.playspace.health'

  const iframe = document.createElement('iframe')
  iframe.title = 'PlaySpace'
  iframe.allow =
    'camera; microphone; display-capture; fullscreen; autoplay; clipboard-read; clipboard-write; picture-in-picture; screen-wake-lock'
  iframe.setAttribute('allowfullscreen', '')
  iframe.style.cssText = 'width: 100%; height: 100%; border: 0'
  document.getElementById('playspace').appendChild(iframe)

  async function signInCode(path) {
    const response = await fetch('/playspace/sign-in-code', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(path ? { path } : {}),
    })
    if (!response.ok) throw new Error('sign-in code request failed: ' + response.status)
    return (await response.json()).code
  }

  window.addEventListener('message', async (event) => {
    // Only the PlaySpace origin, and only this iframe.
    if (event.origin !== PLAYSPACE || event.source !== iframe.contentWindow) return
    const message = event.data || {}

    if (message.type === 'playspace:session-code-needed' && typeof message.nonce === 'string') {
      const code = await signInCode()
      iframe.contentWindow.postMessage({ type: 'playspace:session-code', nonce: message.nonce, code }, PLAYSPACE)
    } else if (message.type === 'playspace:signed-out') {
      // The clinician is signed out of PlaySpace.
    } else if (message.type === 'playspace:frame-unsupported') {
      // message.reason is 'cookie' or 'browser'.
    }
  })

  signInCode('/dashboard').then((code) => {
    iframe.src = PLAYSPACE + '/frame/start?token=' + encodeURIComponent(code)
  })

  // Call this when your own user signs out; wait for playspace:signed-out.
  function signOutOfPlaySpace() {
    iframe.src = PLAYSPACE + '/frame/sign-out'
  }
</script>

The messages, in full:

Direction Message What to do
Frame to page { "type": "playspace:session-code-needed", "nonce": "<random>" } Mint a code and post { "type": "playspace:session-code", "nonce": "<the same nonce>", "code": "<code>" } to the iframe, with the PlaySpace origin as the target, within 10 seconds
Frame to page { "type": "playspace:signed-out" } The session ended: after your sign-out, or because PlaySpace ended it
Frame to page { "type": "playspace:frame-unsupported", "reason": "cookie" } The browser refused the framed session, and PlaySpace is offering its own window
Frame to page { "type": "playspace:frame-unsupported", "reason": "browser" } PlaySpace is showing a "Chrome is recommended" warning

What a bare frame must get right

  • Check both event.origin and event.source before acting on a message. The origin proves it came from PlaySpace, the source proves it came from your frame and not another PlaySpace frame on the page.
  • Post the code to the PlaySpace origin, never to *. The code is the one credential that reaches the browser, and a wildcard target would hand it to whatever document the frame holds at that moment.
  • Echo the nonce. The frame accepts a code only for a request it made.
  • Set the allow attribute exactly, and no sandbox. Live sessions use the camera, microphone and screen share inside the frame, and a cross-origin frame without them fails before any permission prompt appears.
  • Put the code in the address once. /frame/start exchanges it and moves the frame on, so the code leaves the frame's address straight away.

Everything else, from settings to browsers to session limits, is the same as with the package: see Frame the PlaySpace dashboard.