---
title: Integrate SurveyJS with FastAPI
description: Learn how to connect SurveyJS to a FastAPI backend to collect answers, display results, edit forms, and run SurveyJS on the server.
source: https://surveyjs.io/documentation/backend-integration-python-fastapi
---

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Integrate SurveyJS with %7B%40 backend %40%7D&value=backend:FastAPI --->

# Integrate SurveyJS with FastAPI

SurveyJS libraries enable you to display and edit web forms, collect answers, analyze results, and generate PDF forms in the browser. Your backend supplies the data these libraries need and stores the changes they produce. The libraries exchange JSON with your backend, which allows you to use any database and storage services.

This guide explains how to integrate SurveyJS with your FastAPI backend. It walks through all backend-specific workflows, starting with the minimum integration: saving a completed response. Each workflow description provides client and server code samples and a link to a live example.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Integrate SurveyJS with %7B%40 backend %40%7D&value=backend:FastAPI --->

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Run Forms --->

## Run Forms

[SurveyJS Form Library](/form-library/documentation/overview) displays a form using a JSON schema and collects the respondent's answers. Start integration by adding an endpoint that saves those answers. You can then load data from the server, save progress in unfinished forms, and add the other features described below if your application needs them.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Run Forms --->

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Save Responses --->

### Save Responses

To collect responses, your backend needs an endpoint that accepts and stores answers. The form JSON schema can be a JavaScript constant on the page for now—this first step does not require an endpoint for loading it.

