Mindbody Book an Appointment Using Python

mindbody book an appointment using python

Hi friend now we are going to show how to book a MindBody Appointment using Python but before we proceed toward booking we need to gather some basic information which are required to book an Appointment.

In this tutorial we explain the whole process step by step with complete code.

mindbody book an appointment using python

  1. Staff Id
  2. Session Type Id
  3. Start Date Time
  4. Location Id
  5. Client Id

Step 1 : Get Staff Id, Session Type Id, Start Date Time, Location Id

In order to obtain Staff Id, Session Type Id, Start Date Time, Location Id and basic setups regarding to API Credential we have to follow the steps as ascribed in our last tutorial at http://www.mindbodydeveloper.com/mindbody-integration-python-example

Step 2 : Get Client Id

Create a file ClientService.py in Mindbody Folder and copy the code given below

from suds.client import Client
import BasicRequestHelper
from datetime import datetime
import json

USER_NAME = "XXXXXXX"             #### Replace  “XXXXX”  with your own User Name
USER_PASSWORD = "XXXXX"           #### Repalce  “XXXXX” with your own USER_PASSWORD

class ClientService:
 
  serviceName = "Client"
  urlService  ="https://api.mindbodyonline.com/0_5/" + serviceName + "Service.asmx?wsdl"
  service = Client(urlService, location="https://api.mindbodyonline.com/0_5/ClientService.asmx")

  def CreateBasicRequest(self, requestName):
    return BasicRequestHelper.CreateBasicRequest(self.service, requestName)

  def ValidateLogin(self, username, password):
    request = self.CreateBasicRequest("ValidateLogin")

    request.Username = username
    request.Password = password

    result = self.service.service.ValidateLogin(request)
    print str(result)

ClientService().ValidateLogin(USER_NAME,USER_PASSWORD)

Step 3: Run the above file moving to the directory where the file ClientService.py resides by hitting the command “Python ClientService.py” in command prompt. You will get result having lots of stuff in which client Id can be found moving in the client section.
Step 4: Create a file BookAppointment.py in Mindbody Folder and copy the code given below

from datetime import datetime
from suds.client import Client
import BasicRequestHelper
import os
import json
import re

class AppointmentService():
  def Book_Slot(self):
    LocationID      = raw_input("Please Enter Location ID :")
    StaffID         = raw_input("Please Enter Staff ID :")
    SessionTypeId   = raw_input("Please Enter SessionType ID :")
    StartDateTime   = raw_input("Please Enter StartDateTime as this Example "+"2016-10-25T14:30:00 :")
    GetClientID     = raw_input("Please Enter Client ID :")
    Location        = {"ID":LocationID}
    Staff           = {"ID":StaffID}
    SessionType     = {"ID":SessionTypeId}
    Client          = {"ID":GetClientID}
    appointments    = {"StartDateTime":StartDateTime,"Location":Location,"Staff":Staff,
                      "SessionType":SessionType,"Client":Client}
    result          = BookAppointmentMethods().AddOrUpdateAppointments(appointments,"AddNew")
    try:
        status      = result.Appointments.Appointment[0].Action
        if(status=='Added'):
            print "\nAppointment is Fixed successfully"
            appointmentID = result.Appointments.Appointment[0].ID
            SDate         = result.Appointments.Appointment[0].StartDateTime
            EDate         = result.Appointments.Appointment[0].EndDateTime
            print "\nAppointment Id  |      StartDateTime     |     EndDateTime\n",appointmentID,"          "
            ,SDate,"  ",EDate
        elif(status == "Failed"):
            errorCode   = int(result.Appointments.Appointment[0].ErrorCode)
            print "\n",result.Appointments.Appointment[0].Messages.string[0],"\n","Error Code :",errorCode
        else:
            print "Try Again"

    except:
        print "\nInternal Error Please Try Agian" 

class BookAppointmentMethods():
  serviceName = "Appointment"
  urlService  = "https://api.mindbodyonline.com/0_5/" + serviceName + "Service.asmx?wsdl"
  service = Client(urlService)

  def CreateBasicRequest(self, requestName):
      return BasicRequestHelper.CreateBasicRequest(self.service, requestName)

  def AddOrUpdateAppointments(self,appointments, updateAction,test=False,sendEmail=False,applyPayment=True):
      request = self.CreateBasicRequest("AddOrUpdateAppointments")

      request.UpdateAction = updateAction
      request.Test = test
      request.SendEmail = sendEmail
      request.ApplyPayment = applyPayment        
      request.Appointments = BasicRequestHelper.FillArrayType(self.service, [appointments], "Appointment", "Appointment")

      return self.service.service.AddOrUpdateAppointments(request)
    
AppointmentService().Book_Slot()

Step 5: Run the above code moving to the directory where the file BookAppointment.py resides by hitting the command “Python BookAppointment.py” in command prompt. You will be asked to enter Location ID, Staff ID, Session Type ID, Start Date Time, and finally Client ID. After providing the required details you will get result containing the Appointment ID

Detailed Explanation of BookAppointment.py

    LocationID       = raw_input("Please Enter Location ID :")
    StaffID          = raw_input("Please Enter Staff ID :")
    SessionTypeId    = raw_input("Please Enter SessionType ID :")
    StartDateTime    = raw_input("Please Enter StartDateTime as this Example "+"2016-10-25T14:30:00 :")
    GetClientID      = raw_input("Please Enter Client ID :")

These above line takes input from user

    Location           = {"ID":LocationID}
    Staff              = {"ID":StaffID}
    SessionType        = {"ID":SessionTypeId}
    Client             = {"ID":GetClientID}
    appointments       = {"StartDateTime":StartDateTime,"Location":Location,"Staff":Staff,
                         "SessionType":SessionType,"Client":Client}

After getting the input from user these are formatted as required by”MindBody“and are to be sent in single parameter named as appointments

result          = BookAppointmentMethods().AddOrUpdateAppointments(appointments,"AddNew")

The above line call AddOrUpdateAppointments Method of BookAppointmentMethods class these contains two parameter. First Parameter appointments contains the information like Location ID, Staff ID, Session Type ID, Start Date Time and the second parameter is Action and the available actions are:

AddNew : Adds the new appointment.
Update : Updates the appointment for the specified ID/Cancel Appointment.

     try:
        status      = result.Appointments.Appointment[0].Action
        if(status=='Added'):
            print "\nAppointment is Fixed successfully"
            appointmentID = result.Appointments.Appointment[0].ID
            SDate         = result.Appointments.Appointment[0].StartDateTime
            EDate         = result.Appointments.Appointment[0].EndDateTime
            print "\nAppointment Id  |      StartDateTime     |     EndDateTime\n",appointmentID,"          ",SDate,"  ",EDate
        elif(status == "Failed"):
            errorCode   = int(result.Appointments.Appointment[0].ErrorCode)
            print "\n",result.Appointments.Appointment[0].Messages.string[0],"\n","Error Code :",errorCode
        else:
            print "Try Again"

    except:
        print "\nInternal Error Please Try Agian"

The above codes are used to handle the result. If booking proceeded toward success then the status will be “Added” if it fails then the status will be “Failed”, If any other error occurs then it will prompt try Again.

  serviceName = "Appointment"
  urlService  = "https://api.mindbodyonline.com/0_5/" + serviceName + "Service.asmx?wsdl"
  service = Client(urlService)

  def CreateBasicRequest(self, requestName):
      return BasicRequestHelper.CreateBasicRequest(self.service, requestName)

We prepare Appointment Service of Mind Body in above code and create request as required by Mind Body API.

def AddOrUpdateAppointments(self,appointments, updateAction,test=False,sendEmail=False,applyPayment=True):
      request = self.CreateBasicRequest("AddOrUpdateAppointments")

      request.UpdateAction = updateAction
      request.Test = test
      request.SendEmail = sendEmail
      request.ApplyPayment = applyPayment        
      request.Appointments = BasicRequestHelper.FillArrayType(self.service, [appointments], "Appointment", "Appointment")

      return self.service.service.AddOrUpdateAppointments(request)

In the above code AddOrUpdateAppointments Method contains 5 parameters all these are ascribed below.
Appointments : Contains basic details required for booking as explained in the above.
UpdateAction : It can be AddNew or Update action according to need.
Test : Default it is false. When test mode is enabled, the method will be validated, but no Appointment data will be added or updated.
SendEmail : Whether to send client an email for cancelations (default false).
ApplyPayment : Whether to apply a payment to the appointment (default false).

Finally this Method will return result containing either success with Appointment ID or failure. If you want our team to do it for you or any work related to MindBody please email us at rajneesh@mindbodydeveloper.com

top

GET A FREE
MindBody Consulation

Let Experts Help You!
This Offer Is Limited! Don't Miss...
Fill out this form for a FREE, Immediate, Case Evaluation
GET HELP NOW