Is it possible with Sanity? scheduled external API calls to Sanity

844 views Asked by At

Here is what I would like to accomplish?

1- Make a fetch call to a news API everynight 2- Pull latest headlines 3- Import to Sanity...

Does Sanity let you do that? Does it have a cron job?

Thank you,

1

There are 1 answers

1
Henrique Doro On

Sanity does not provide any native way to do that, but you could create cron jobs with an external serverless provider that does the functionality you're looking for

Firebase scheduled functions are an example of provider, but there are many more options. I suggest taking a look at Serverless framework examples.

After you figure out what you'll use, then use Sanity's HTTP API or one of their API clients (@sanity/client for Javascript) to add the data to it. You'll need a token to do so, as POST requests are protected behind an auth wall (take a look at their Authentication docs).

Here's an example of what that could look like in Javascript:

// For Javascript - using the @sanity/client npm package
const allHeadlines = await pullHeadlines(/* ... */);

// Create a single transaction that will handle
// the creation of all headline documents
const transaction = sanityClient.transaction();
for (const headline of allHeadlines) {
  transaction = transaction.create({ title: headline.title, ...headline });
}

transaction
  .commit()
  .then((res) => {
    console.log("All headlines created");
    // Finish the cron job here
  })
  .catch((error) => {
    console.error("Couldn't create the headline documents", error);
    // Maybe retry it here?
  });

Hope that helps, Timur