SurveyJS Python Backend Integration with FastAPI /

Save Responses

MIT

Save Responses

Send completed form responses to your backend and store them as JSON. The server returns the saved response's ID to confirm success.

Documentation

Try this

  1. Enter your email and a message. Both fields are required.
  2. Press Send message. The completion screen shows Sending your message... until the server confirms the save, then displays the response's ID.
  3. Open Requests and expand POST /api/responses to inspect the request body and the server's response. Then open Data to find the saved record with the same ID.
  4. If saving fails, an error message appears. Press Try again to resend your answers.
  5. Press Start over to clear the form and submit another response.

Running main@5b404b3

    No requests

      What the server stored
      JSON definition · shared/definitions/save-response.json View on GitHub
      {
        "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
          }
        ]
      }
      Client · shared/client/save-response.js · sjs:save-response.client View on GitHub
      // 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 · app/routes/save_response.py · sjs:save-response.server View on GitHub
      # 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}