In this session we are now ready to start talking to Betfair through the API

Step 1 Double click on your desktop Python IDLE icon to open up the Python development tool

Step 2 Click the file tab followed by new file

Step 3 In the new file window that has just appeared paste in the following code. (NOTE indentation is important in Python, it delimits the scope of an IF or a FOR loop so make sure you paste as is with indentation in place)

#!/usr/bin/env python

#API-NG library

import requests

import urllib
import urllib.request
import urllib.error
import json
import datetime
import sys
import time

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

def loginAPING(userName,passWord):
  ### returns session token or -1 if fails ###

  appKey = “1” # seems to be needed although not a valid appkey

  payload = 'username='+userName+'&password='+passWord
  headers = {'X-Application': appKey,'Content-Type': 'application/x-www-form-urlencoded'}

  resp = requests.post('https://identitysso.betfair.com/api/certlogin ', data=payload, cert=('client-2048.crt', 'client-2048.key'), headers=headers)
  resp_json = resp.json()
  if resp_json['loginStatus'] == 'SUCCESS':

    return resp_json['sessionToken']
  else:
    return -1

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

Step 4 Save the file with the file name myAPILib.py

Step 5 Open another new file and paste in the following text

#!/usr/bin/env python

import myAPILib

sessionToken = myAPILib.loginAPING("yourusername","yourpassword")

print (sessionToken)

In the above substitute your Betfair account name and password

Save the file as testlib.py

Step 6 In the testlib window click the run tab and select run module

Step 7 Output will appear in the shell window and it should print out your session taken for the login just performed by the program. If it failed it will have printed out the number -1

Well done you now have a program that is using a python library to execute commands to the Betfair API. You have successfully logged in and we can in the next session look at how to get hold of race ID’s for the day along with race off times.

Advertisements