Issue with saving data in database

Hello Fliplet Support Team,

I’m encountering an issue with saving data to the Fliplet Database. The API call seems to be working successfully, but the data is not appearing in the database.

Issue Description:
I am generating a structured JSON study plan using OpenAI’s API.
The API correctly returns the expected JSON output (example below).
The system parses the JSON and transforms it into entries for the Fliplet Database.
The Fliplet database connection is established, and the console logs show “Data saved successfully.”
However, when I check the database, the entries do not appear.
What I’ve Tried:
Ensuring JSON format is correct:
The AI output is valid JSON, structured as an array of objects with fields: “Title”, “Date”, “Start Time”, “End Time”, “Content”, and “Session ID”.
Example output from AI:
[
{
“Title”: “Study Session (2025-02-19)”,
“Date”: “2025-02-19”,
“Start Time”: “14:00”,
“End Time”: “14:25”,
“Content”: “Study Task: Introduction to DNA replication - Activity: Read and highlight key points from the textbook”,
“Session ID”: “SS20250219”
}
]
Attempted saving with and without wrapping the data inside an object (e.g., { data: {…} }).
Checked console logs:
The logs confirm a successful connection to the Fliplet Database.
The logs also show “Data saved successfully.”
Despite this, the data does not actually appear inside the database.
Checked for errors:
No error messages appear in the logs.
No indication of failed requests or permission issues.
Request for Assistance:
Could you please help me identify why the data is not appearing in the Fliplet Database, even though the logs confirm it was saved?
Is there a known issue with the API, or do I need to modify how the data is being inserted?

Thank you for your time and support!

Hi,

We can certainly help with that. Can you provide the CURL request for your API request to save data to a datasource? Remember to replace the auth token with a placeholder string.

Thanks,
Deb

there’s a message telling me that I can;t put more than two link in a post so I;ll divide my CURL request into multiple message
Here it is
curl ‘https://us.i.posthog.com/s/?ip=1&_=1740098555254&ver=1.221.1&compression=gzip-js
-H ‘accept: /
-H ‘accept-language: fr,fr-FR;q=0.9,en-US;q=0.8,en;q=0.7’
-H ‘content-type: text/plain’
-H ‘origin: https://studio.fliplet.com’ \

