I just started playing with observable framework tonight and I’m struggling to figure out the best way to achieve some things involving fetching JSON data from an API.
The API that I’m using as an experiment happens to be the time tracking service that my company uses, but I think the questions would apply to any RESTful API that doesn’t have a language-specific library.
This particular API seems to require an API key or “token” as a url parameter and additionally allows two optional parameters for start date and end date to limit the returned data. It returns the results as a JSON object containing an array of objects.
I’ve written a data loader that successfully fetches some data and I’m able to display it using markdown. The place where I’m struggling is with refreshing that data. I understand that the combination of data loaders and FileAttachment() is intended to be used to create static datasets to speed up page loading, so it probably isn’t the solution for me. I would like a user to be able to select a data range and/or refresh the existing data if they think that things may have changed.
I’ve tried moving the data fetching to the markdown file, however it the fetch doesn’t seem to be returning any data.
These are two separate js blocks in the markdown file, one after the other:
async function getData() {
const url = "https://api.service.com?token=blah&start_date=2024-08-01&end_date=2024-08-15";
try {
const response = await fetch(url,
{
mode: "no-cors"
});
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const json = await response.json();
console.log(json);
} catch (error) {
console.error(error.message);
}
}
const timesheets = getData();
display(timesheets);
// const timesheets = await FileAttachment("./data/timesheets.json").json();