Integrate SurveyJS with Spring Boot

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 Spring Boot 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.

Run Forms

SurveyJS Form Library 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.

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

Client code
// 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.");
  }
});
Server code
// POST /api/responses: Store submitted answers as one JSON document
@PostMapping("/api/responses")
@ResponseStatus(HttpStatus.CREATED)
public Map<String, Integer> saveResponse(@RequestBody JsonNode body) {
    // A JsonNode, not a DTO: binding to a class would drop unknown keys and coerce values in the answers
    if (!body.path("formId").isString() || !body.has("data")) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Expected { formId, data }");
    }

    int id = storedJson.insertResponse(body.get("formId").asString(), body.get("data"));   // stored as it arrived: {} stays {}, 1.0 stays 1.0

    return Map.of("id", id);
}

Live Example: Save Responses

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.

Client code
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;
}
Server code
// Option A: Embed the schema and user variables in the HTML response
@GetMapping("/claim")
public String claimPage(@AuthenticationPrincipal User user, Model model) throws IOException {
    model.addAttribute("formDefinition", json.readTree(Files.readString(DEFINITION)));
    model.addAttribute("formVariables", Variables.of(user));
    // The template writes both with th:inline="javascript", which escapes them for an inline <script>
    return pages.render("load-definition-variables-data", model.addAttribute("optionA", true));
}

// Option B: Return the definition, variables, and previous answers in one response
@GetMapping("/api/forms/{id}")
@ResponseBody
public FormAnswer loadForm(@PathVariable String id, @RequestParam(required = false) Long record, @AuthenticationPrincipal User user) {
    String form = jdbc.sql("SELECT json FROM forms WHERE key = ?").param(id).query(String.class).optional()
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Unknown form"));
    Optional<JsonNode> saved = jdbc.sql("SELECT data FROM responses WHERE id = ?" + (id.equals("claim-request") ? " AND form_id = 'claim'" : ""))
            .param(record).query(String.class).optional().map(json::readTree);
    if (id.equals("claim-request")) {   // only the signed-in customer's own claims
        // H2 can't query inside JSON text, so the owner check reads the document
        saved = saved.filter(data -> user != null && user.email().equals(data.path("customer_email").asString(null)));
    }
    return new FormAnswer(json.readTree(form), Variables.of(user), saved.orElse(json.createObjectNode()));   // {} without a record
}

Live Example: Load JSON Schemas, Variables, and Answers

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.

Client code
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);
  }
});
Server code
// Return the current user's saved answers and UI state, or null when there is no draft
@GetMapping("/api/progress/{formId}")
public ResponseEntity<String> loadProgress(@PathVariable String formId, @AuthenticationPrincipal User user) {
    if (user == null) {
        throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Sign in to load progress");
    }
    String draft = jdbc.sql("SELECT json FROM progress WHERE key = ?").param(user.id() + ":" + formId)
            .query(String.class).optional().orElse("null");
    return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(draft);   // as stored, or the JSON text null
}

// Store progress under a key containing both the user ID and form ID
@PutMapping("/api/progress/{formId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void saveProgress(@PathVariable String formId, @RequestBody JsonNode body, @AuthenticationPrincipal User user) {
    if (user == null) {
        throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Sign in to save progress");
    }
    // A JsonNode, not a DTO: { data, uiState } is stored as it arrived, {} stays {}
    storedJson.put("progress", user.id() + ":" + formId, body);
}

Live Example: Resume Progress

Store Files Separately

A 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 property to false and handle the survey's 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 event to retrieve the content when the form needs to display a preview.