–data-raw $‘\u001f\u008b\u0008\u0000\u0000\u0000\u0000\u0000\u0000\u0003­R]Oà \u0014ý+\u0086ì±,\(\u0005ú¦\u0099q¾\u0019£\u000fÆ,\r-Ô¡\u001bm\u0006Ý2\u0097þwifâ|ß#çr>8Ü÷\u0013\u001a\u0006gP\u0089\u0008(Ny\u009bã\u0006j\u0086\u00850-Ö@\u0008\u0006¦\u001b­¸\u0000)\u0018Ê\u0090Ý[\u001fÓõYðº\u000fë.&¬ßu½ÝEg\u0003*O\u007f\u0093ª>Æ\u0009¢9É.P££Fe2\u008eÇÞ¢\u0092gè\u008c$@\u007f$å\u0083ó¦;ܬ\u009d1ÖOêú¸ét\u008ax\u001aÇ\u000cE·µ\u0021êm\u008fJ\u00109\u0021JrN\u0008äcv]AymA5®¦\u0016l\u0008®óÕeå\u00043Ð\u0005\u0016-çX\u001b¦0Im+mDal\u009eägg¿\u007f\u001c\u008a[¢\u0012ÇpÀª¨%\u0096-\u0018Ij¥LSL\u009c\u008d«§¤¶þ=T{»\u009b\u009c\u0013\u0008sJa\u000ei\u0010»¯ô\u0080\u0012õë¦2ß²x\u0096àâç\u009d_ø×<6ì\u0096Ñáéñð\u0016\u0086\u0097fÉ©ØÊ\u0005[Þ?L_n\\u0088Î7ñ\u001cj\u0008\u0018r\n\u009c`I\u0094R(µÐµm°iQ\u0018\u00012®~\u0000êl1Mg\u0002\u0000\u0000’ ;
curl ‘https://us.api.fliplet.com/v1/data-sources/964898/data?appId=269877
-X ‘PUT’
-H ‘accept: /
-H ‘accept-language: fr,fr-FR;q=0.9,en-US;q=0.8,en;q=0.7’
-H ‘authorization: Bearer [My auth token]==’
-H ‘content-type: application/x-www-form-urlencoded; charset=UTF-8’
-b 'hubspotutk=ac6c893c966971772a55daeb93f71311;

intercom-device-id-eo99qllm=16e5f366-1279-4a1d-ae30-86cdb58d4da2; ruid=yT6KYd7Jrs; _delighted_web={%22YfShW8tzhdA4omOP%22:{%22_delighted_fst%22:{%22t%22:%221720806079001%22}%2C%22_delighted_lst%22:{%22t%22:%221719860937000%22%2C%22m%22:{%22token%22:%22POFKHgtjt7XbeGHjYd4hodce%22}}}}; cookieyes-consent=consentid:cVBiNDYxSzVyZ1k1TU4xenRZdXRid1ZiMklNc2tvZzY,consent:yes,action:yes,necessary:yes,functional:yes,analytics:yes,performance:yes,advertisement:yes,other:yes; intercom-id-eo99qllm=2ca16aa0-dc00-4249-b8af-3fee35d0fb24; _CEFT=EgNwlgpg7hAmBcAZAHGASgOygMQgNgEYAGAaAEMALAUQAcBzAWwEUmA5e0SGBAMwHFWAdgBWAJwASAQRpSSxImSLI8rABoB7AM6doceFXHIy4gB4AtAFJmA6nRIBhAK50A-gBcMDANLX1AYx1ueABPNyhEOjQAeQBaCABVJhJhABFNZCiAGzc6QSgoIA; _gcl_gs=2.1.k1$i1738295884$u170902391; _gac_UA-653644-19=1.1738295888.Cj0KCQiA4-y8BhC3ARIsAHmjC_E9tLshXXnIM1BeUmBsQzAIfiRZMciUjIG8K83tBbOCwcNjtCinbNIaAsDeEALw_wcB; mf_user=f5833e9b65b500c49577005d4f1ccbdc|; _gcl_aw=GCL.1738295891.Cj0KCQiA4-y8BhC3ARIsAHmjC_E9tLshXXnIM1BeUmBsQzAIfiRZMciUjIG8K83tBbOCwcNjtCinbNIaAsDeEALw_wcB; auth_token=[My auth token]%3D%3D; _gcl_au=1.1.1096282177.1739039711; _ce.s=v~208c10e06e164712f2f360a808fd2ed070aee711~lcw~1739050996643~lva~1739050727915~vpv~9~flvl~%2CL8iRnwFe610%3AahEpgmQQNpg%2CfGN7jrHApHA%3A100a086NXos%2CEH8aHxZJZWg%3ACug_tnmKWoc%2CytwLgRO-eUQ%3AjDs8Oltg7ww~v11.fhb~1739050728816~v11.lhb~1739051038215~vir~returning~v11.cs~436994~v11.s~14e6cc50-e665-11ef-863b-d15c42abc206~v11.sla~1739050990254~gtrk.la~m6wpx8cp~lcw~1739051038260; ph_phc_Tbfg4EiRsr5iefFoth2Y1Hi3sttTeLQ5RV5TLg4hL1W_posthog=%7B%22distinct_id%22%3A%22194f87b6762634-092ba395837a15-26011b51-e1000-194f87b676315e0%22%2C%22%24device_id%22%3A%22194f87b6762634-092ba395837a15-26011b51-e1000-194f87b676315e0%22%2C%22%24user_state%22%3A%22anonymous%22%2C%22%24session_recording_enabled_server_side%22%3Afalse%2C%22%24autocapture_disabled_server_side%22%3Afalse%2C%22%24active_feature_flags%22%3A%5B%5D%2C%22%24enabled_feature_flags%22%3A%7B%7D%2C%22%24feature_flag_payloads%22%3A%7B%7D%2C%22%24sesid%22%3A%5B1739335625217%2C%22194f87b6a0125b-01f27add07cb2c-26011b51-e1000-194f87b6a02165b%22%2C1739335625217%5D%7D; _ga_CM1E1N1Q4R=GS1.1.1739335622.1.1.1739335629.0.0.0; _ga_0BHLMNSBYS=GS1.1.1739855931.28.0.1739855931.0.0.0; _gid=GA1.2.371042501.1740032939; __hssrc=1; _ga_F1JX7MGZJ1=GS1.1.1740032948.16.0.1740032948.0.0.0; _ga_NYBXSCS0NR=GS1.1.1740098258.5.1.1740098307.0.0.0; __hstc=203209230.ac6c893c966971772a55daeb93f71311.1720635934271.1740032941240.1740098434514.104; __hssc=203209230.1.1740098434514; intercom-session-eo99qllm=QzR1QmduL2JFc05keXE3T2N2ak1hNFRBRWhGbHJNR2tBalRjWjg5aURGR2E4TytlQzVkdXkvUjQ5T21Oa3FsNnZ4cHFxOUZKYmd6L05wMitqUjFxSFRrd09QdXpKMXl0L0dLUUtnaGpiWUU9LS1IV0oyR1NhOGxsNHdXTEswdXhlUnBnPT0=–1d65272b9b2d6f29f600206373d0c0c7dea3a8a5; _ga_10D296KYXY=GS1.1.1740098435.136.0.1740098435.0.0.0; mp_b44bd46d5ad4a8de7b436914865371f0_mixpanel=%7B%22distinct_id%22%3A%20%22us-142150-80999%22%2C%22%24device_id%22%3A%20%22190a807564c18eb-0cac784fad0098-26001f51-e1000-190a807564d18eb%22%2C%22%24initial_referrer%22%3A%20%22https%3A%2F%2Ffliplet.com%2F%22%2C%22%24initial_referring_domain%22%3A%20%22fliplet.com%22%2C%22__mps%22%3A%20%7B%7D%2C%22__mpso%22%3A%20%7B%7D%2C%22__mpus%22%3A%20%7B%7D%2C%22__mpa%22%3A%20%7B%7D%2C%22__mpu%22%3A%20%7B%7D%2C%22__mpr%22%3A%20%5B%5D%2C%22__mpap%22%3A%20%5B%5D%2C%22company%22%3A%20%5B%0A%20%20%20%20%22us-80999%22%0A%5D%2C%22%24user_id%22%3A%20%22us-142150-80999%22%2C%22%24search_engine%22%3A%20%22google%22%2C%22utm_source%22%3A%20%22adwords%22%2C%22utm_medium%22%3A%20%22ppc%22%2C%22utm_campaign%22%3A%20%22Search%20%7C%20Template%20%7C%20Events%20-%20Generic%20%7C%20US%2C%20UK%202%22%2C%22utm_term%22%3A%20%22conference%20apps%20for%20attendees%22%7D; deviceUuid=af14bffe-0adf-f66f-c510-02b017d4b230; _ga=GA1.1.483395905.1720805959; _ga_XJMS835XZP=GS1.1.1740098440.98.1.1740098450.0.0.0; _ga_XZN60VWWL5=GS1.1.1740098362.114.1.1740098450.0.0.0; _ga_TT2MPH1G61=GS1.1.1740098362.117.1.1740098450.43.0.0;

ph_phc_dz86R81itjBnDnU4tc3A32uPIwYsuTcH527m8D3HEGt_posthog=%7B%22distinct_id%22%3A%22us-142150-80999%22%2C%22%24sesid%22%3A%5B1740098555113%2C%22019525f0-31a6-7f55-ad39-05719ad76de4%22%2C1740098253222%5D%2C%22%24epp%22%3Atrue%2C%22%24initial_person_info%22%3A%7B%22r%22%3A%22https%3A%2F%2Ffliplet.com%2F%22%2C%22u%22%3A%22https%3A%2F%2Fstudio.fliplet.com%2Fsignin%22%7D%7D’ \

-H ‘origin: https://us.api.fliplet.com
-H ‘priority: u=1, i’
-H ‘referer: Stuy plan test - Smart calendar test
-H ‘sec-fetch-dest: empty’
-H ‘sec-fetch-mode: cors’
-H ‘sec-fetch-site: same-origin’
-H ‘user-agent: Mozilla/5.0 (X11; Linux aarch64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 CrKey/1.54.250320’
-H ‘x-app-locales: en’
-H ‘x-device-platform: web’
-H ‘x-device-tracking: {“uuid”:“af14bffe-0adf-f66f-c510-02b017d4b230”,“model”:“Browser”,“platform”:“Win32”,“manufacturer”:“Web”,“version”:1,“width”:416,“height”:854}’
-H ‘x-requested-with: XMLHttpRequest’
–data-raw ‘undefined=&undefined=&undefined=’

Do you need anything else ?

thank you Deb

Just to be clear, where are you executing your API request from? From outside Fliplet environment for e.g. Postman or from inside the app i.e from the developer options.

From inside the app in the preview tab

If you are writing custom code from inside the app you use our JS API’s not our REST API’s.

See docs here:

Data source: Data Sources JS APIs | Fliplet Developers Documentation
AI JS API: AI (Artificial Intelligence) | Fliplet Developers Documentation

Hope this helps

Hi I thin that there is a misunderstanding of my request.

I did use what’s written in the fliplet documentation to save something to the databe but it still don’t work. let me clarify it better:

when we try to save AI-generated study{not fliplet’s AI}sessions to the Fliplet data source, we’re encountering an issue:

  • The session_ID gets saved correctly.
  • But instead of storing the full study session details, the other fields (Title, Date, Start Time, End Time, Content) appear as empty strings (["", "", "", ""]).

Here’s an example of the JSON data our AI generates and attempts to store:

json

type or paste c[
  {
    "Title": "Study Session (2025-02-26)",
    "Date": "2025-02-26",
    "Start Time": "20:45",
    "End Time": "21:10",
    "Content": "Study Task: Review DNA replication - Activity: Read the section about DNA replication in the textbook and summarize the main points",
    "Session ID": "SS20250226"
  },
  {
    "Title": "Study Session (2025-02-27)",
    "Date": "2025-02-27",
    "Start Time": "20:45",
    "End Time": "21:10",
    "Content": "Study Task: Review DNA replication - Activity: Use internet resources to further explore and understand DNA replication",
    "Session ID": "SS20250227"
  }
]
`Preformatted text`ode here

And this is the code we are using to insert the data into the Fliplet database:

js

CopierModifier

// Function to save study plan to Fliplet database using .connect() and .insert()
async function saveToDatabase(entriesArray) {
  const dataSourceId = 964898; // Your Fliplet Database ID

  if (!Array.isArray(entriesArray) || entriesArray.length === 0) {
    console.error("Error: No valid study sessions to save.");
    alert("Error: No valid study sessions to save.");
    return;
  }

  // Transform each entry so that its data is wrapped in a "data" object with keys matching your database columns.
  const transformedEntries = entriesArray.map(entry => {
    // Log the original entry for debugging
    console.log("Original entry:", entry);
    return {
      data: {
        "Title": entry["Title"] || "",
        "Date": entry["Date"] || "",
        "Start Time": entry["Start Time"] || "",
        "End Time": entry["End Time"] || "",
        "Content": entry["Content"] || "",
        "Session ID": entry["Session ID"] || ""
      }
    };
  });

  console.log("Transformed entries to save:", transformedEntries);

  try {
    console.log("Connecting to Fliplet Database...");
    // Connect to the data source
    const connection = await Fliplet.DataSources.connect(dataSourceId);
    console.log("Connection established. Inserting entries...");

    // Insert the entries into the database using the connection.insert method
    await connection.insert(transformedEntries);

    console.log("Data saved successfully.");
    alert("Study plan added to your agenda!");
  } catch (error) {
    console.error("Error saving to database:", error);
    alert("Failed to save study plan. Please try again.");
  }
}

Could you help us understand why the fields are not being stored correctly? Are we structuring the insert request incorrectly, or is there something specific about how Fliplet handles objects inside data?

Looking forward to your guidance! Thanks in advance.

You shouldn’t put your data inside a “data” object, it should be a object with key values only. See example here: Data Sources JS APIs | Fliplet Developers Documentation

Thank for that precision, I’ve updated my code to have an object with key value only but it still doesn;t work.
Despite ensuring that everything is set up correctly on my end—following your documentation, matching field names, and verifying the data format—new entries are still being saved with empty data objects. Older entries in the same data source populate correctly, which makes me suspect there might be an issue on the Fliplet side, possibly with the data source configuration or API behavior.

Problem Overview:

  • Data Source ID: 964898

  • Issue: New entries inserted via the Fliplet Data Sources JS API have empty data objects, while older entries retain their expected fields (e.g., Title, Date, Start Time, etc.).

  • Expected Behavior: New entries should save with all fields populated, as shown in the transformed data before insertion.

  • Actual Behavior: New entries are created, but their data objects are empty in the database.

Steps I’ve Taken:

  1. Field Name Verification: Confirmed that field names in my code (“Title”, “Date”, “Start Time”, “End Time”, “Content”, “Session ID”) match the column names in the data source exactly, including case and spacing.

  2. Data Source Check: Reviewed the data source settings—columns are correctly defined, and older entries display as expected.

  3. Logging: Added detailed console logs to trace the data from AI output to database insertion. The data appears correct before saving but doesn’t persist.

  4. Minimal Test: Tried inserting a single entry manually, but the issue remains.

Code:

Here’s the JavaScript code I’m using to generate and save the study plan:

type or paste codFliplet.Navigator.onReady().then(() => {
  console.log("Fliplet is ready!");
  document.getElementById("studyForm").addEventListener("submit", async function(event) {
    event.preventDefault();
    const subject = document.getElementById("subject").value;
    const topics = document.getElementById("topics").value;
    const testDate = document.getElementById("testDate").value;
    const testType = document.getElementById("testType").value;
    const resources = document.getElementById("resources").value || "None provided";
    const studyTime = document.getElementById("studyTime").value;
    const sessionLength = document.getElementById("sessionLength").value;
    const today = new Date().toISOString().split("T")[0];

    const prompt = `Create a structured study plan for a student preparing for a test.
Current Date: ${today}  
Test Date: ${testDate}  
Subject: ${subject}  
Topics: ${topics}  
Test Type: ${testType}  
Available Study Resources: ${resources}  
Preferred Study Time: ${studyTime}  
Session Length: ${sessionLength} minutes  
**FORMAT GUIDELINES:**  
- Spread study sessions evenly until the test  
- Use exact dates (YYYY-MM-DD)  
- Provide specific time slots in the format (HH:MM - HH:MM)  
- For each session, output two lines:
    • The first line is the time slot  
    • The second line contains "Study Task: ..." and "Activity: ..." separated by a hyphen  
- Do not include labels like "Homework" or "Break".  
- Ensure the response is fully completed with no cut-off text.  
- **Return the output as a JSON array** of objects with keys: "Title", "Date", "Start Time", "End Time", "Content", "Session ID".`;

    try {
      console.log("Sending prompt to OpenAI:", prompt);
      const response = await fetch("https://api.openai.com/v1/chat/completions", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer my API " // My API key
        },
        body: JSON.stringify({
          model: "gpt-4",
          messages: [{ role: "user", content: prompt }],
          max_tokens: 1000
        })
      });

      const data = await response.json();
      const aiOutput = data.choices[0].message.content.trim();
      console.log("AI Output (raw):", aiOutput);

      let studyPlanEntries = JSON.parse(aiOutput);
      console.log("Parsed study plan entries:", studyPlanEntries);

      document.getElementById("output").innerHTML = `
        <pre>${JSON.stringify(studyPlanEntries, null, 2)}</pre>
        <button id="confirmPlan">Confirm Study Plan</button>
      `;

      document.getElementById("confirmPlan").addEventListener("click", function() {
        saveToDatabase(studyPlanEntries);
      });
    } catch (error) {
      console.error("Error fetching AI response:", error);
      document.getElementById("output").innerText = "Failed to generate study plan. Please try again.";
    }
  });

  async function saveToDatabase(entriesArray) {
    const dataSourceId = 964898;
    if (!Array.isArray(entriesArray) || entriesArray.length === 0) {
      console.error("Error: No valid study sessions to save.");
      alert("Error: No valid study sessions to save.");
      return;
    }

    const transformedEntries = entriesArray.map(entry => ({
      "Title": entry["Title"] || "",
      "Date": entry["Date"] || "",
      "Start Time": entry["Start Time"] || "",
      "End Time": entry["End Time"] || "",
      "Content": entry["Content"] || "",
      "Session ID": entry["Session ID"] || ""
    }));

    console.log("Transformed entries to save:", transformedEntries);

    try {
      console.log("Connecting to Fliplet Database...");
      const connection = await Fliplet.DataSources.connect(dataSourceId);
      console.log("Connection established. Inserting entries...");
      await connection.insert(transformedEntries);
      const allEntries = await connection.find();
      console.log("All entries in database:", allEntries);
      console.log("Data saved successfully.");
      alert("Study plan added to your agenda!");
    } catch (error) {
      console.error("Error saving to database:", error);
      alert("Failed to save study plan. Please try again.");
    }
  }
});e here

