DEV Community

Cover image for How to check if Cloudflare API working before making calls
Pavel
Pavel

Posted on

How to check if Cloudflare API working before making calls

Today Cloudflare’s API and dashboard became unavailable for more than an hour already. Then things got worse as Cloudflare’s own node.js client for API do not handle such case properly.

Luckily cloudflarestatus.com is powered by Statuspage.io and has its own API.

So I end up writing a small piece of code that checks if Cloudflare API is up and working correctly.

The endpoint we are interested in is located at https://yh6f0r4529hb.statuspage.io/api/v2/summary.json.

After inspecting it:

$ curl -L https://yh6f0r4529hb.statuspage.io/api/v2/summary.json
Enter fullscreen mode Exit fullscreen mode

We may find required piece of data that contains status of Cloudflare API component:

{
  id: 'g4tb35rs9yw7',
  name: 'Cloudflare API',
  status: 'major_outage',
  created_at: '2014-10-09T03:32:07.158Z',
  updated_at: '2020-04-15T17:39:38.257Z',
  position: 5,
  description: "Cloudflare's API where customers can read from and write to their configurations at https://api.cloudflare.com",
  showcase: false,
  group_id: '1km35smx8p41',
  page_id: 'yh6f0r4529hb',
  group: false,
  only_show_if_degraded: false
}
Enter fullscreen mode Exit fullscreen mode

So we end up with the following code:

const fetch = require('isomorphic-unfetch');

const CLOUDFLARE_STATUS_ENDPOINT =
  'https://yh6f0r4529hb.statuspage.io/api/v2/summary.json';

const isApiWorking = async () => {
  let isWorking = false;
  await fetch(CLOUDFLARE_STATUS_ENDPOINT)
    .then((r) => r.json())
    .then((data) => {
      if (data.hasOwnProperty('components') && data.components.length > 0) {
        data.components.forEach((c) => {
          //   id: 'g4tb35rs9yw7',
          //   name: 'Cloudflare API',
          if (c.id === 'g4tb35rs9yw7' && c.status === 'operational') {
            isWorking = true;
          }
        });
      }
    })
    .catch((e) => {
      console.error(e);
    });
  return isWorking;
};
Enter fullscreen mode Exit fullscreen mode

And the usage may be:

isApiWorking().then((res) => {
  if (res) {
    // Do something with api
    console.log(res);
  } else {
    // Cloudflare API seems to be broken
    // Do something else
    console.error(res);
  }
});
Enter fullscreen mode Exit fullscreen mode

Hope this will be a help for somebody in the situation like me.

Top comments (0)