Client code
// 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] })));
});
Server code
// POST /api/files — store uploads, return their ids in the same order
@PostMapping(path = "/api/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public List<String> storeFiles(MultipartHttpServletRequest request) throws IOException {
    List<MultipartFile> files = request.getFiles("files[]");   // the name on every platform: PHP keeps only the last of several "files"
    if (files.isEmpty()) {
        throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_CONTENT, "Upload one or more files in a field named \"files[]\"");
    }
    for (MultipartFile file : files) {   // check the whole batch before storing any
        if (file.getSize() > MAX_BYTES) {
            throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_CONTENT, "Each file must be 5 MB or less");
        }
        if (FileType.detect(file) == null) {   // PNG, JPEG, WebP, GIF or PDF by the bytes, never the client's Content-Type
            throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_CONTENT, file.getOriginalFilename() + " is not a PNG, JPEG, WebP, GIF or PDF file");
        }
    }
    List<String> ids = new ArrayList<>();
    for (MultipartFile file : files) {
        String id = UUID.randomUUID().toString();   // named by id, never by the client
        fileStore.write(id, file);
        jdbc.sql("INSERT INTO files (id, name, type) VALUES (?, ?, ?)").params(id, file.getOriginalFilename(), FileType.detect(file)).update();
        ids.add(id);
    }
    return ids;
}

Live Example: Store Files Separately

Load Choices from Web

Choice lists often come from data your application already stores, such as products or offices. Use the 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.

Client code
// 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}`);
};
Server code
// GET /api/offices?region= — {region} from the form arrives as a query parameter
@GetMapping("/api/offices")
public List<Office> offices(@RequestParam(defaultValue = "") String region) {
    return jdbc.sql("SELECT id, name FROM offices WHERE region = ? ORDER BY name").param(region).query(Office.class).list();
}

// GET /api/countries — a proxy: the browser can't call a service without CORS, your server can
@GetMapping("/api/countries")
public ResponseEntity<List<Country>> countries() {
    List<Country> countries = cache.get("countries");
    if (countries == null) {
        try {
            JsonNode all = restcountries.get().uri("https://restcountries.com/v3.1/all?fields=name,cca2").retrieve().body(JsonNode.class);
            countries = all.valueStream().map(c -> new Country(c.get("cca2").asString(), c.get("name").get("common").asString()))
                    .sorted(Comparator.comparing(Country::name)).toList();
            cache.put("countries", countries, Duration.ofHours(24));
        } catch (RuntimeException e) {   // down, or a different answer: the bundled list for 10 minutes, not a timeout each
            log.warn("restcountries.com failed (" + e.getMessage() + "); serving shared/seed/countries.json");
            countries = json.readValue(BUNDLED_COUNTRIES.toFile(), new TypeReference<List<Country>>() { });
            cache.put("countries", countries, Duration.ofMinutes(10));
        }
    }
    return ResponseEntity.ok().cacheControl(CacheControl.maxAge(Duration.ofDays(1)).cachePublic()).body(countries);
}

Live Example: Load Choices from Web

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.

Client code
// 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");
  }
});
Server code
// GET /api/customers/exists?email= — answers emailExists()
@GetMapping("/api/customers/exists")
public Map<String, Boolean> customerExists(@RequestParam(defaultValue = "") String email) {
    boolean exists = jdbc.sql("SELECT COUNT(*) FROM customers WHERE email = ?")
            .param(email.strip().toLowerCase(Locale.ROOT)).query(Integer.class).single() > 0;
    return Map.of("exists", exists);
}

// 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")
@GetMapping("/api/shipping")
public Price shipping(@RequestParam(defaultValue = "") String postcode) {
    String code = postcode.replace(" ", "").toUpperCase(Locale.ROOT);
    if (!POSTCODE.matcher(code).matches()) {
        return new Price(null);
    }
    return new Price(jdbc.sql("SELECT price FROM shipping_rates WHERE ? LIKE postcode_prefix || '%'"
                    + " ORDER BY LENGTH(postcode_prefix) DESC LIMIT 1")
            .param(code).query(Double.class).optional().orElse(null));
}

Live Example: Async Calculations and Validation

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