When the respondent completes the form, SurveyJS raises the [`onComplete`](/form-library/documentation/api-reference/survey-data-model#onComplete) event. Handle it to send `survey.data` and the form ID to your save endpoint. The backend should store the answers as a single JSON document and return the saved response's ID to confirm that the save succeeded.

> Store the response exactly as it arrives—spaces, empty strings, and empty objects may be meaningful.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Save Responses --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/save-response.js#L6-L29 --->

```js
// Define the form directly in the page - no database needed
const definition = {
  title: "Contact us", completeText: "Send message",
  elements: [
    { type: "text", name: "email", title: "Your email", inputType: "email", isRequired: true },
    { type: "comment", name: "message", title: "How can we help?", isRequired: true }
  ]
};
const survey = new Model(definition);
// Save after completion; SurveyJS offers a retry action if saving fails
survey.onComplete.add(async (sender, options) => {
  try {
    const response = await fetch("/api/responses", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ formId: "contact", data: sender.data })
    });
    const { id } = response.ok ? await response.json() : {};
    if (!Number.isInteger(id) || id < 1) throw new Error("Missing response ID");
    sender.setVariable("responseId", id);
    options.showSaveSuccess();
  } catch {
    options.showSaveError("We couldn't save your message. Please try again.");
  }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/save-response.js#L6-L29 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/save_response.py#L15-L24 --->

```python
# POST /api/responses: Store submitted answers as one JSON document
@router.post("/api/responses", status_code=201)
def save_response(body: JsonBody, db: Db) -> dict[str, int]:
    # The raw body, not a Pydantic model: a model would drop unknown keys and coerce values in the answers
    if not isinstance(body, dict) or "formId" not in body or "data" not in body:
        raise HTTPException(400, "Expected { formId, data }")

    id = insert_response(db, body["formId"], body["data"])   # stored as it arrived: {} stays {}, 1.0 stays 1.0

    return {"id": id}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/save_response.py#L15-L24 --->

</details>

[Live Example: Save Responses](https://python-fastapi.demos.surveyjs.io/examples/save-response (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Load JSON Schemas%2C Variables%2C and Answers --->

### Load JSON Schemas, Variables, and Answers

As your application grows, the same form may need to dynamically change, behave differently for different users, or open with answers already filled in. Your backend can provide the JSON schema, variables, and previous answers needed to prepare the form.

- JSON schema\
  Form JSON schema describes the questions, layout, and logic. You can include the schema in the page when the latter renders or fetch it from an endpoint before displaying the form. In either case, the server can dynamically adjust the schema for the current request.

- Variables\
  Variables provide context for the form. For example, the current user's name can appear in a title, and their subscription plan can control which questions are visible. Variables are excluded from the saved answers.

- Previous answers\
  If the user is returning to an existing record, also load its answers and assign them to `survey.data`. The form then opens with those values already filled in.

An endpoint can return all three pieces of data in one request.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Load JSON Schemas%2C Variables%2C and Answers --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/load-definition-variables-data.js#L5-L21 --->

```js
import { Model } from "survey-core";

async function createSurvey(recordId) {
  if (window.FORM_DEFINITION) {
    // Option A: Use the schema and user variables embedded in the HTML response
    const survey = new Model(window.FORM_DEFINITION);
    survey.setVariables(window.FORM_VARIABLES);
    return survey;
  }
  // Option B: Load the definition, variables, and previous answers in one request
  const { definition, variables, data } =
    await fetch(`/api/forms/claim-request?record=${encodeURIComponent(recordId)}`).then(r => r.json());
  const survey = new Model(definition);
  survey.setVariables(variables);   // Variables are available in expressions such as {user.name} and are excluded from survey.data
  survey.data = data;               // Restore previously saved answers for editing
  return survey;
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/load-definition-variables-data.js#L5-L21 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/load_definition_variables_data.py#L23-L46 --->

```python
# Option A: Embed the schema and user variables in the HTML response
@router.get("/claim", response_class=HTMLResponse)
def claim_page(request: Request, user: CurrentUser) -> Response:
    definition = json.loads(DEFINITION.read_text(encoding="utf-8"))
    variables = {"user": {"name": user.name if user else None, "plan": user.plan if user else None}}
    # The template writes both with Jinja's tojson, which escapes them for an inline <script>
    return render_example(request, "load-definition-variables-data", form_definition=definition, form_variables=variables)


# Option B: Return the definition, variables, and previous answers in one response
@router.get("/api/forms/{id}")
def load_form(id: str, user: CurrentUser, db: Db, record: str = "") -> dict[str, Any]:
    if (form := db.execute("SELECT json FROM forms WHERE key = ?", (id,)).fetchone()) is None:
        raise HTTPException(404, "Unknown form")
    if id == "claim-request":   # only the signed-in customer's own claims
        saved = db.execute("SELECT data FROM responses WHERE id = ? AND form_id = 'claim' AND data ->> '$.customer_email' = ?",
                           (record, user.email if user else "")).fetchone()
    else:
        saved = db.execute("SELECT data FROM responses WHERE id = ?", (record,)).fetchone()
    return {
        "definition": json.loads(form["json"]),                       # the stored form definition
        "variables": {"user": {"name": user.name if user else None, "plan": user.plan if user else None}},
        "data": json.loads(saved["data"]) if saved else {},           # previous answers, or {} without them
    }
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/load_definition_variables_data.py#L23-L46 --->

</details>

[Live Example: Load JSON Schemas, Variables, and Answers](https://python-fastapi.demos.surveyjs.io/examples/load-definition-variables-data (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Resume Progress --->

### Resume Progress

With long forms, respondents may need to stop and return later. You can save their answers together with the form's UI state, which includes the current page and focused input field. Restoring both lets them continue from the same place.

While the respondent works, listen for answer and page changes and send the updated progress to the backend. Answer changes can happen on every keystroke, so wait for a short pause before saving. Send any pending changes when users close or reload the browser tab as well.

The backend should store one progress document for each user and form. When the respondent returns, load that document and restore the answers and UI state before they continue.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Resume Progress --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/resume-progress.js#L100-L122 --->

```js
import debounce from "lodash/debounce";

const saveProgress = debounce(() => flushProgress().catch(showSaveError), 800);
function flushProgress() {
  saveProgress.cancel();
  if (pendingProgress === null) return saving ?? Promise.resolve();
  return saving ??= persistProgress().finally(() => { saving = null; });
}
function queueProgress() {
  if (!recording || locked) return;
  const body = JSON.stringify(snapshot());
  if (body === lastSnapshot) return;
  lastSnapshot = pendingProgress = body;
  setStatus("Changes will be saved automatically");
  saveProgress();
}
survey.onValueChanged.add(queueProgress);
survey.onUIStateChanged.add(queueProgress);   // Include page and focus changes
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden" && recording && !locked) {
    flushProgress().catch(showSaveError);
  }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/resume-progress.js#L100-L122 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/resume_progress.py#L13-L28 --->

```python
# Return the current user's saved answers and UI state, or null when there is no draft
@router.get("/api/progress/{form_id}")
def load_progress(form_id: str, user: CurrentUser, db: Db) -> Response:
    if user is None:
        raise HTTPException(401, "Sign in to load progress")
    row = db.execute("SELECT json FROM progress WHERE key = ?", (f"{user.id}:{form_id}",)).fetchone()
    return Response(row["json"] if row else "null", media_type="application/json")   # as stored


# Store progress under a key containing both the user ID and form ID
@router.put("/api/progress/{form_id}", status_code=204)
def save_progress(form_id: str, body: JsonBody, user: CurrentUser, db: Db) -> None:
    if user is None:
        raise HTTPException(401, "Sign in to save progress")
    # The raw body, not a Pydantic model: { data, uiState } is stored as it arrived, {} stays {}
    put(db, "progress", f"{user.id}:{form_id}", body)
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/resume_progress.py#L13-L28 --->

</details>

[Live Example: Resume Progress](https://python-fastapi.demos.surveyjs.io/examples/resume-progress (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Store Files Separately --->

### Store Files Separately

A [File Upload](/form-library/examples/file-upload/) question can store file contents in the response as Base64 strings. This makes responses much larger. Alternatively, you can keep files in a separate storage. To do this, set the question's [`storeDataAsText`](/form-library/documentation/api-reference/file-model#storeDataAsText) property to `false` and handle the survey's [`onUploadFiles`](/form-library/documentation/api-reference/survey-data-model#onUploadFiles) event.

The event handler should send selected files to an upload endpoint. The backend stores each file and returns its ID or URL. The form saves that reference in the answers, leaving the file contents out of the response document.

For private files, use IDs and a download endpoint that checks the user's access before returning a file. Handle the [`onDownloadFile`](/form-library/documentation/api-reference/survey-data-model#onDownloadFile) event to retrieve the content when the form needs to display a preview.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Store Files Separately --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/store-files.js#L9-L20 --->

```js
// Upload: your server stores the files and returns an id (or a URL) for each
survey.onUploadFiles.add(async (_, options) => {
  const body = new FormData();
  options.files.forEach(file => body.append("files[]", file));   // "files[]": PHP keeps only the last of several "files"
  const response = await fetch("/api/files", { method: "POST", body }).catch(() => null);
  const ids = response?.ok ? await response.json().catch(() => null) : null;
  if (!Array.isArray(ids) || ids.length !== options.files.length || ids.some(id => typeof id !== "string" || !id)) {
    return options.callback([], ["Couldn't upload files. Please try again."]);
  }
  // The response stores these ids, not the file contents
  options.callback(options.files.map((file, i) => ({ file, content: ids[i] })));
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/store-files.js#L9-L20 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/store_files.py#L23-L44 --->

```python
# POST /api/files — store uploads, return their ids in the same order
@router.post("/api/files")
async def store_files(request: Request, db: Db, files_dir: FilesDir) -> list[str]:
    async with request.form(max_files=20, max_fields=20) as form:   # closes the spooled uploads afterwards
        # Field "files[]", the name on every platform: PHP keeps only the last of several fields named "files"
        files = [f for f in form.getlist("files[]") if isinstance(f, UploadFile)]
        if not files:
            raise HTTPException(422, 'Upload one or more files in a field named "files[]"')
        uploads = [(f, await f.read(MAX_BYTES + 1)) for f in files]   # check the whole batch before storing any
        for file, content in uploads:
            if len(content) > MAX_BYTES:
                raise HTTPException(422, "Each file must be 5 MB or less")
            if detect_type(content) not in TYPES:                        # by the bytes, never the client's type
                raise HTTPException(422, f"{file.filename} is not a PNG, JPEG, WebP, GIF or PDF file")

    ids = []
    for file, content in uploads:
        id = str(uuid.uuid4())                                           # named by id, never by the client
        (files_dir / id).write_bytes(content)
        db.execute("INSERT INTO files (id, name, type) VALUES (?, ?, ?)", (id, file.filename, detect_type(content)))
        ids.append(id)
    return ids
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/store_files.py#L23-L44 --->

</details>

[Live Example: Store Files Separately](https://python-fastapi.demos.surveyjs.io/examples/store-files (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Load Choices from Web --->

### Load Choices from Web

Choice lists often come from data your application already stores, such as products or offices. Use the [`choicesByUrl`](/form-library/documentation/api-reference/dropdown-menu-model#choicesByUrl) property to load those options into a Dropdown, Checkboxes, or Radio Button Group question. The configured endpoint should return the list, and SurveyJS displays it as the question's choices.

The URL can include answers or variables in curly braces. For example, `/api/offices?region={region}` uses the selected region to request matching offices. When that answer changes, SurveyJS requests the list again.

The browser calls the URL directly. If an external service needs a secret key or does not allow cross-origin requests, have your backend call it and return the choices to the browser. If your own endpoint requires authentication headers, add them through [`settings.web.onBeforeRequestChoices`](/form-library/documentation/api-reference/settings#web).

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Load Choices from Web --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/choices-from-web.js#L9-L18 --->

```js
// Use choicesByUrl in the form definition to load lists from API endpoints
//   "choicesByUrl": { "url": "/api/offices?region={region}", "valueName": "id", "titleName": "name" }
//   "choicesByUrl": { "url": "/api/countries", "valueName": "code", "titleName": "name" }
// SurveyJS replaces {region} with the selected region and reloads the office list when the region changes

// Optional: add your auth header to every choices request
import { settings } from "survey-core";
settings.web.onBeforeRequestChoices = (_, options) => {
  options.request?.setRequestHeader("Authorization", `Bearer ${token}`);
};
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/choices-from-web.js#L9-L18 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/choices_from_web.py#L22-L42 --->

```python
# GET /api/offices?region= — {region} from the form arrives as a query parameter
@router.get("/api/offices")
def offices(db: Db, region: str = "") -> list[dict[str, str]]:
    return [dict(row) for row in db.execute("SELECT id, name FROM offices WHERE region = ? ORDER BY name", (region,))]


# GET /api/countries — a proxy: the browser can't call a service without CORS, your server can
@router.get("/api/countries")
async def countries(http: HttpClient, cache: Cache) -> JSONResponse:
    countries = cache.get("countries")
    if countries is None:
        try:
            answer = await http.get("https://restcountries.com/v3.1/all", params={"fields": "name,cca2"}, timeout=5)
            countries = sorted(({"code": c["cca2"], "name": c["name"]["common"]} for c in answer.raise_for_status().json()),
                               key=lambda country: country["name"])
            cache.set("countries", countries, DAY)
        except Exception as error:   # down, or a different answer: the bundled list for 10 minutes, not a timeout each
            log.warning("restcountries.com failed (%s); serving shared/seed/countries.json", error)
            countries = json.loads(BUNDLED_COUNTRIES.read_text(encoding="utf-8"))
            cache.set("countries", countries, 10 * 60)
    return JSONResponse(countries, headers={"Cache-Control": "public, max-age=86400"})
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/choices_from_web.py#L22-L42 --->

</details>

[Live Example: Load Choices from Web](https://python-fastapi.demos.surveyjs.io/examples/choices-from-web (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Async Calculations and Validation --->

### Async Calculations and Validation

Some form logic needs information that only your backend has. For example, a validation rule may need to check whether an email address is already registered, or a calculation may need the shipping rate for a postcode.

Register an expression function with `isAsync: true` and have it request that information from your backend. The function returns a promise. When the request finishes, SurveyJS uses the result to update the calculation, validation rule, or visibility condition that called the function.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Async Calculations and Validation --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/async-functions.js#L58-L78 --->

```js
// Validate email availability using the backend's customer records
registerFunction({
  name: "emailExists",
  isAsync: true,
  func: async ([email]) => {
    const key = normalize("email", email);
    if (!key) return false;
    return lookup("email", key, `/api/customers/exists?email=${encodeURIComponent(key)}`, "exists");
  }
});

// Share one shipping lookup between the calculation and the postcode validator
registerFunction({
  name: "shippingCost",
  isAsync: true,
  func: async ([postcode]) => {
    const key = normalize("postcode", postcode);
    if (!key) return null;
    return lookup("postcode", key, `/api/shipping?postcode=${encodeURIComponent(key)}`, "price");
  }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/async-functions.js#L58-L78 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/async_functions.py#L16-L35 --->

```python
# GET /api/customers/exists?email= — answers emailExists()
@router.get("/api/customers/exists")
def customer_exists(db: Db, email: str = "") -> dict[str, bool]:
    row = db.execute("SELECT 1 FROM customers WHERE email = ?", (email.strip().lower(),)).fetchone()
    return {"exists": row is not None}


# GET /api/shipping?postcode= — answers shippingCost(): the longest matching postcode prefix wins,
# { "price": null } when none matches (the form shows "We don't deliver to this postcode yet")
@router.get("/api/shipping")
def shipping(db: Db, postcode: str = "") -> dict[str, float | None]:
    postcode = postcode.replace(" ", "").upper()
    if not POSTCODE.match(postcode):
        return {"price": None}
    rate = db.execute(
        "SELECT price FROM shipping_rates WHERE substr(?, 1, length(postcode_prefix)) = postcode_prefix"
        " ORDER BY length(postcode_prefix) DESC",
        (postcode,),
    ).fetchone()
    return {"price": rate["price"] if rate else None}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/async_functions.py#L16-L35 --->

</details>

[Live Example: Async Calculations and Validation](https://python-fastapi.demos.surveyjs.io/examples/async-functions (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Use Relational Storage --->

### Use Relational Storage

Storing each response as JSON is enough to preserve its answers. If you also need to query those answers with SQL or join them with other application data, copy the relevant values into database columns.

First, give the answers stable keys. A question's [`valueName`](/form-library/documentation/api-reference/question#valueName) sets the key it writes into the response independently of its question name. Form authors can then rename or move questions without breaking the mapping to your columns. If you need more mapping information, add a custom question property and expose it in Survey Creator's Property Grid.

When saving, keep the original JSON and the version of the form JSON schema used to collect it. Then copy the mapped values into their columns. Save both in one transaction, so the records stay consistent. Keeping the original document and schema version also lets you rebuild the mapping if your tables change later.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Use Relational Storage --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/relational-storage.js#L10-L17 --->

```js
import { Model, Serializer } from "survey-core";

// Optional metadata describing the columns used by the server
Serializer.addProperty("question", { name: "dbColumn", category: "data" });

// Keep answer keys stable when question names change
const survey = new Model(definitions[definitionVersion]);
survey.completeText = "Submit claim";
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/relational-storage.js#L10-L17 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/relational_storage.py#L13-L29 --->

```python
# POST /api/claims — original JSON first, then the columns you query
@router.post("/api/claims", status_code=201)
def save_claim(body: JsonBody, db: Db) -> dict[str, int]:
    # The raw body, not a Pydantic model: the stored answers keep every key, {} and 1.0 as they arrived
    if not isinstance(body, dict) or body.get("data") is None or body.get("definitionVersion") is None:
        raise HTTPException(400, "Expected { data, definitionVersion }")
    data = body["data"]

    with transaction(db):
        id = insert_response(db, "claim", data, body["definitionVersion"])   # the original and its version
        db.execute(                                                          # keys come from valueName
            "INSERT INTO claims (response_id, customer_email, amount) VALUES (?, ?, ?)",
            (id, data.get("customer_email") if isinstance(data, dict) else None,
             data.get("amount") if isinstance(data, dict) else None),
        )

    return {"id": id}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/relational_storage.py#L13-L29 --->

</details>

[Live Example: Use Relational Storage](https://python-fastapi.demos.surveyjs.io/examples/relational-storage (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Fill Forms Together --->

### Fill Forms Together

Several people may need to fill out the same record, such as a dispatcher and a technician completing a job sheet. Participants see each other's answers, focus, and cursors.

To let participants fill out a form together, follow these steps:

1. Add `CollaborationPlugin` from `survey-core/collaboration` to enable this functionality.
1. Connect the clients to a WebSocket relay that groups participants by record. When someone joins, the relay sends the form JSON schema and current answers so that their form starts in the same state as everyone else's.
1. Have the relay keep the latest value for each question and forward changes to the other clients. If two people change the same question, the last change wins.
1. Save the completed response through the usual save endpoint.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Fill Forms Together --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/fill-together.js#L74-L97 --->

```js
// Transport the plugin's answer and presence messages over a WebSocket
function applySharedState(message) {
  const draft = survey?.data;
  const previousSession = sessionId;
  if (!collab) {
    survey = new Model(message.seed);
    survey.completeText = "Finish job sheet";
    collab = new CollaborationPlugin(survey, { getInviteLink: partnerLink });
    collab.onEvent.add((_, { message }) => {
      if (ready && responseId === null && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
    });
    survey.onComplete.add(completeJobSheet);
    mountSurvey(survey);
  }
  sessionId = message.sessionId;
  ready = true;
  collab.apply(message);
  // Restore the local draft if an empty session replaces the disconnected one
  if (previousSession && previousSession !== sessionId && !message.responseId && !message.peers.length) survey.data = draft;
  form.hidden = false;
  document.getElementById("collaboration-loading").hidden = true;
  setLocked(false);
  if (message.responseId) confirmCompletion(message.responseId, message.values);
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/fill-together.js#L74-L97 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/fill_together.py#L37-L72 --->

```python
# The relay runs in this app's process, on its port, and relays JSON: it never parses the definition
@router.websocket("/ws/rooms/{record_id}")
async def fill_together(websocket: WebSocket, record_id: RecordId, user: CurrentUser, rooms: Rooms,
                        room_key: FillRoomKey, db: Db, name: str = "") -> None:
    if user is None or room_key is None:   # the demo_user cookie stands in for your real session check
        await websocket.close(code=1008)   # before accept(): the browser sees a refused handshake
        return
    await websocket.accept()
    room = rooms.join(room_key, lambda: seed(db, record_id))   # the definition + the saved answers
    client = room.add(websocket, display_name(name, user.name))
    client.send({"type": "init", "clientId": client.id, "name": client.name, "colorIndex": room.color_index(client),
                 "seed": room.seed, "values": room.values, "peers": room.roster(client),
                 "sessionId": room.session_id, "responseId": room.response_id})
    try:
        async for raw in websocket.iter_text():
            message = parse(raw)   # objects stay objects: {} is relayed as {}
            if not isinstance(message, dict):
                continue
            kind = message.get("type")
            if kind == "complete" and isinstance(message.get("data"), dict):
                await complete(room, client, message["data"], db)
            elif kind == "value" and isinstance(message.get("key"), str) and room.response_id is None:
                room.values[message["key"]] = message.get("value")   # last write wins
                room.broadcast(client, {"type": "value", "from": client.id, "key": message["key"],
                                        "value": message.get("value")})
            elif kind == "presence" and message.get("state") is not None and len(raw) <= 4096:
                retain = message.get("retain") is not False   # stamp identity, relay
                if retain:
                    client.state = message["state"]
                room.broadcast(client, {"type": "peer", "retain": retain, "peer": room.peer(client, message["state"])},
                               droppable=not retain)
            # unknown types: ignore
    except WebSocketDisconnect:
        pass
    finally:
        rooms.leave(room_key, client)   # peer-left to the others; the room is dropped 2 s after the last leaves
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/fill_together.py#L37-L72 --->

</details>

[Live Example: Fill Forms Together](https://python-fastapi.demos.surveyjs.io/examples/fill-together (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Analyze Results with Dashboard --->

## Analyze Results with Dashboard

Once you have collected responses, use [SurveyJS Dashboard](/dashboard/documentation/overview) to display and analyze them. Dashboard runs in the browser and uses the form JSON schema to choose a chart for each question automatically.

Load the JSON schema and request the saved responses for that form. The backend should return the answers as a JSON array, which the client passes to Dashboard along with the schema.

As the number of responses grows, you can filter or paginate them on the server. This lets users load the data they need without sending every stored response to the browser.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Analyze Results with Dashboard --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/dashboard.js#L23-L46 --->

```js
// Load answers with their submission dates for Dashboard's built-in date filter
async function loadResults(signal) {
  const query = new URLSearchParams({ formId: "feedback", includeCreatedAt: "1", limit: "5000" });
  const [definition, response] = await Promise.all([
    loadSchema(), fetch(`/api/responses?${query}`, { signal })
  ]);
  if (!response.ok) throw new Error("Responses load failed");
  const data = await response.json();
  if (!Array.isArray(data)) throw new Error("Invalid responses");
  return { definition, data: data.map(row => ({ ...row.data, createdAt: row.createdAt })) };
}

function renderResults(definition, data) {
  if (!dashboard) {
    const survey = new Model(definition);
    dashboard = new Dashboard({
      questions: survey.getAllQuestions(), data,
      dateFieldName: "createdAt", datePeriod: "last30days"
    });
    dashboard.render(container);
  } else {
    dashboard.updateData(data);
  }
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/dashboard.js#L23-L46 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/dashboard.py#L15-L35 --->

```python
# GET /api/responses?formId=&includeCreatedAt=&from=&to=&limit=&offset=
@router.get("/api/responses")
def responses(
    db: Db,
    form_id: Annotated[str, Query(alias="formId")] = "",
    include_created_at: Annotated[bool, Query(alias="includeCreatedAt")] = False,
    since: Annotated[str, Query(alias="from")] = "1970-01-01",
    to: str = "",
    limit: int = 500,
    offset: int = 0,
) -> Response:
    rows = db.execute(   # ISO 8601 UTC strings compare as dates; `to` includes that whole day
        "SELECT data, created_at FROM responses WHERE form_id = ? AND created_at >= ?"
        " AND (? = '' OR substr(created_at, 1, 10) <= ?) ORDER BY created_at, id LIMIT ? OFFSET ?",
        (form_id, since, to, to, min(max(limit, 1), 5000), max(offset, 0)),   # page on the server for large volumes
    ).fetchall()

    # Include submission dates separately when requested by Dashboard
    if include_created_at:
        return JSONResponse([{"data": json.loads(row["data"]), "createdAt": row["created_at"]} for row in rows])
    return Response("[" + ",".join(row["data"] for row in rows) + "]", media_type="application/json")   # as stored
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/dashboard.py#L15-L35 --->

</details>

[Live Example: Analyze Results with Dashboard](https://python-fastapi.demos.surveyjs.io/examples/dashboard (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Edit Forms in Survey Creator --->

## Edit Forms in Survey Creator

[Survey Creator](/survey-creator/documentation/overview) lets authors build and edit forms in your application. It works with the same form JSON schemas that Form Library displays to respondents. Your backend should load those schemas when the editor opens and save them when an author makes changes.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Edit Forms in Survey Creator --->

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Load and Save Form JSON Schemas --->

### Load and Save Form JSON Schemas

Start by loading the saved schema into Survey Creator. You can use the [same endpoint that supplies the schema to Form Library](#load-json-schemas-variables-and-answers).

When the author clicks **Save**, Survey Creator calls [`saveSurveyFunc`](/survey-creator/documentation/api-reference/survey-creator#saveSurveyFunc). Use this function to send the updated JSON schema to your backend. The backend should check the author's permission to edit forms, store the JSON, and confirm that it was saved. The next time a respondent opens the form, Form Library loads the updated JSON schema.

To save after each change, set the [`autoSaveEnabled`](/survey-creator/documentation/api-reference/survey-creator#autoSaveEnabled) property to `true`. Survey Creator then calls the same save function automatically. If the backend rejects a save, the backend should report the failure to Survey Creator so that the author can see it.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Load and Save Form JSON Schemas --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/creator-load-save.js#L22-L39 --->

```js
const creator = new SurveyCreator({ showTranslationTab: true });
// Queue writes so an older request cannot overwrite newer edits
const saver = createSchemaSaver(() => creator.JSON, async json => {
  const response = await fetch(`/api/forms/${formId}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: json
  });
  if ([401, 403].includes(response.status)) saveDenied = true;
  if (!response.ok) throw await responseError(response, "Couldn't save the form schema. Please try again.");
}, updateSaveState);
creator.saveSurveyFunc = (saveNo, callback) => {
  saver.save().then(saved => {
    callback(saveNo, saved);
    // Creator says "not saved" in the callback; show the server's reason after it
    if (!saved) creator.notify(saver.error, "error");
  });
};
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/creator-load-save.js#L22-L39 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/creator_load_save.py#L17-L24 --->

```python
# PUT /api/forms/{id} — store the definition as-is: it's one JSON document
@router.put("/api/forms/{id}", status_code=204)
def save_form(id: str, definition: JsonBody, user: CurrentUser, db: Db) -> None:
    if not can(user, "edit-forms"):   # editing is an admin action: 403 otherwise
        raise HTTPException(403, "You don't have editor rights: only editors can change forms")
    # The raw body, not a Pydantic model: a model would drop the keys it doesn't declare
    put(db, "forms", id, definition)   # stored as it arrived: {} stays {}, 1.0 stays 1.0
    # 204: the next page load renders the new version
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/creator_load_save.py#L17-L24 --->

</details>

[Live Example: Load and Save Form JSON Schemas](https://python-fastapi.demos.surveyjs.io/examples/creator-load-save (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Upload Files --->

### Upload Files

Authors may need to add a logo, image, or file to a form. You can keep these files in your storage and save their URLs in the JSON schema to keep it small.

When an author selects a file, Survey Creator raises the [`onUploadFile`](/survey-creator/documentation/api-reference/survey-creator#onUploadFile) event. Handle it by sending the file to your upload endpoint, then pass the returned URL back to Survey Creator. Survey Creator adds the URL to the JSON schema, and the next save preserves that reference.

You can reuse the [storage endpoint for respondent uploads](#store-files-separately). If the file is private, its URL should point to a download endpoint that checks access before serving the file.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Upload Files --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/creator-uploads.js#L39-L62 --->

```js
// Store each uploaded image separately and keep its URL in the form schema
creator.onUploadFile.add(async (_, options) => {
  const label = options.propertyName === "logo" || options.elementType === "header" ? "Logo" : "Image";
  uploads++; updateControls();
  showError("");
  try {
    if (!options.files.length || options.files.some(file =>
      file.size > 5242880 || !["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)))
      throw new Error("Choose a PNG, JPEG, WebP, or GIF image up to 5 MB.");
    const body = new FormData();
    options.files.forEach(file => body.append("files[]", file));
    const response = await fetch("/api/files", { method: "POST", body });
    const ids = response.ok ? await response.json() : null;
    if (!Array.isArray(ids) || ids.length !== options.files.length ||
      ids.some(id => typeof id !== "string" || !id))
      throw new Error(`Couldn't upload the ${label.toLowerCase()}. Please try again.`);
    options.callback("success", `/api/files/${encodeURIComponent(ids[0])}`);
    note(`${label} uploaded.`, "ok");
  } catch (error) {
    options.callback("error");
    showError(error.message);
    note(error.message, "error");
  } finally { uploads--; updateControls(); }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/creator-uploads.js#L39-L62 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/store_files.py#L23-L44 --->

```python
# POST /api/files — store uploads, return their ids in the same order
@router.post("/api/files")
async def store_files(request: Request, db: Db, files_dir: FilesDir) -> list[str]:
    async with request.form(max_files=20, max_fields=20) as form:   # closes the spooled uploads afterwards
        # Field "files[]", the name on every platform: PHP keeps only the last of several fields named "files"
        files = [f for f in form.getlist("files[]") if isinstance(f, UploadFile)]
        if not files:
            raise HTTPException(422, 'Upload one or more files in a field named "files[]"')
        uploads = [(f, await f.read(MAX_BYTES + 1)) for f in files]   # check the whole batch before storing any
        for file, content in uploads:
            if len(content) > MAX_BYTES:
                raise HTTPException(422, "Each file must be 5 MB or less")
            if detect_type(content) not in TYPES:                        # by the bytes, never the client's type
                raise HTTPException(422, f"{file.filename} is not a PNG, JPEG, WebP, GIF or PDF file")

    ids = []
    for file, content in uploads:
        id = str(uuid.uuid4())                                           # named by id, never by the client
        (files_dir / id).write_bytes(content)
        db.execute("INSERT INTO files (id, name, type) VALUES (?, ?, ?)", (id, file.filename, detect_type(content)))
        ids.append(id)
    return ids
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/store_files.py#L23-L44 --->

</details>

[Live Example: Upload Files](https://python-fastapi.demos.surveyjs.io/examples/creator-uploads (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Translate with AI --->

### Translate with AI

For multilingual forms, you can integrate AI in Survey Creator's **Translations** tab so that authors can translate titles, choices, and other form text semi-automatically.

When an author requests a translation, send the source strings and language information to your backend. The backend should call the AI provider you choose and return the translated strings in their original order. Keep the provider's API key on the server.

Authors can review and edit the translations in the UI before using them in the form.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Translate with AI --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/ai-translation.js#L31-L49 --->

```js
// Return translated strings in the original order, and always finish the callback
creator.onMachineTranslate.add(async (_, options) => {
  showError("");
  try {
    const response = await fetch("/api/translate", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ strings: options.strings, from: options.fromLocale, to: options.toLocale })
    });
    if (!response.ok) throw await responseError(response, "AI translation failed. Please try again.");
    const strings = await response.json();
    if (!Array.isArray(strings) || strings.length !== options.strings.length || strings.some(text => typeof text !== "string"))
      throw new Error("The translation provider returned an invalid result. Please try again.");
    options.callback(strings);
  } catch (error) {
    options.callback([]);
    showError(`${translationError(error)} Existing translations are kept.`);
    note(error.message, "error");
  }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/ai-translation.js#L31-L49 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/ai_translation.py#L22-L33 --->

```python
# POST /api/translate — strings in, translated strings out (same order); nothing goes to SurveyJS
@router.post("/api/translate")
async def translate(body: TranslateRequest, settings: SettingsDep, translator: Translator) -> list[str]:
    if not settings.ai_api_key:
        raise HTTPException(501, "Set AI_API_KEY to enable translation")

    translated = await translator.translate(body.strings, body.source, body.to)   # any OpenAI-compatible provider
    if not isinstance(translated, list) or len(translated) != len(body.strings) \
            or not all(isinstance(text, str) for text in translated):
        raise HTTPException(502, "The AI provider returned an unexpected answer")

    return translated   # what options.callback() takes
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/ai_translation.py#L22-L33 --->

</details>

[Live Example: Translate with AI](https://python-fastapi.demos.surveyjs.io/examples/ai-translation (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Variable Presets --->

### Variable Presets

Form logic may depend on variables supplied by your application, such as a customer's subscription plan. Authors need sample values to test that logic before the form is used. Variable presets allow them to do that by providing named sets of those values in Survey Creator.

Load the saved presets from the backend when the editor opens. In the **Preview** tab, an author can select a preset to see how the form behaves with its values. Switching presets updates the preview using data already loaded in the browser.

When an author edits a preset, you need to save the updated presets to your backend as a JSON document. Check editing permission before saving, just as you do for form JSON schemas.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Variable Presets --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/variable-presets.js#L14-L29 --->

```js
const creator = new SurveyCreator({
  variablePresets: {
    definition: {
      elements: [{
        type: "dropdown", name: "customerTier", title: "Customer plan",
        choices: [{ value: "basic", text: "Basic" }, { value: "premium", text: "Premium" }],
        isRequired: true
      }]
    },
    presets: []
  }
});
creator.onVariablePresetsChanged.add((_, options) => {
  // Switching scenarios changes only Preview; editing persists the preset list
  if (loaded && options.reason === "edit") { saver.changed(); saver.save(); }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/variable-presets.js#L14-L29 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/variable_presets.py#L14-L27 --->

```python
# GET /api/variable-presets/{form_id} — return the stored preset list, or [] when none are saved
@router.get("/api/variable-presets/{form_id}")
def load_presets(form_id: str, db: Db) -> Response:
    row = db.execute("SELECT json FROM variable_presets WHERE key = ?", (form_id,)).fetchone()
    return Response(row["json"] if row else "[]", media_type="application/json")   # as stored


# PUT /api/variable-presets/{form_id} — store the variable presets as-is: it's one JSON document
@router.put("/api/variable-presets/{form_id}", status_code=204)
def save_presets(form_id: str, presets: JsonBody, user: CurrentUser, db: Db) -> None:
    if not can(user, "edit-forms"):   # editing is an admin action: 403 otherwise
        raise HTTPException(403, "You don't have editor rights: only editors can change forms")
    # The raw body, not a Pydantic model: the presets are stored as they arrived, {} stays {}
    put(db, "variable_presets", form_id, presets)
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/variable_presets.py#L14-L27 --->

</details>

[Live Example: Variable Presets](https://python-fastapi.demos.surveyjs.io/examples/variable-presets (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Edit Forms Together --->

### Edit Forms Together

Several authors can work on the same form. Participants see each other's edits, selection, and cursors, and cannot edit survey elements that another participant is editing.

To let several authors work on the same form, follow these steps:

1. Add `CollaborationPlugin` from `survey-creator-core/collaboration` to enable this functionality.
1. Connect the clients to a WebSocket relay. Have the relay add each edit to a change log as a JSON record and forward it to the other participants.
1. When someone joins, send them the starting JSON schema and the change log. Applying those changes brings the new participant's editor up to date.
1. Save the JSON schema through `saveSurveyFunc` and your usual save endpoint. After the collaboration session ends, the next session starts from the saved schema.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Edit Forms Together --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/edit-together.js#L64-L79 --->

```js
// Rebuild the shared form from its saved schema and ordered edit log
function initialize(message) {
  creator?.dispose();
  creator = new SurveyCreator({ showTranslationTab: true });
  creator.JSON = message.seed;
  collab = new CollaborationPlugin(creator, { roomId: formId, getInviteLink: sharedFormLink });
  creator.addPlugin("collaboration", collab);
  collab.setClientId(message.clientId);
  configureSaving();
  saver.markSaved();
  if (message.log.length) collab.apply(message.log);
  const append = (_, { record }) => send({ type: "append", payload: record });
  collab.onRecordAdded.add(append);
  collab.onRecordChanged.add(append);
  collab.onStateChanged.add(() => send({ type: "presence", state: collab.getState() }));
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/edit-together.js#L64-L79 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/edit_together.py#L31-L61 --->

```python
# The same kind of relay as Fill Forms Together, keeping an append-only log instead of a value map:
# Creator records must be replayed in order. It runs in this app's process, on its port.
@router.websocket("/ws/forms/{form_id}")
async def edit_together(websocket: WebSocket, form_id: FormId, user: CurrentUser, rooms: Rooms,
                        room_key: EditRoomKey, db: Db, name: str = "") -> None:
    if not can(user, "edit-forms") or room_key is None:   # like saving, editing together is for editors
        await websocket.close(code=1008)                  # before accept(): the browser sees a refused handshake
        return
    await websocket.accept()
    room = rooms.join(room_key, lambda: saved_definition(db, form_id))   # seed = the saved definition
    client = room.add(websocket, display_name(name, user.name))
    client.send({"type": "init", "clientId": client.id, "colorIndex": client.slot, "color": room.color(client),
                 "seed": room.seed, "log": room.log})   # init first
    if peers := room.roster(client):
        client.send({"type": "presence-sync", "peers": peers})
    try:
        async for raw in websocket.iter_text():
            message = parse(raw)   # records stay opaque: {} is relayed as {}
            if not isinstance(message, dict):
                continue
            if message.get("type") == "append" and message.get("payload") is not None:   # append, then fan out
                room.log.append(message["payload"])
                room.broadcast(client, {"type": "record", "from": client.id, "payload": message["payload"]})
            elif message.get("type") == "presence" and message.get("state") is not None and len(raw) <= 4096:
                client.state = message["state"]
                room.broadcast(client, {"type": "presence", "peer": room.peer(client)})
            # unknown types: ignore
    except WebSocketDisconnect:
        pass
    finally:
        rooms.leave(room_key, client)   # presence-leave to the others; the log lives until the room empties
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/edit_together.py#L31-L61 --->

</details>

[Live Example: Edit Forms Together](https://python-fastapi.demos.surveyjs.io/examples/edit-together (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Run Server-Side Workflows --->

## Run Server-Side Workflows

Some workflows need SurveyJS logic on the server. You may need to check a submission before storing it, find problems in a form JSON schema, create a PDF, or read answers from a document.

These operations run in Node.js. A Node.js backend can run the components directly; other backends can call a Node.js service over HTTP. In either case, your backend supplies the required data and uses the result in its own workflow.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Run Server-Side Workflows --->

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Validate Responses --->

### Validate Responses

Browser validation helps respondents correct their answers while filling out a form. Your API can also receive requests that bypass the form, so you need to repeat validation on the server before storing a response.

When a submission arrives, load the form JSON schema from your storage. Validate the submitted answers against that schema on the server, checking required questions, value types, and allowed choices.

Save the response only if validation succeeds. If it fails, return the errors to the client so that the respondent can correct the answers.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Validate Responses --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/validate-response.js#L46-L61 --->

```js
// Confirm a save only after the backend accepts the answers and returns a response ID
survey.onComplete.add(async (sender, options) => {
  lock(true);
  sender.completedHtml = "<h3>Submitting your claim...</h3>";
  options.showSaveInProgress();
  try {
    const result = await submit(sender.data);
    if (result.rejected) throw new Error(result.errors.map(describe).join("; "));
    sender.completedHtml = `<h3>Your claim has been saved.</h3><p>Response ID: ${result.id}</p>`;
    options.showSaveSuccess();
  } catch (error) {
    sender.completedHtml = "<h3>Your claim hasn't been saved.</h3>";
    const message = error instanceof TypeError ? "Couldn't validate the response. Please try again." : error.message;
    options.showSaveError(message);
  } finally { lock(false); }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/validate-response.js#L46-L61 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/validate_response.py#L22-L43 --->

```python
# POST /api/responses — ask the SurveyJS service to validate, then store as usual
@router.post("/api/responses", status_code=201, response_model=None)
async def save_validated_response(body: JsonBody, db: Db, surveyjs: SurveyJs) -> dict[str, int] | JSONResponse:
    # The raw body, not a Pydantic model: the stored answers keep every key, {} and 1.0 (see Save Responses)
    if not isinstance(body, dict) or not isinstance(body.get("formId"), str) or not isinstance(body.get("data"), dict):
        raise HTTPException(400, "Expected { formId, data } with an answers object")
    form = db.execute("SELECT json FROM forms WHERE key = ?", (body["formId"],)).fetchone()
    if form is None:
        raise HTTPException(404, "Unknown form")

    check = await surveyjs.post("/response", {"schema": json.loads(form["json"]), "response": body["data"]}, timeout=10)
    answer: Any = None
    with suppress(ValueError):   # not JSON: fails closed below
        answer = json.loads(check.content)
    if check.status_code == 422 and isinstance(answer, dict) and "errors" in answer:
        if "warnings" in answer:   # the stored definition itself has errors
            surveyjs.unexpected("/response", check, "The stored definition has errors")
        return JSONResponse({"errors": answer["errors"]}, status_code=400)   # the answers don't fit the definition
    if check.status_code != 200 or answer != {}:   # fail closed: only exactly {} means valid
        surveyjs.unexpected("/response", check)

    return {"id": insert_response(db, body["formId"], body["data"])}   # stored as it arrived: 1.0 stays 1.0
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/validate_response.py#L22-L43 --->

</details>

[Live Example: Validate Responses](https://python-fastapi.demos.surveyjs.io/examples/validate-response (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Lint JSON Schemas --->

### Lint JSON Schemas

A form JSON schema can contain mistakes that stop its questions or logic from working as intended. For example, a condition may refer to a question that does not exist. Check JSON schemas using the [SurveyJS Linter](/form-library/documentation/survey-json-validation#use-the-surveyjs-linter) before saving and return its findings to Survey Creator so that authors can fix these problems before respondents encounter them.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Lint JSON Schemas --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/lint-definition.js#L31-L47 --->

```js
// Display the server's errors and warnings and return the actual save result to Creator
async function saveDefinition(definition) {
  const response = await fetch(`/api/forms/${formId}`, {
    method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(definition)
  });
  const report = response.status === 204 ? {} : await response.json();
  reportFindings(report);
  if (response.status === 422 && Array.isArray(report.errors) && report.errors.length) {
    note("Form schema not saved. Fix the reported errors and retry.", "error");
    return false;
  }
  if (!response.ok) throw new Error(report.error || "Couldn't save the form schema. Please try again.");
  const count = report.warnings?.length ?? 0;
  note(count ? `Schema saved with ${count} warning${count === 1 ? "" : "s"}. Review the findings above.` : "Form schema saved successfully.", "ok");
  return true;
}
creator.saveSurveyFunc = async (saveNo, callback) => callback(saveNo, await checkAndSave(creator.JSON));
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/lint-definition.js#L31-L47 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/lint_definition.py#L22-L39 --->

```python
# PUT /api/forms/{id} — lint the definition from Creator before storing it
@router.put("/api/forms/{id}", status_code=204, response_model=None)
async def save_linted_form(id: str, definition: JsonBody, user: CurrentUser, db: Db, surveyjs: SurveyJs) -> Response | None:
    if not can(user, "edit-forms"):
        raise HTTPException(403, "You don't have editor rights: only editors can change forms")
    # The raw body keeps {} as {} (see Load and Save Form JSON Schemas)
    lint = await surveyjs.post("/schema", definition, timeout=10)
    answer: Any = None
    with suppress(ValueError):   # not JSON: fails closed below
        answer = json.loads(lint.content)
    if lint.status_code == 422 and isinstance(answer, dict) and {"errors", "warnings"} <= answer.keys():
        return JSONResponse(answer, status_code=422)   # errors: refuse the save, report them as they are
    warnings_only = lint.status_code == 200 and isinstance(answer, dict) and list(answer) == ["warnings"]
    if not warnings_only and (lint.status_code != 200 or answer != {}):   # fail closed: nothing else is clean
        surveyjs.unexpected("/schema", lint)

    put(db, "forms", id, definition)   # stored as it arrived: 1.0 stays 1.0
    return JSONResponse({"warnings": answer["warnings"]}) if warnings_only else None   # warnings don't block it
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/lint_definition.py#L22-L39 --->

</details>

[Live Example: Lint JSON Schemas](https://python-fastapi.demos.surveyjs.io/examples/lint-definition (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Generate PDFs --->

### Generate PDFs

A backend workflow may need a PDF for an archive or email attachment. [SurveyJS PDF Generator](/pdf-generator/documentation/overview) can create the document on the server without opening a browser.

Load the form JSON schema and, for a completed form, its saved answers. Pass them to PDF Generator to create the document. Your backend can then store the PDF, attach it to an email, or send it to the browser with the `application/pdf` content type.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Generate PDFs --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/server-pdf.js#L24-L41 --->

```js
// Open a tab during the click and navigate only after the server returns a PDF
async function generatePdf(id, action) {
  if (urls.has(id)) return usePdfUrl(id, action, urls.get(id));
  const tab = action === "open" ? window.open("/examples/server-pdf/loading", "_blank") : null;
  try {
    const response = await fetch(`/api/claims/${id}/pdf`);
    if (!response.ok) throw await responseError(response, "Couldn't generate the PDF. Please try again.");
    if (!response.headers.get("content-type")?.startsWith("application/pdf")) throw new Error("The server didn't return a PDF. Please try again.");
    const blob = await response.blob();
    if (!blob.size) throw new Error("The server returned an empty PDF. Please try again.");
    const url = URL.createObjectURL(blob);
    urls.set(id, url);
    if (action === "download") return usePdfUrl(id, action, url);
    const opened = tab && !tab.closed;
    if (opened) tab.location = url;
    return { message: opened ? "PDF opened in a new tab." : "PDF ready. Select Open PDF again or Download PDF.", needsAction: !opened };
  } catch (error) { tab?.close(); throw error; }
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/server-pdf.js#L24-L41 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/server_pdf.py#L18-L38 --->

```python
# GET /api/claims/{id}/pdf — ask the SurveyJS service for the filled form and pass the PDF through
@router.get("/api/claims/{id}/pdf")
async def claim_pdf(id: int, db: Db, surveyjs: SurveyJs) -> Response:
    claim = db.execute("SELECT definition_version, data FROM responses WHERE form_id = 'claim' AND id = ?", (id,)).fetchone()
    if claim is None:
        raise HTTPException(404, "Unknown claim")
    match claim["definition_version"]:   # use the schema version recorded with the response
        case "v1" | "v2" as version:
            definition = (DEFINITIONS / f"relational-storage.{version}.json").read_text(encoding="utf-8")
        case None:
            definition = db.execute("SELECT json FROM forms WHERE key = 'claim'").fetchone()["json"]
        case _:
            raise HTTPException(409, "The schema version for this claim is unavailable")

    pdf = await surveyjs.post("/pdf", {"schema": json.loads(definition), "response": json.loads(claim["data"])}, timeout=60)
    if (pdf.status_code != 200 or not pdf.headers.get("content-type", "").startswith("application/pdf")
            or not pdf.content.startswith(b"%PDF-")):
        surveyjs.unexpected("/pdf", pdf)

    return Response(pdf.content, media_type="application/pdf", headers={
        "Content-Disposition": f'inline; filename="claim-{id}.pdf"', "Cache-Control": "private, no-store"})
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/server_pdf.py#L18-L38 --->

</details>

[Live Example: Generate PDFs](https://python-fastapi.demos.surveyjs.io/examples/server-pdf (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Extract Responses from Documents --->

### Extract Responses from Documents

Some responses arrive as completed paper forms, scans, or PDFs. [AI Form Response Extractor](/documentation/combine-paper-and-online-survey-form-data) can use your form JSON schema to read those documents and return answers in the same format as an online response.

Upload the document to your backend and send it, along with the JSON schema, to the extractor. The extractor calls the AI provider you configure and returns the answers with confidence information. It can also return a unique ID detected in the document, such as an ID from a QR code.

Use the returned answers to fill a draft form. Show which answers need checking so a person can review and correct them before submitting. Extraction itself does not save a response—save the reviewed answers through your usual endpoint.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Extract Responses from Documents --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/extract-from-paper.js#L57-L68 --->

```js
// Extract a draft without saving it and validate the response before replacing any answers
async function extract(file, signal) {
  const body = new FormData();
  body.append("scan", file);
  const response = await fetch("/api/work-orders/extract", { method: "POST", body, signal });
  if (!response.ok) throw await responseError(response, "Couldn't extract the answers. Try again or enter the answers directly in the form.");
  const result = await response.json();
  if (!result.answers || typeof result.answers !== "object" || Array.isArray(result.answers) || !Array.isArray(result.confidence)) {
    throw new Error("The extraction result couldn't be read. Try again or enter the answers directly in the form.");
  }
  return result;
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/shared/client/extract-from-paper.js#L57-L68 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/extract_from_paper.py#L40-L63 --->

```python
# POST /api/work-orders/extract — send the uploaded scan to the SurveyJS service; return a draft response
@router.post("/api/work-orders/extract")
async def extract_work_order(db: Db, surveyjs: SurveyJs, scan: Annotated[UploadFile | str | None, File()] = None) -> Any:
    if scan is None:
        raise HTTPException(400, 'Upload the scan in a field named "scan"')
    if isinstance(scan, str) or len(raw := await scan.read(MAX_BYTES + 1)) > MAX_BYTES:   # a text field isn't a file
        raise HTTPException(413, "The scan must be a file of 5 MB or less")
    if detect_type(raw) is None:   # by the first bytes, never the client's Content-Type
        raise HTTPException(400, "The file is not a PDF, PNG, JPEG, WebP or GIF document")
    schema = json.loads(db.execute("SELECT json FROM forms WHERE key = 'work-order'").fetchone()["json"])
    out = await surveyjs.post("/extract", {"schema": schema, "document": base64.b64encode(raw).decode()}, timeout=120)
    result: Any = None
    with suppress(ValueError):   # JSON with base64 went out, not multipart; an answer that isn't JSON fails closed
        result = json.loads(out.content)
    match out.status_code, result:   # nothing is saved: a person reviews the draft
        case 200, {"data": dict() as answers}:
            return {"answers": answers, "confidence": result.get("confidence", []), "uniqueId": result.get("uniqueId")}
        case 400, {"error": "INVALID_DOCUMENT"}:
            raise HTTPException(400, "The file is not a PDF, PNG, JPEG, WebP or GIF document")
        case 503, {"error": "AI_NOT_CONFIGURED"}:
            raise HTTPException(503, "The SurveyJS service has no AI provider configured")
        case 502, {"error": "EXTRACTION_FAILED"}:
            raise HTTPException(502, "Could not extract the response from the document")
    surveyjs.unexpected("/extract", out, log_body=False)   # fail closed, logged by status only
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-python-fastapi/blob/5b404b3354454fb18832e59900ddcdec3029790e/app/routes/extract_from_paper.py#L40-L63 --->

</details>

[Live Example: Extract Responses from Documents](https://python-fastapi.demos.surveyjs.io/examples/extract-from-paper (linkStyle))
