Deepak Moonat — June 11, 2021
Advanced Machine Learning Programming Python

This article was published as a part of the Data Science Blogathon

Overview

  • In this article, we will build a notification service for the availability of vaccination slots
  • Learn how to call Public API to get required data
  • How to integrate Twilio SMS service

Prerequisite

  • Python Programming
  • JSON Parsing
  • Basic cloud knowledge(especially GCP, if want to deploy on the cloud)
  • Eager to learn new things

Introduction

As the Covid vaccination drive is ongoing in India, the process is to register and schedule an appointment via a portal(especially for the 18-45 age group).

The catch is we don’t know when the vaccination slots are available, the option is to stock to the screen 24/7 to book a slot(not possible) but now there are few sources that send a notification when slots are available.

So in this article, we will build our own notification service which will notify us via SMS when vaccination slots are available.

Co-WIN

It is the platform through which we need to register and schedule appointments for vaccination. It provides APIs to fetch data on available slots, we will be using public API to get appointment availability based on area pin code and customize it to fetch data for the next few days.

Few points to note while using the API

  • The appointment availability data is cached and may be up to 5 minutes old
  • These APIs are subject to a rate limit of 100 API calls per 5 minutes per IP

What is an API?

API stands for Application Programming Interface, It provides an interface to communicate with different web applications via request-response mechanisms.

The below image will help us understand it clearly.

Notification service vaccination slots 1

                                                                           image source

Request Library

To fetch data from API we will be using the Python Request library. It will allow us to send HTTP requests which will return the response object with the required data.

 Let’s dive deep into this.

  • First, we need to install the library, which we can do via pip
      pip install requests
  • Next, we will import the library into our python script
      import requests

Fetch data

We need age, pin code, and date for which we need to get information about slots availability

URL to fetch the data

URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={}&date={}".format(pincode, given_date)

We will be required header to access the API

header = {'User-Agent':"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"}

Now we will use the request library to call the API, we will be using the GET method as it indicates that we trying to get or retrieve data from a particular resource.

To make a GET request we have to invoke requests.get() method.

result = requests.get(URL, headers=header)

The result object will contain a response from the API, we can check if the request was successful by calling

result.ok

It returns a status code that informs us about the status of the request, if it returns 200 then it is successful and we can then view the data. (for other status code you can refer to this link)

To view the data we will first use the JSON function to format it as the response is in JSON format which will return a dictionary so we can access data by keys.

response_json = result.json()
json Notification service vaccination slots
Notification service vaccination slots 2

                                                  Source: Cowin

Now we have to parse the JSON response.

The hierarchy starts with ‘centers‘ which contains a list of available centers, for each center we will have ‘sessions‘ which will contain information about “min_age_limit“, “available_capacity“.

Filter data based on requirements and sent the notification if all requirements are met

if response_json['centers']:
    for center in response_json['centers']:
         for session in center['sessions']:
             if session['min_age_limit']<=age and session['available_capacity']>0:
                       "Sent Notification"

Twilio Service

First, we need to create a Twilio account, click on the link to register, and start your free trial.

On the home page, you will see your Trial number and Account SID and Auth token, note them as this will be required to access the service.

Now we need to verify the phone number on which we need to receive SMS, for that go to this link. A plus icon will appear click it to add and verify a number. It will open a popup box. Add your phone number and verify either via the ‘Call Me’ or text option.

Once it’s verified we can use the Twilio service to sent SMS.

We will create a python function to sent SMS. To access the Twilio service via python we need to install the Twilio python library

You can install it via pip

pip install twilio

Next copy the required token and SID from the Twilio console and assign to appropriate variables to access the service as follows

# Your Account Sid and Auth Token from twilio.com console
account_sid = '<Account Sid>'
auth_token = '<Auth Token>'
#create a twilio client object 
client = Client(account_sid, auth_token)
#sent sms
client.messages.create(
        from_ = '<twilio no.>',
        body = message,
        to = number
)

Assign Twilio number to ‘from_’ and your verified number to ‘to’ fields. Assign the message to the ‘body’ field. For more context refer to this link.

Sample output:

Notification service vaccination slots sample

 

Desktop Notification

In addition to SMS Notification, we can also add functionality for desktop notification which produces a notification message in form of a pop-up message on the desktop.

For this we will be using the python subprocess module, it comes with python so we don’t have to install it explicitly.

The subprocess module allows you to spawn new processes, connect to their
input/output/error pipes, and obtain their return codes.

It will use a program called ‘notify-send, which is available for Linux. For Mac or Windows, you’ll have to use another program.

Import the module

import subprocess as s

Format of the command

s.call(['notify-send', title, message])

Let’s send a desktop notification for the availability of vaccination slots

s.call( ['notify-send', 'Vaccination', 'Slot Available'] )

Output

send

                                                                           Source: Github

You can even use other python libraries such as ‘notify2‘ for desktop notification. For more information about how to use ‘notify2’, you can refer to this blog.

Deployment

We have built our script now its time to deploy it on the cloud as the script needs to be run 24×7 for checking the availability of vaccination appointments.

We can’t run it on our local system 24×7 as we used to shut down our system and it doesn’t make sense to always keep running our systems.

So for that, we will use the Google cloud platform Compute Engine to deploy our script. You can use any cloud provider of your choice, the steps will be the same.

Compute Engine is the Infrastructure as a Service (IaaS) component of Google Cloud Platform which is built on the global infrastructure that runs Google’s search engine, Gmail, YouTube, and other services. Google Compute Engine enables users to launch virtual machines (VMs) on demand.

You can sign-up on GCP to get free credits which will be helpful for our deployment purpose

Steps for deployment

For deploying our script we will need to launch a Virtual machine/compute engine, on the GCP console search for compute engine and click on create. You have to specify a name and select the default os image(Linux) and for the region, select the Mumbai region as Cowin API is accessible in India only.

Steps for deployment

                                                                Source: Google cloud

Once the instance is ready, click on ssh and a terminal prompt will open. Now create a new python file and add your script to it.

                                                               Source: Google cloud

We will run the script in the background, for that we will use the ‘nohup’ functionality of Linux.

nohub python3 -u app.py &
cloud

                                                Source: Google cloud

Now our app will run in the background, we can close the ssh terminal. We don’t have to stop the instance as we need to run the script 24×7, don’t worry it won’t incur any cost as it will be covered from free credits.

Now you can even shut your local system and wait for the SMS and once you get SMS, book your appointment and get vaccinated.

Note: The desktop notification won’t work on the cloud

Github

For Complete code jump to the GitHub repository

Also added an automation script to partially automate the vaccination appointment scheduling process.

References

https://apisetu.gov.in/public/api/cowin/cowin-public-v2

https://www.twilio.com/docs/sms

https://realpython.com/python-requests/

https://docs.python.org/3/library/subprocess.html

https://en.wikipedia.org/wiki/Google_Compute_Engine

What Is Nohup and How Do You Use It?

https://stackoverflow.com/questions/230751/how-can-i-flush-the-output-of-the-print-function

The media shown in this article on Notification service for vaccination slots are not owned by Analytics Vidhya and are used at the Author’s discretion.

Leave a Reply Your email address will not be published. Required fields are marked *