Client code
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";
Server code
// POST /api/claims — original JSON first, then the columns you query
@PostMapping("/api/claims")
@ResponseStatus(HttpStatus.CREATED)
@Transactional
public Map<String, Integer> saveClaim(@RequestBody JsonNode body) {
    // A JsonNode, not a DTO: the stored answers keep every key, {} and 1.0 as they arrived
    if (!body.hasNonNull("data") || !body.hasNonNull("definitionVersion")) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Expected { data, definitionVersion }");
    }
    JsonNode data = body.get("data");

    int id = storedJson.insertResponse("claim", data, StoredJson.text(body.get("definitionVersion")));   // the original and its version
    jdbc.sql("INSERT INTO claims (response_id, customer_email, amount) VALUES (?, ?, ?)")   // keys come from valueName
            .params(id, StoredJson.text(data.get("customer_email")), number(data.get("amount"))).update();

    return Map.of("id", id);
}

Live Example: Use Relational Storage

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.
  2. 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.
  3. 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.
  4. Save the completed response through the usual save endpoint.
Client code
// 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);
}
Server code
// The relay runs in this app's process, on its port, and relays JSON: it never parses the definition
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler,
                               Map<String, Object> attributes) {
    String recordId = request.getURI().getPath().substring("/ws/rooms/".length());
    // Spring Security's filter chain ran on the upgrade request: the demo_user cookie stands in for your real session check
    User user = request.getPrincipal() instanceof Authentication auth && auth.getPrincipal() instanceof User u ? u : null;
    String roomKey = roomKeys.forId(recordId);
    if (!RECORD_ID.matcher(recordId).matches() || user == null || roomKey == null) {
        response.setStatusCode(HttpStatus.FORBIDDEN);   // the browser sees a refused handshake
        return false;
    }
    attributes.putAll(Map.of("user", user, "recordId", recordId, "roomKey", roomKey));
    return true;
}

@Override
public void afterConnectionEstablished(WebSocketSession session) {
    User user = (User) session.getAttributes().get("user");
    FillRoom room = rooms.join(roomKey(session), () -> seed((String) session.getAttributes().get("recordId")));   // definition + saved answers
    room.lock().lock();
    try {
        Participant client = room.add(session, Participant.displayName(session, user.name()));
        client.send(Participant.message("type", "init", "clientId", client.id(), "name", client.name(), "colorIndex", room.colorIndex(client),
                "seed", room.seed(), "values", room.values(), "peers", room.roster(client),
                "sessionId", room.sessionId(), "responseId", room.responseId()));   // init first
    } finally {
        room.lock().unlock();
    }
}

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage text) {
    JsonNode message = parse(text.getPayload());   // objects stay objects: {} is relayed as {}
    FillRoom room = rooms.room(roomKey(session));
    Participant client = Participant.of(session);
    switch (message.path("type").asString("")) {
        case "complete" -> {
            if (message.get("data") instanceof ObjectNode data) {
                complete(room, client, data);
            }
        }
        case "value" -> {
            if (message.path("key").isString()) {   // last write wins; ignored once the room's response is saved
                room.value(client, message.get("key").asString(), message.path("value").isMissingNode() ? null : message.get("value"));
            }
        }
        case "presence" -> {
            if (message.hasNonNull("state") && text.getPayloadLength() <= 4096) {   // stamp identity, relay
                room.presence(client, message.get("state"), !message.path("retain").isBoolean() || message.get("retain").asBoolean());
            }
        }
        default -> { }   // unknown types: ignore
    }
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
    rooms.leave(roomKey(session), Participant.of(session));   // peer-left to the others; the room is dropped 2 s after the last leaves
}

Live Example: Fill Forms Together

Analyze Results with Dashboard

Once you have collected responses, use SurveyJS Dashboard 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.

