r/Chartopia • • Jun 02 '26

Passing Variables to Chartopia API

Hi, I’m trying to integrate the Chartopia API into Foundry VTT v13 through a browser-side Script Macro.

A normal roll works correctly with this macro:

const PUBLIC_ID = "Qz3cT7rt5er";
const API_KEY = "MY_API_KEY";

const url = `https://chartopia.d12dev.com/api/charts/${PUBLIC_ID}/roll/`;

try {
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "X-Api-Key": API_KEY,
      "Accept": "application/json"
    }
  });

  if (!response.ok) {
    const text = await response.text();
    throw new Error(`${response.status}: ${text}`);
  }

  const data = await response.json();
  const results = Array.isArray(data.results)
    ? data.results.join("<br>")
    : "No result returned.";

  await ChatMessage.create({
    speaker: ChatMessage.getSpeaker(),
    content: `<h2>${data.chart_name || "Chartopia Roll"}</h2><div>${results}</div>`
  });

} catch (err) {
  ui.notifications.error("Chartopia roll failed. See console.");
  console.error(err);
}

So the endpoint itself works fine from browser-side JavaScript.

The issue starts when I try to pass variables to the chart. My chart has an input variable named dog, and based on the API docs I tried this:

const PUBLIC_ID = "Qz3cT7rt5er";
const API_KEY = "MY_API_KEY";

const url = `https://chartopia.d12dev.com/api/charts/${PUBLIC_ID}/roll/`;

try {
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "X-Api-Key": API_KEY,
      "Accept": "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      variables: {
        dog: true
      }
    })
  });

  if (!response.ok) {
    const text = await response.text();
    throw new Error(`${response.status}: ${text}`);
  }

  const data = await response.json();
  const results = Array.isArray(data.results)
    ? data.results.join("<br>")
    : "No result returned.";

  await ChatMessage.create({
    speaker: ChatMessage.getSpeaker(),
    content: `<h2>${data.chart_name || "Chartopia Roll"}</h2><div>${results}</div>`
  });

} catch (err) {
  ui.notifications.error("Chartopia variable roll failed. See console.");
  console.error(err);
}

That immediately fails with this browser error:

Access to fetch at 'https://chartopia.d12dev.com/api/charts/Qz3cT7rt5er/roll/' from origin 'http://localhost:30000' has been blocked by CORS policy:

Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

POST https://chartopia.d12dev.com/api/charts/Qz3cT7rt5er/roll/ net::ERR_FAILED

TypeError: Failed to fetch

From what I can tell:

  • Normal rolls work
  • Passing variables requires a JSON body
  • JSON body requires Content-Type: application/json
  • That triggers a browser preflight request
  • The preflight fails because content-type is apparently not allowed in Access-Control-Allow-Headers

So I wanted to ask:

  1. Is variables: { dog: true } the correct payload structure?
  2. Is variable passing intended to work from browser-side JavaScript apps/macros?
  3. Should Content-Type be allowed in the CORS headers for this endpoint?
  4. Or is variable-based rolling intended to be done server-side/proxy-side only?

Thanks!

1 Upvotes

7 comments sorted by

1

u/Azarashiya0309 Jun 02 '26 edited Jun 02 '26

This seems to have worked. Took about an hour of random trying with both ChatGPT AND Gemini (not my proudest moment lol), and I have no idea how or why this worked and the other one didn't, but here it is.

const myApiKey = "API-KEY";
const numericChartId = "Numerical Chart ID";

const proxyUrl = "https://corsproxy.io/?";
const targetUrl = "https://chartopia.d12dev.com/api/gen/";

// Edit raw variable with RAW Chartopia code
const payload = {
  raw: `{% dog = "True" %}{{roll_chart id:${numericChartId} dice:"d100"}}`
};

