In this Python tutorial, you’ll write a script to query an API and show desktop notification. Through the course of this tutorial you’ll learn a couple of things,
- How to make an API call
- How to parse the response JSON
- How to play a song
- How to show desktop notification
Source code from this tutorial is available on GitHub.
Indian government is conducting the Covid-19 vaccination drive via Co-WIN. Due to high booking for vaccination slots, the slots are getting filled within minutes before you know that they were even available.
CoWIN is offering public APIs to find appointment availability. In this tutorial, let’s create a Python script to check for vaccine slot availability for a particular pincode and show a notification if it finds one.
Reading the API
Create a file called app.py
. Inside the file create a method called loadCowinData
. You’ll be making use of requests
to make the API call. Start by importing the requests
module.
import requests
The API takes a pincode
and date
as parameter. Here is how the loadCowinData
method.
PIN_CODE = 689586
def loadCowinData():
today = date.today()
fromDate = today.strftime("%d-%m-%Y")
print "#############################################"
print "Checking vaccine availablity for pincode " + str(PIN_CODE) + " on date " + fromDate
API_URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode="+str(PIN_CODE)+"&date="+fromDate
resp = requests.get(API_URL)
return resp.content
Parsing the API Response
Write a method called parseJSON
to parse the API response. Let’s use json.loads
method to parse the JSON. Once you have the parsed JSON, let’s check for the centres
availability. If no centers found return a message else parse the centre data to check for vaccination slots. Here is how it looks:
def parseJSON(res):
'''
utility function to parse API JSON response
'''
root = json.loads(res);
centres = root['centers']
if len(centres) == 0:
return "No centres found !!"
else:
return checkVaccineAvailabilty(centres)
Checking for Slots
Next, let’s write the checkVaccineAvailabilty
to parse the centre data and check if vaccination slots are available or not. Here is how the method looks:
def checkVaccineAvailabilty(centres):
'''
utility function to check for vaccine availablity
'''
for center in centres:
block = center['block_name']
for session in center['sessions']:
if session['min_age_limit'] == 18 and session['available_capacity'] > 0:
print currentDateTime() + "FOUND ONE"
return str(session['available_capacity']) + ' doses of ' + session['vaccine'] + ' available @ ' + block
print currentDateTime() + ' :: None found in ' + block + '. Checking in a minute ...'
print "#############################################"
print "---------------------------------------------"
return 'None'
The above method iterates over the centers
array and checks each of the center for min_age_limit
and available_capacity
. If found it returns the message.
Writing the main method
Now let’s write the main method. From the main method, we first make the API call and load the JSON response. Once you have the JSON we parse it to check if the vaccine is available. If found let’s show a notification and play a song :)
def main():
'''
the main function
'''
response = loadCowinData()
vaccine_available = parseJSON(response)
if vaccine_available != 'None':
playSong()
showNotification(vaccine_available)
time.sleep(40)
Play Song
For playing a song, I’m using the mixer
from pygame
library.
pip install pygame
Here is how the playSong
method looks:
def playSong():
'''
utility function to play song
'''
mixer.init()
mixer.music.load("song.mp3")
mixer.music.set_volume(10)
mixer.music.play()
Show Notification
For showing desktop notification, we are making use of win10toast
python package. Let’s install it using pip.
pip install win10toast
Let’s create a method to show notification, showNotification
:
def showNotification(message):
'''
utility method to show desktop notification
'''
toaster.show_toast("Cowin Notification",
message,
icon_path="custom.ico",
duration=30)
Running the script
Let’s run the script inside to while to keep checking after a 40 second time interval which we have specified inside the main method.
while True:
main()
Here is the complete script from app.py
file.
import requests
import json
from win10toast import ToastNotifier
import datetime
from datetime import date
from pygame import mixer
import time
toaster = ToastNotifier()
PIN_CODE = 689586
def loadCowinData():
today = date.today()
fromDate = today.strftime("%d-%m-%Y")
print "#############################################"
print "Checking vaccine availablity for pincode " + str(PIN_CODE) + " on date " + fromDate
API_URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode="+str(PIN_CODE)+"&date="+fromDate
resp = requests.get(API_URL)
return resp.content
def playSong():
'''
utility function to play song
'''
mixer.init()
mixer.music.load("song.mp3")
mixer.music.set_volume(10)
mixer.music.play()
def parseJSON(res):
'''
utility function to parse API JSON response
'''
root = json.loads(res);
centres = root['centers']
if len(centres) == 0:
return "No centres found !!"
else:
return checkVaccineAvailabilty(centres)
def checkVaccineAvailabilty(centres):
'''
utility function to check for vaccine availablity
'''
for center in centres:
block = center['block_name']
for session in center['sessions']:
if session['min_age_limit'] == 18 and session['available_capacity'] > 0:
print currentDateTime() + "FOUND ONE"
return str(session['available_capacity']) + ' doses of ' + session['vaccine'] + ' available @ ' + block
print currentDateTime() + ' :: None found in ' + block + '. Checking in a minute ...'
print "#############################################"
print "---------------------------------------------"
return 'None'
def currentDateTime():
'''
utility function to get current date and time
'''
return datetime.datetime.now().strftime("%d-%m-%Y, %H:%M:%S")
def showNotification(message):
'''
utility method to show desktop notification
'''
toaster.show_toast("Cowin Notification",
message,
icon_path="custom.ico",
duration=30)
def main():
'''
the main function
'''
response = loadCowinData()
vaccine_available = parseJSON(response)
if vaccine_available != 'None':
playSong()
showNotification(vaccine_available)
time.sleep(40)
#######################################################################
#################### THIS IS WHERE IT ALL STARTS ######################
#######################################################################
while True:
main()
Summary
In this Python tutorial you learnt,
- how to make an API call
- how to parse the response JSON
- how to play a song
- how to show desktop notification
Hope you like this tutorial. Do let us know your thoughts via Twitter.