Client code
// 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);
  }
}
Server code
// GET /api/responses?formId=&includeCreatedAt=&from=&to=&limit=&offset=
@GetMapping("/api/responses")
public ResponseEntity<?> responses(@RequestParam(defaultValue = "") String formId,
                                   @RequestParam(defaultValue = "false") boolean includeCreatedAt,
                                   @RequestParam(defaultValue = "1970-01-01") String from, @RequestParam(defaultValue = "") String to,
                                   @RequestParam(defaultValue = "500") int limit, @RequestParam(defaultValue = "0") int offset) {
    // ISO 8601 UTC strings compare as dates; `to` includes that whole day
    List<StoredResponse> rows = jdbc.sql("SELECT data, created_at FROM responses WHERE form_id = ? AND created_at >= ?"
                    + " AND (? = '' OR SUBSTRING(created_at, 1, 10) <= ?) ORDER BY created_at, id LIMIT ? OFFSET ?")
            .params(formId, from, to, to, Math.clamp(limit, 1, 5000), Math.max(offset, 0))   // page on the server for large volumes
            .query(StoredResponse.class).list();

    // Include submission dates separately when requested by Dashboard
    if (includeCreatedAt) {
        return ResponseEntity.ok(rows.stream().map(row -> new DatedResponse(json.readTree(row.data()), row.createdAt())).toList());
    }
    return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON)
            .body("[" + rows.stream().map(StoredResponse::data).collect(Collectors.joining(",")) + "]");   // as stored
}

Live Example: Analyze Results with Dashboard

Edit Forms in Survey Creator

Survey Creator 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.

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.

When the author clicks Save, Survey Creator calls 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 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.

Client code
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");
  });
};
Server code
// PUT /api/forms/{id} — store the definition as-is: it's one JSON document
@PutMapping("/api/forms/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
@PreAuthorize("hasAuthority('edit-forms')")   // editing is an admin action: 403 otherwise
public void saveForm(@PathVariable String id, @RequestBody JsonNode definition) {
    // A JsonNode, not a DTO: binding to a class would drop the keys it doesn't declare
    storedJson.put("forms", id, definition);   // stored as it arrived: {} stays {}, 1.0 stays 1.0
    // 204: the next page load renders the new version
}

Live Example: Load and Save Form JSON Schemas

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 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. If the file is private, its URL should point to a download endpoint that checks access before serving the file.

Client code
// 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(); }
});
Server code
// POST /api/files — store uploads, return their ids in the same order
@PostMapping(path = "/api/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public List<String> storeFiles(MultipartHttpServletRequest request) throws IOException {
    List<MultipartFile> files = request.getFiles("files[]");   // the name on every platform: PHP keeps only the last of several "files"
    if (files.isEmpty()) {
        throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_CONTENT, "Upload one or more files in a field named \"files[]\"");
    }
    for (MultipartFile file : files) {   // check the whole batch before storing any
        if (file.getSize() > MAX_BYTES) {
            throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_CONTENT, "Each file must be 5 MB or less");
        }
        if (FileType.detect(file) == null) {   // PNG, JPEG, WebP, GIF or PDF by the bytes, never the client's Content-Type
            throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_CONTENT, file.getOriginalFilename() + " is not a PNG, JPEG, WebP, GIF or PDF file");
        }
    }
    List<String> ids = new ArrayList<>();
    for (MultipartFile file : files) {
        String id = UUID.randomUUID().toString();   // named by id, never by the client
        fileStore.write(id, file);
        jdbc.sql("INSERT INTO files (id, name, type) VALUES (?, ?, ?)").params(id, file.getOriginalFilename(), FileType.detect(file)).update();
        ids.add(id);
    }
    return ids;
}

Live Example: Upload Files

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.

Client code
// 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");
  }
});
Server code
// POST /api/translate — strings in, translated strings out (same order); nothing goes to SurveyJS
@PostMapping("/api/translate")
public JsonNode translate(@RequestBody TranslateRequest body) {
    if (settings.aiApiKey() == null) {
        throw new ResponseStatusException(HttpStatus.NOT_IMPLEMENTED, "Set AI_API_KEY to enable translation");
    }

    JsonNode translated = ai.translate(body.strings(), body.from(), body.to());   // any OpenAI-compatible provider
    if (translated == null || !translated.isArray() || translated.size() != body.strings().size()
            || !translated.valueStream().allMatch(JsonNode::isString)) {
        throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "The AI provider returned an unexpected answer");
    }

    return translated;   // what options.callback() takes
}

