Unable to add a new question using API

  • hibjul
    Asked on March 26, 2025 at 7:04 AM

    Unable to add new questions
    error message
     Error creating JotForm: {

     responseCode: 400,

     message: 'Question not created!',

     content: '',

     duration: '121.08ms',

      info: 'https://api.jotform.com/docs#form-id-questions'

    }

    const
    axios = require("axios");


    const JOTFORM_API_KEY = "57c42030e2c52d98a6c9a0a03b1c6ef6";

    const JOTFORM_BASE_URL = "https://api.jotform.com";


    function delay(ms) {

      return new Promise((resolve) => setTimeout(resolve, ms));

    }


    async function createJotForm(questions, formTitle = "Generated Form") {

      try {

        // Step 1: Create a new form

        const formResponse = await axios.post(

          `${JOTFORM_BASE_URL}/user/forms`,

          new URLSearchParams({

            apiKey: JOTFORM_API_KEY,

            title: formTitle,

            status: "ENABLED",

          })

        );


        console.log("🔹 Form Creation Response:", formResponse.data);

        const formId = formResponse.data?.content?.id;

        if (!formId) throw new Error("Form creation failed!");

        axios

          .get(`${JOTFORM_BASE_URL}/form/${formId}?apiKey=${JOTFORM_API_KEY}`)

          .then((res) => console.log("✅ Form Details:", res.data))

          .catch((err) =>

            console.error("❌ Cannot Access Form:", err.response.data)

          );

        await delay(1000);

        console.log(`✅ Form Created: ${formId}`);


        // Step 2: Add questions to the form

        for (const question of questions) {

          const questionData = {

            apiKey: JOTFORM_API_KEY,

            type: "control_textbox", // Ensure the type is correct

            name: `${question.id}_question`,

            text: question.title.replace(/<\/?p>/g, ""), // Remove HTML tags

            // options: question.options.map((opt) => opt.text).join("|"),

          };


          console.log("🔹 Adding Question:", questionData);


          await axios.post(

            `${JOTFORM_BASE_URL}/form/${formId}/questions`,

            { type: "control_textbox", text: question.title },

            {

              headers: {

                "Content-Type": "application/json",

                apikey: JOTFORM_API_KEY,

              },

            }

          );


          await delay(500); // Prevent rate limiting

        }


        console.log(`✅ Questions Added to Form: ${formId}`);

        return `https://www.jotform.com/${formId}`;

      } catch (error) {

        console.error(

          "❌ Error creating JotForm:",

          error.response?.data || error.message

        );

        return null;

      }

    }


    // Example Usage:

    const input = [

      {

        id: "e57edd09-0372-4f32-b0cb-fb259ed891d3",

        questionType: "Text",

        levelTitle: "Clinical Consideration",

        title:

          "<p>What clinical indicators suggest the approach may not be sufficient?</p>",

        // options: [

        //   { text: "Disease progression despite treatment", value: "1" },

        //   { text: "Symptoms worsening or persisting", value: "2" },

        // ],

        sectionId: "ea314d5c-5cf6-4751-a23a-e4c1b2989bfe",

      },

    ];


    createJotForm(input).then((formUrl) => {

      if (formUrl) console.log(`🚀 Form Created: ${formUrl}`);

    });


  • Kyle JotForm Support
    Replied on March 26, 2025 at 7:54 AM

    Hi Hibjul,

    Thanks for reaching out to Jotform Support. I tested our API to add a new question using Postman and could not replicate the issue on my end. Here’s the curl command I used for the test:

    curl -X POST -d "question[type]=control_head" -d "question[text]=Header" -d "question[order]=1" -d "question[name]=clickTo" "https://api.jotform.com/form/{formID}/questions?apiKey={apiKey}"

    Using this command, I successfully added a question to my sample form without encountering any errors. This indicates that the issue might be specific to your implementation or the data being sent. Check out my screenshot below to see the result:Unable to add a new question using API Image 1 Screenshot 20Can you check that all required fields, such as type, text, order, and name, are correctly filled out? For example, the type should be valid (e.g., control_textbox), and text should be clear of unexpected HTML tags or special characters. Also confirm that your API key is correct and has sufficient permissions to create questions. We have a guide on Jotform API Documentation that you can check out. If the same thing happens, share with us the full API request details and any additional error messages you may have received.

    Give it a try and reach out again if you have any other questions.

Your Answer