Python

This tutorial provides you with a step-by-step walkthrough of how to build a ‘Doctor’s Appointment App’ to send appointment reminders via SMS using Live Link 365.

This is not a production-ready application. Please take your time to enhance it for production so that it meets your specific business requirements.

The main panel on the right highlights the right piece of code for each step.

Steps

Code

keyboard_arrow_down
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# _Step_1
class Doctor:
    def __init__(self, id, name, specialization):
        self.doctorID = id
        self.doctorName = name
        self.specialization = specialization

# _Step_2
class Patient:
    def __init__(self, id, name):
        self.patientID = id
        self.patientName = name

# _Step_3
class Specialization:
    def __init__(self, id, name):
        self.specializationID = id
        self.specializationName = name

# _Step_4
class Appointment:
    def __init__(self, doctor, patient, appointmentDate):
        self.doctor = doctor
        self.patient = patient
        self.date = appointmentDate
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import base64
import json
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode

class MessageHandler():
    def __init__(self, base_url, app_key, app_secret):
        self.base_url = base_url
        self.app_key = app_key
        self.app_secret = app_secret

    # _Step_7
    def getAccessToken(self, key, secret):
        """
        This Function is used to retrieve oAuth2 access_tokens.
        This conforms to oAuth2 Spec client_credentials grant_type.
        This Function is not doing any validation regarding expiration of tokens.
        """
        token_url = self.base_url + '/oauth/token'
        credentials = "%s:%s" % (key, secret)
        encode_credential = base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")
        header_params = {
            "Authorization": ("Basic %s" % encode_credential),
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json"
        }
        param = {
            'grant_type': 'client_credentials'
        }

        token_data = urlencode(param)
        token_request = Request(url=token_url, headers=header_params, data=token_data.encode('ascii'))

        try:
            token_response = urlopen(token_request).read()
        except HTTPError as error:
            print ("Error " + error.reason)
        else:
            return json.loads(token_response.decode('UTF-8'))['access_token']

    # _Step_8
    def sendSMS(self, sms, number):
        token_url = self.base_url + '/v2/sms'
        header_params = {
            "Content-Type": "application/json",
            "Authorization": ("Bearer %s" % self.getAccessToken(self.app_key, self.app_secret))
        } 

        param = { 
            "message": sms,
            "origin": "", 
            "destination": number #Phone numbers have to be in E.164 format.
        }
        token_data = json.dumps(param).encode('ascii')
        token_request = Request(url=token_url, headers=header_params, data=token_data)
        # Exception handle example
        try:
            token_response = urlopen(token_request)
            print (token_response)
        except HTTPError as e:
            return 'HTTP Request error with status %i %s' % (e.code, e.reason)
        except URLError as e:
            return 'URL Request error with status %i %s' % (e.code, e.reason)
        else:
            return 'SMS Sent Successfully' #with OrderId:' #% json.loads(sms_response.read().decode('UTF-8'))['orderId']
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from sendSMS import MessageHandler
from DoctorsAppointment import *
from dateutil.parser import parse
import configparser
import datetime
import json

# _Step_6
if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read('../resources/config.ini')

    base_url = config['API']['base_url']
    app_key = config['API']['app_key']
    app_secret = config['API']['app_secret']

    pId = 0
    dId = 0
    sId = 0
    doctor = Doctor(dId + 1, config['APP']["doctor_name"], Specialization(sId + 1, config['APP']["specialization"]))
    patient = Patient(pId + 1, config['APP']["patient_name"], config['APP']["patient_number"])
    appointment = Appointment(doctor, patient, parse(config['APP']["date"]))

    patientName = appointment.patient.patientName
    doctorName = appointment.doctor.doctorName
    specializationName = appointment.doctor.specialization.specializationName
    appointmentDate = appointment.date
    strAppointmentDate = appointmentDate.strftime('%b %d, %Y')

    # _Step_9
    appointmentMessage = "Mr./Mrs " + patientName + ", you have an appointment with " + doctorName + " (" + specializationName + ")" + " scheduled on " + strAppointmentDate
    destinationNumber = appointment.patient.number #Phone numbers have to be in E.164 format.
    messageHandler = MessageHandler(base_url, app_key, app_secret)
    messageHandler.sendSMS(appointmentMessage, destinationNumber)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
[API]
; _Step_5
; Insert your api url here
base_url=https://livelink.sapdigitalinterconnect.com/api
;Insert your generated app key here
app_key=appKey
;Insert your generated app secret here
app_secret=appSecret

[APP]
patient_name=John Doe
patient_number=number ;Phone numbers have to be in E.164 format.
doctor_name=Dr. Donald
specialization=Diabetologist
date=2017-04-11T04:00