Live Example: Translate with AI

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.

Client code
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(); }
});
Server code
// GET /api/variable-presets/{formId} — return the stored preset list, or [] when none are saved
@GetMapping("/api/variable-presets/{formId}")
public ResponseEntity<String> loadPresets(@PathVariable String formId) {
    String presets = jdbc.sql("SELECT json FROM variable_presets WHERE key = ?").param(formId).query(String.class).optional().orElse("[]");
    return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(presets);   // as stored
}

// PUT /api/variable-presets/{formId} — store the variable presets as-is: it's one JSON document
@PutMapping("/api/variable-presets/{formId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
@PreAuthorize("hasAuthority('edit-forms')")   // editing is an admin action: 403 otherwise
public void savePresets(@PathVariable String formId, @RequestBody JsonNode presets) {
    // A JsonNode, not a DTO: the presets are stored as they arrived, {} stays {}
    storedJson.put("variable_presets", formId, presets);
}

Live Example: Variable Presets

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.
  2. 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.
  3. 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.
  4. Save the JSON schema through saveSurveyFunc and your usual save endpoint. After the collaboration session ends, the next session starts from the saved schema.
Client code
// 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() }));
}
Server code
// 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.
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler,
                               Map<String, Object> attributes) {
    String formId = request.getURI().getPath().substring("/ws/forms/".length());
    // Spring Security's filter chain ran on the upgrade request: the demo_user cookie stands in for your real session check
    User user = request.getPrincipal() instanceof Authentication auth && auth.getPrincipal() instanceof User u ? u : null;
    String roomKey = roomKeys.forId(formId);
    if (!FORM_ID.matcher(formId).matches() || user == null || !user.editor() || roomKey == null) {   // like saving, editing together is for editors
        response.setStatusCode(HttpStatus.FORBIDDEN);   // the browser sees a refused handshake
        return false;
    }
    attributes.putAll(Map.of("user", user, "formId", formId, "roomKey", roomKey));
    return true;
}

@Override
public void afterConnectionEstablished(WebSocketSession session) {
    User user = (User) session.getAttributes().get("user");
    EditRoom room = rooms.join(roomKey(session), () -> savedDefinition((String) session.getAttributes().get("formId")));   // seed = the saved definition
    room.lock().lock();
    try {
        Participant client = room.add(session, Participant.displayName(session, user.name()));
        client.send(Participant.message("type", "init", "clientId", client.id(), "colorIndex", client.slot(), "color", room.color(client),
                "seed", room.seed(), "log", room.log()));   // init first
        List<Map<String, Object>> peers = room.roster(client);
        if (!peers.isEmpty()) {
            client.send(Participant.message("type", "presence-sync", "peers", peers));
        }
    } finally {
        room.lock().unlock();
    }
}

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage text) {
    JsonNode message = parse(text.getPayload());   // records stay opaque: {} is relayed as {}
    EditRoom room = rooms.room(roomKey(session));
    Participant client = Participant.of(session);
    switch (message.path("type").asString("")) {
        case "append" -> {
            if (message.hasNonNull("payload")) {   // append, then fan out
                room.append(client, message.get("payload"));
            }
        }
        case "presence" -> {
            if (message.hasNonNull("state") && text.getPayloadLength() <= 4096) {
                room.presence(client, message.get("state"));
            }
        }
        default -> { }   // unknown types: ignore
    }
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
    rooms.leave(roomKey(session), Participant.of(session));   // presence-leave to the others; the log lives until the room empties
}

Live Example: Edit Forms Together

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.

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.