Logs from a Recent Test:

  • AI Output:

json

[ { "Title": "Study Session (2025-02-27)", "Date": "2025-02-27", "Start Time": "10:30", "End Time": "11:00", "Content": "Study Task: Review basic concepts of DNA replication - Activity: Read chapter on DNA replication from textbook", "Session ID": "SS20250227" } ]

  • Transformed Entries:

javascript

[ { "Title": "Study Session (2025-02-27)", "Date": "2025-02-27", "Start Time": "10:30", "End Time": "11:00", "Content": "Study Task: Review basic concepts of DNA replication - Activity: Read chapter on DNA replication from textbook", "Session ID": "SS20250227" } ]

  • Database Entries After Save:

javascript

EnvelopperCopier

[ { "id": 70960481, "data": { "Date": "2025-01-30", "Title": "tst math", "End Time": "23:45", "Session ID": "ubmjoyzw-xmxb-coqx-oa1f-azaikbxcahbv", "Start Time": "23:45" }, "createdAt": "2025-01-31T04:45:38.593Z", "updatedAt": "2025-02-18T05:31:19.387Z" }, { "id": 71234841, "data": {}, "createdAt": "2025-02-27T01:28:46.079Z", "updatedAt": "2025-02-27T01:28:46.079Z" } ]

My Request:

Everything seems correct on my side—the data is properly formatted, and the field names align with the data source. Yet, new entries consistently have empty data objects, unlike older ones. Could this be due to a recent change in Fliplet’s API or a misconfiguration in the data source? I’d really appreciate your help in pinpointing and fixing this issue.


This is a picture of what’s really being saved in my database. As you can see the columm name match with the Code and I’m following what’s recommended by the doc yet only the Session_id get created and a random arrray of empty strings appear.

Thanks for the detailed logs and code.

I believe the issue is that to the await connection.insert(transformedEntries); you are passing an array with an object inside it.

The insert() function only accepts an object, not an array of objects. You can simply change it to await connection.insert(transformedEntries[0]);

I’ve tested this and it works as expected.

Hope this helps,
Deb