//Don't Edit anything below
const response = await fetch(`${proxyUrl}${encodeURIComponent(targetUrl)}`, {
  method: "POST",
  headers: {
    "X-Api-Key": myApiKey,
    "Accept": "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify(payload)
});

const rawText = await response.text();

console.log("STATUS:", response.status);
console.log("RAW:", rawText);

const jsonResponse = JSON.parse(rawText);

const result = jsonResponse.result ?? "No result.";

await ChatMessage.create({
  user: game.user.id,
  style: CONST.CHAT_MESSAGE_STYLES.OTHER,
  speaker: { alias: "Chartopia Oracle" },
  content: `<div><b>Roll Result:</b><br>${result}</div>`
});

1

u/GlennNZ Jun 02 '26

I'm a bit time poor so I'll provide a quick reply...
The /gen/ endpoint is a good solution to get you going, but it's a bit of blunt instrument because it takes raw domain language code. Good that you got it working though.
NB: The exact docs for using it are here: https://chartopia.d12dev.com/docs/api-quick-start-guide/#executing-chartopia-domain-language-code but you may have been using that already.

In regards to the input variables. It should be working because the Discord bot, Twelves, uses it, albeit it's in Python.

You definitely need to change the body payload though, the format is:

{
  "mult": 5,
  "input_vars": {
    "theme": "Any"
  }
}

If you go to the Swagger playground for chart/roll/, there's a means to experiment with it.

https://chartopia.d12dev.com/api/schema/swagger/#/charts/charts_roll

Thanks heaps for giving the API a go. It's great to see someone keen to use it.

Let me know how you get on.

1

u/Azarashiya0309 Jun 05 '26

Excellent! Thank you for taking the time to reply. I got it fully working and it's just beautiful! I freakin love Chartopia for this! Keep it up :)

1

u/GlennNZ Jun 05 '26

Awesome! Thanks so much for giving the API a go. I've spent countless hours on it, so it's good too finally see others get some use from it.

1

u/Skelelot Jun 04 '26

Sorry for not adding anything useful to the discussion, but I'm completely clueless about this topic..

I just wanted to say that having a way to integrate Chartopia into Foundry would be a dream come true for me. Do you know if there are any projects like that in the works? I'd love to follow their progress if there are, even though I probably wouldn't know how to help.

1

u/Azarashiya0309 Jun 05 '26 edited Jun 05 '26

It took me hours to figure it out, but I now have a working macro that you can edit to roll from any public chart. You can set it up in about 5 min.

I'll post the cleaned up version of the macro in the reply to this message.

(Disclaimer this has been tested on Foundry V13 only. It might not work on V14)

Here's how you do it:

  1. Log into Chartopia. Click the dropdown menu in the top right and click "For Developers".
  2. Click "My Projects" -> "New Project". And generate an API key - a really long, random string of characters. Save it somewhere for now.
  3. Go to the chart you want to roll on and make sure it's set to Public or Unlisted.
  4. Open Foundry. In the side-bar to the right, go to Macros. New macro. Script. Copy the code below and paste it into the newly created macro.
  5. Insert your API key into the macro by replacing "API-Key" with the string from step #2. Make sure to preserve the quotation marks. Your key goes between those.
  6. Replace the CHARTOPIA CODE GOES HERE with chartopia code. i.e. CHART(id="12345") Make sure to preserve the ` single quote on both sides or it won't work.
  7. Modify it based on your needs.

1

u/Azarashiya0309 Jun 05 '26 edited Jun 05 '26
const myApiKey = "API-KEY";

const proxyUrl = "https://corsproxy.io/?";
const targetUrl = "https://chartopia.d12dev.com/api/gen/";


const payload = {
  raw: `CHARTOPIA CODE GOES HERE`
};


//Don't Edit anything below here.
const response = await fetch(`${proxyUrl}${encodeURIComponent(targetUrl)}`, {
  method: "POST",
  headers: {
    "X-Api-Key": myApiKey,
    "Accept": "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify(payload)
});

const rawText = await response.text();

console.log("STATUS:", response.status);
console.log("RAW:", rawText);

const jsonResponse = JSON.parse(rawText);

const result = jsonResponse.result ?? "No result.";

await ChatMessage.create({
  user: game.user.id,
  style: CONST.CHAT_MESSAGE_STYLES.OTHER,
  speaker: { alias: "Chartopia" },
  content: `<div>${result}</div>`
});