Client code
// 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); }
});
Server code
// POST /api/responses — ask the SurveyJS service to validate, then store as usual
@PostMapping("/api/responses")
public ResponseEntity<Map<String, Object>> saveValidatedResponse(@RequestBody JsonNode body) {
    // A JsonNode, not a DTO: the stored answers keep every key, {} and 1.0 (see Save Responses)
    if (!body.path("formId").isString() || !body.path("data").isObject()) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Expected { formId, data } with an answers object");
    }
    String form = jdbc.sql("SELECT json FROM forms WHERE key = ?").param(body.get("formId").asString()).query(String.class).optional()
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Unknown form"));
    ServiceAnswer check = surveyjs.post("/response", Map.of("schema", json.readTree(form), "response", body.get("data")), Duration.ofSeconds(10));
    JsonNode answer = check.json();   // null when it isn't JSON: fails closed below
    if (check.status() == 422 && answer != null && answer.has("errors")) {
        if (answer.has("warnings")) {   // the stored definition itself has errors
            throw surveyjs.unexpected("/response", check, "The stored definition has errors");
        }
        return ResponseEntity.badRequest().body(Map.of("errors", answer.get("errors")));   // the answers don't fit the definition
    }
    if (check.status() != 200 || !(answer instanceof ObjectNode valid && valid.isEmpty())) {   // fail closed: only exactly {} means valid
        throw surveyjs.unexpected("/response", check);
    }
    int id = storedJson.insertResponse(body.get("formId").asString(), body.get("data"));   // stored as it arrived: 1.0 stays 1.0
    return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("id", id));
}

Live Example: Validate Responses

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 before saving and return its findings to Survey Creator so that authors can fix these problems before respondents encounter them.

Client code
// 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));
Server code
// PUT /api/forms/{id} — lint the definition from Creator before storing it
@PutMapping("/api/forms/{id}")
@PreAuthorize("hasAuthority('edit-forms')")
public ResponseEntity<JsonNode> saveLintedForm(@PathVariable String id, @RequestBody JsonNode definition) {
    // A JsonNode keeps {} as {} (see Load and Save Form JSON Schemas)
    ServiceAnswer lint = surveyjs.post("/schema", definition, Duration.ofSeconds(10));
    JsonNode answer = lint.json();   // null when it isn't JSON: fails closed below
    if (lint.status() == 422 && answer != null && answer.has("errors") && answer.has("warnings")) {
        return ResponseEntity.status(HttpStatus.UNPROCESSABLE_CONTENT).body(answer);   // errors: refuse the save, report them as they are
    }
    boolean clean = lint.status() == 200 && answer instanceof ObjectNode found && found.isEmpty();
    boolean warningsOnly = lint.status() == 200 && answer instanceof ObjectNode found && found.size() == 1 && found.has("warnings");
    if (!clean && !warningsOnly) {   // fail closed: nothing else is a lint result
        throw surveyjs.unexpected("/schema", lint);
    }

    storedJson.put("forms", id, definition);   // stored as it arrived: 1.0 stays 1.0
    return warningsOnly ? ResponseEntity.ok(answer) : ResponseEntity.noContent().build();   // warnings don't block it
}

Live Example: Lint JSON Schemas

Generate PDFs

A backend workflow may need a PDF for an archive or email attachment. SurveyJS PDF Generator 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.

Client code
// 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; }
}
Server code
// GET /api/claims/{id}/pdf — ask the SurveyJS service for the filled form and pass the PDF through
@GetMapping("/api/claims/{id:\\d+}/pdf")
public ResponseEntity<byte[]> claimPdf(@PathVariable long id) throws IOException {
    Claim claim = jdbc.sql("SELECT definition_version, data FROM responses WHERE form_id = 'claim' AND id = ?").param(id)
            .query(Claim.class).optional().orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Unknown claim"));
    String definition = switch (claim.definitionVersion()) {   // use the schema version recorded with the response
        case "v1", "v2" -> Files.readString(DEFINITIONS.resolve("relational-storage." + claim.definitionVersion() + ".json"));
        case null -> jdbc.sql("SELECT json FROM forms WHERE key = 'claim'").query(String.class).single();
        default -> throw new ResponseStatusException(HttpStatus.CONFLICT, "The schema version for this claim is unavailable");
    };

    ServiceAnswer pdf = surveyjs.post("/pdf", Map.of("schema", json.readTree(definition), "response", json.readTree(claim.data())), Duration.ofSeconds(60));
    if (pdf.status() != 200 || !pdf.hasContentType("application/pdf") || !pdf.startsWith("%PDF-")) {   // a 200 alone isn't a PDF
        throw surveyjs.unexpected("/pdf", pdf);
    }

    return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF)
            .header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline().filename("claim-" + id + ".pdf").build().toString())
            .cacheControl(CacheControl.noStore().cachePrivate())
            .body(pdf.bytes());
}

