Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
In Development Last updated: September 12, 2023
Share on:
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Users try to access your site, you know what happened? It doesn’t show up. There are some errors that you didn’t figure out before. Users get frustrated and leave your site.  So, you lost some loyal users with it.

How to solve this problem? How do you get to know about the site down before your users find it?

There are two possible ways:

If you don’t mind spending a few $, you can go for a monitoring solution like StatusCake or others mentioned here.

However, if you are a developer or not ready to spend monthly, you can take advantage of Geekflare API – Is Site Up?

Is Site Up? API checks whether a site is up or down from different locations.

Let me show you Python code that notifies you immediately when your site goes down via Gmail.

Let’s start with exploring the Is Site Up? API.

Is Site Up? API

Before checking the API, we need to install a package called requests to work with APIs in Python. But, it’s not necessary to use only Python. You can use your preferred language. But make sure you set up the required things to make an API request.

So, for those who are using Python install the requests package using the command pip install requests

Complete the setup for other languages (if you choose other than Python) and continue to the next steps.

Now, go to the Geekflare API page.

Geekflare-API-page

You can find different types of APIs, including Is Site Up? API, which we are interested in for this article. To use the Geekflare APIs, we need an API Key that we can get by signing up for the Geekflare API.

Click on the Sign Up Free button on the header and create an account in Geeflare API.

Create Geekflare API Account

Once you create your account, you will be redirected to the dashboard of Geekflare API. In the dashboard, you will find the API key and other details like your email, active plan, etc..,

Geekflare API Dashboard

You can copy the API key. Now, let’s check the documentation of Is Site Up API. Click on your profile icon and documentation.

Geekflare API Documentation

It will redirect you to the Geeflare API documentation.

You will find the Site status (Is Site Up?) API documentation here. Go to it.

You will get the usage of API on the right side. Select Python from the Code Snippets section on the right side. Choose your preferred language if you are not using Python.

You will get the code to call the Is Site Up? API. Let’s modify it a bit which helps us to add more code later easily. Have a look at the modified code in Python.

import requests
import json

API_URL = "https://api.geekflare.com/up" 

def make_api_request(): 
    headers = { 
        'x-api-key': 'YOUR-API-KEY',
        'Content-Type': 'application/json'
    }
    payload = json.dumps({"url": "https://geekflare.com"})
    response = requests.request("POST", API_URL, data=payload, headers=headers) 
    return response.json()
    
if __name__ == '__main__': 
    data = make_api_request() 
    print(data)

Replace the YOUR-API-KEY with your own API key from the Geekflare API dashboard. It will be different for every user. Copy the API key from the dashboard and add it to the above code

Multi-Location

The above code checks whether the site is up or not from a single location (New York, USA). But, we can test it from a different location with proxyCountry in the request body.

Other available locations are England (London) and Singapore. We can pass the proxyCountry data along with the site URL as follows.

{
    "proxyCountry": "uk",
    "url": "geekflare.com"
}

You may pass any location that you prefer from the available locations here.

We have completed the code to make an API request that fetches the data on whether a site is up or not. Now, it’s time to write some more code that sends mail when the site is down. Let’s go.

Receiving Email When the Site is Down

You can find the detailed tutorial on how to send emails through Gmail in Python Or use the following code, which uses a package called yagmail specially designed to send emails from Gmail.

Before sending a mail through your Gmail account, we have to turn on the Allow less secure apps options. You can turn it on here.

Let’s see the code.

def send_mail():
    gmail = yagmail.SMTP("gmail", "password")

    receiver = "receiver@domain.com"
    subject = "Testing Subject"
    body = "This is a testing mail"

    gmail.send(
        to=receiver,
        subject=subject,
        contents=body,
    )

You can find the complete tutorial of yagmail here.

Now, we have code for API requests and sending mail. Our next step is to invoke the send_mail whenever we receive bad status from the API request.

So, how do we know that our site is down or up? When we request the Is Site Up? API, it will respond with some data as follows.

{
  "timestamp": 1671545622213,
  "apiStatus": "success",
  "apiCode": 200,
  "message": "Site is up.",
  "meta": {
    "url": "https://geekflare.com",
    "proxyCountry": "United Kingdom",
    "followRedirect": false,
    "test": {
      "id": "riah3dvi04ngaa1jw1b75smiibrus2a7"
    }
  },
  "data": {
    "statusCode": 200,
    "reasonPhrase": "OK"
  }
}

You will find a key called message in it. The value of the key message tells us whether the site is up or down. So, can be two types of messages as follows.

  • Site is up.
  • Site is down

I think you got it now. So, we will send the mail when we receive the message “Site is down.”. The final code will look as follows.

import requests
import json
import yagmail

API_URL = "https://api.geekflare.com/up"


def make_api_request():
    headers = {
        'x-api-key': 'YOUR-API-KEY',
        'Content-Type': 'application/json'
    }
    payload = json.dumps({
        "url": "https://geekflare.com",
        "followRedirect": True,
        "proxyCountry": "uk"
    })
    response = requests.request("POST", API_URL, data=payload, headers=headers)
    return response.json()


def send_mail(content):
    gmail = yagmail.SMTP("gmail", "password")
    receiver = "email@domain.com"
    subject = "Your Site is Down"
    gmail.send(
        to=receiver,
        subject=subject,
        contents=content,
    )


if __name__ == '__main__':
    data = make_api_request()
    message = data['message']

    ## seding the mail
    if message == 'Site is down':
        ## extracting the location and error
        location = data['meta']['proxyCountry']
        mail_content = "Your site is down due to unexpected error. See the useful data to resolve errors below.nn"
        if location:
            mail_content += f"{location}"
        mail_content += f"{data['data']['reasonPhrase']}nn"
        mail_content += "Check the error and resolve it as soon as possible."
        send_mail(mail_content)

You may update the content of the mail as you prefer. We have completed sending mail whenever our site is down.

But there is still a problem.

We have to execute our code to check whether our site is up or down. How often do we run it? Yeah, it depends on your preference. Let’s say we have to check it every hour.

We can open a terminal or command line and execute our code every hour. But it’s a repetitive process and boring one. And sometimes we can forget to check it. So, we need to execute the code automatically every hour.

Here we can use the cron to execute our code every hour automatically. Let’s see how to set it up.

Cron Setup

Let’s see the steps to set up the cron on a UNIX-based operating system.

  • Open terminal.
  • Run the command crontab -e which opens the crontab file in the terminal.
  • Press the key i to enter the INSERT mode.
  • Now, add the cron pattern, Python directory, and our code file directory. You see the example below.

0 * * * * /usr/bin/python3 /home/sample.py

Cron
Cron

We have set the pattern to execute the code every hour. But you may need to set it to every minute based on the requirement. So, you can use the Crontab Guru or other cron tools to generate the cron pattern for the schedule.

That’s it. We have completed the setup to get notified when the site is down.

Conclusion

Use the cron to schedule the script to run periodically on your cloud server that runs 24/7 to get notified through email when the site is down. Automation saves a lot of time and works for us. So, make use of it as we did in this article.

Happy Monitoring 🙂

  • Hafeezul Kareem Shaik
    Author
Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.
    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder