In this session we will add some code that will obtain the code number for horse racing. All sports have a code number on Betfair, at the moment horse racing is 7 but of course this could change so we need some code to ask Betfair for the code number for horse racing. In the next session we will then be in a position to ask Betfair for all of todays race ID’s for UK racing. We can use these individual race ID’s to obtain specific data on a race, such as horse names, horse ID’s and odds.

Step 1 Make sure you have the python IDLE running with both the MYAPILib.py file and the testlib.py file open.

Step 2 Append the following statement to the testlib.py file. Obviously add your API key that you created in the earlier session. Our program will need to communicate this to Betfair through the calls we will make in this session.

appKey = ‘yourappkeyhere’

Step 3  Add the following line to the testlib.py file

eventTypesResult = myAPILib.getEventTypes (appKey, sessionToken)

In the above we are making a call to a subroutine called getEventTypes in our MyAPILib file. If you have looked in that file you will have noticed that there is not subroutine in there called getEventTypes but dont worry we will add this in due course. The above will assign the eventTypesResult variable a list of codes for all sports, amongst which horse racing will be one of them (probably the number 7).

Step 4 Add the following line to the testlib file

horseRacingEventTypeID = myAPILib.getEventTypeIDForEventTypeName(eventTypesResult, ‘Horse Racing’)

The subroutine getEventTypeIDForEventTypeName expects two parameters to be passed to it. The list of event types and the text describing the eventID that you want passing back, in this case Horse Racing. On completion of this statement the variable horseRacingEventTypeID should contain the ID number for horse racing (currently the number 7). If this gets changed in the future we dont have to worry, our program will still pick up the number for horse racing.

Step 5 Finally add the following line of code

print (‘The number for horse racing is ‘ + horseRacingEventTypeID)

To keep things simple we are at the moment not adding any error checking. The routines in MyAPILib could fail for some reason (eg Betfair down) and in most cases return the number -1 but for simplicity we are ignoring this possibility at the moment.

Step 6 Before we run this code we need to add the missing subroutines to the MyAPILib.py file which you have loaded up at the moment. Copy and paste the following text into the MyAPILib file and save it.

def callAping(jsonrpc_req, appKey, sessionToken):

  headers = {'X-Application': appKey, 'X-Authentication': sessionToken, 'content-type': 'application/json'}
  url = "https://api.betfair.com/exchange/betting/json-rpc/v1 "
  try:
    req = urllib.request.Request(url, jsonrpc_req.encode('utf-8'), headers)
    response = urllib.request.urlopen(req)
    jsonResponse = response.read()
    return jsonResponse.decode('utf-8')
  except urllib.error.URLError as e:
    print (e.reason)
    print ('Oops no service available at ' + str(url))
    exit()
  except urllib.error.HTTPError:
    print ('Oops not a valid operation from the service ' + str(url))
    exit()

############################################################

def getEventTypes(appKey,sessionToken):
  ### returns eventypeids eg racing = 7 or -1 if fails ###

  event_type_req = '{"jsonrpc": "2.0", "method": "SportsAPING/v1.0/listEventTypes", "params": {"filter":{ }}, "id": 1}'

  eventTypesResponse = callAping(event_type_req, appKey, sessionToken)
  eventTypeLoads = json.loads(eventTypesResponse)

  try:
   eventTypeResults = eventTypeLoads['result']
   return eventTypeResults
  except:
   print ('Exception from API-NG' + str(eventTypeLoads['error']))
   return -1

############################################################

def getEventTypeIDForEventTypeName(eventTypesResult, requestedEventTypeName):

  ## returns specific event ID for a given sport or -1 if fails ##

  if(eventTypesResult is not None):
   for event in eventTypesResult:
     eventTypeName = event[‘eventType’][‘name’]
     if( eventTypeName == requestedEventTypeName):
      return event[‘eventType’][‘id’]
  else:
   print ('Oops there is an issue with the input')
   return -1

###########################################################

Step 7 Save and run the testlib file, you should get an ouput line stating that The number for horse racing is 7

Advertisements