Live Example: Generate PDFs

Extract Responses from Documents

Some responses arrive as completed paper forms, scans, or PDFs. AI Form Response Extractor 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.

Client code
// 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;
}
Server code
// POST /api/work-orders/extract — send the uploaded scan to the SurveyJS service; return a draft response
@PostMapping(path = "/api/work-orders/extract", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Draft extractWorkOrder(MultipartHttpServletRequest request) throws IOException {
    MultipartFile scan = request.getFile("scan");
    if (scan == null || scan.getSize() > MAX_BYTES) {   // missing, a text field (not a file), or too large
        throw scan == null && request.getParameter("scan") == null
                ? new ResponseStatusException(HttpStatus.BAD_REQUEST, "Upload the scan in a field named \"scan\"")
                : new ResponseStatusException(HttpStatus.CONTENT_TOO_LARGE, "The scan must be a file of 5 MB or less");
    }
    if (FileType.detect(scan) == null) {   // by the first bytes, never the client's Content-Type
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "The file is not a PDF, PNG, JPEG, WebP or GIF document");
    }
    ServiceAnswer out = surveyjs.post("/extract", Map.of("schema", workOrder().orElseThrow(), "document", Base64.getEncoder().encodeToString(scan.getBytes())), Duration.ofSeconds(120));
    JsonNode result = out.json();   // JSON with base64 went out, not multipart; an answer that isn't JSON fails closed
    if (out.status() == 200 && result != null && result.path("data").isObject()) {   // nothing is saved: a person reviews the draft
        return new Draft(result.get("data"), result.has("confidence") ? result.get("confidence") : json.createArrayNode(), result.get("uniqueId"));
    }
    throw switch (out.status() + " " + (result == null ? "" : result.path("error").asString(""))) {
        case "400 INVALID_DOCUMENT" -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "The file is not a PDF, PNG, JPEG, WebP or GIF document");
        case "503 AI_NOT_CONFIGURED" -> new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE, "The SurveyJS service has no AI provider configured");
        case "502 EXTRACTION_FAILED" -> new ResponseStatusException(HttpStatus.BAD_GATEWAY, "Could not extract the response from the document");
        default -> surveyjs.unexpectedExtraction(out);   // fail closed, logged by status only
    };
}

Live Example: Extract Responses from Documents

Send feedback to the SurveyJS team

Need help? Visit our support page

Your cookie settings

We use cookies to make your browsing experience more convenient and personal. Some cookies are essential, while others help us analyse traffic. Your personal data and cookies may be used for ad personalization. By clicking “Accept All”, you consent to the use of all cookies as described in our Terms of Use and Privacy Statement. You can manage your preferences in “Cookie settings.”

Your renewal subscription expires soon.

Since the license is perpetual, you will still have permanent access to the product versions released within the first 12 month of the original purchase date.

If you wish to continue receiving technical support from our Help Desk specialists and maintain access to the latest product updates, make sure to renew your subscription by clicking the "Renew" button below.

Your renewal subscription has expired.

Since the license is perpetual, you will still have permanent access to the product versions released within the first 12 month of the original purchase date.

If you wish to continue receiving technical support from our Help Desk specialists and maintain access to the latest product updates, make sure to renew your subscription by clicking the "Renew" button below.