Help understanding why I'm receiving an error?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • HappyChappy
    Junior Member
    • Feb 2024
    • 5

    #1

    Help understanding why I'm receiving an error?

    Hello, when running the following code -

    def fetch_football_data(session_token):
    url = "https://api.betfair.com/exchange/betting/rest/v1.0/listMarketCatalogue/"
    headers = {
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {session_token}'
    }
    data = {
    "filter": {
    "eventTypeIds": [1], # 1 corresponds to Football
    "marketTypeCodes": ["MATCH_ODDS"], # Example: Only fetch Match Odds markets
    },
    "marketProjection": ["EVENT", "COMPETITION", "RUNNER_DESCRIPTION", "MARKET_START_TIME"],
    "maxResults": 10
    }
    response = requests.post(url, json=data, headers=headers)
    if response.status_code == 200:
    return response.json()
    else:
    print("Failed to fetch football data from Betfair API.")
    print("Response status code:", response.status_code)
    print("Response content:", response.content)
    return None​

    I am receiving this error -

    runcell(0, 'C:/Users/cdye/OneDrive/Desktop/ArbBetfairScripts/API_get_data_newest.py')
    Failed to fetch football data from Betfair API.
    Response status code: 400
    Response content: b'{"faultcode":"Client","faultstring":"ANGX-0004","detail":{"APINGException":{"requestUUID":"i e1-ang06a-prd-01290905-0069ec111b","errorCode":"NO_APP_KEY","errorDetails ":""},"exceptionname":"APINGException"}}'
    Failed to fetch football data from Betfair API.

    Is anyone able to advise as to why this is happening?

    Thanks​
  • jabe
    Senior Member
    • Dec 2014
    • 705

    #2
    Apart from passing the Content Type for each call, you have to specify other headers, particularly these two

    request.Headers.Add("X-Application: " & appKey)
    request.Headers.Add("X-Authentication: " & ssoid)​

    I'm afraid I don't know what the Python code is for them.

    Comment

    • HappyChappy
      Junior Member
      • Feb 2024
      • 5

      #3
      Thanks for replying, I have these

      request.Headers.Add("X-Application: " & appKey)
      request.Headers.Add("X-Authentication: " & ssoid)​

      in my code now but am still receiving an error do you know why it would be, my whole code is below with the error message -

      ​# -*- coding: utf-8 -*-
      """

      """
      import requests
      import psycopg2
      import logging


      # Enable DEBUG level logging for requests
      logging.basicConfig(level=logging.DEBUG)

      def fetch_football_data(session_token, app_key):
      url = "https://api.betfair.com/exchange/betting/rest/v1.0/listMarketCatalogue/"
      headers = {
      'Content-Type': 'application/json',
      'Authorization': f'Bearer {session_token}',
      'X-Application': app_key,
      'X-Authentication': session_token
      }
      data = {
      "filter": {
      "eventTypeIds": [1], # 1 corresponds to Football
      "marketTypeCodes": ["MATCH_ODDS"], # Example: Only fetch Match Odds markets
      },
      "marketProjection": ["EVENT", "COMPETITION", "RUNNER_DESCRIPTION", "MARKET_START_TIME", "MARKET_ID", "MARKET_NAME"],
      "sort": "RANK",
      "maxResults": 10,
      "locale": "en"
      }
      response = requests.post(url, json=data, headers=headers)
      if response.status_code == 200:
      return response.json()
      else:
      print("Failed to fetch football data from Betfair API.")
      print("Request URL:", url)
      print("Request Headers:", headers)
      print("Request Data:", data)
      print("Response status code:", response.status_code)
      print("Response text:", response.text)
      return None

      def insert_football_data_into_postgres(football_data):
      conn = psycopg2.connect(
      dbname='Betfair',
      user='postgres',
      host='localhost',
      password='xxxxxxxx'
      )
      cur = conn.cursor()

      for market in football_data:
      event = market.get('event', {}).get('name', '')
      competition = market.get('competition', {}).get('name', '')
      market_start_time = market.get('marketStartTime', '')

      for runner in market.get('runners', []):
      selection_id = runner.get('selectionId', '')
      selection_name = runner.get('runnerName', '')
      odds = runner.get('lastPriceTraded', '')

      # Insert data into the PostgreSQL table
      cur.execute("""
      INSERT INTO football_matches_staging
      (event, competition, market_start_time, selection_id, selection_name, odds)
      VALUES (%s, %s, %s, %s, %s, %s)
      """, (event, competition, market_start_time, selection_id, selection_name, odds))

      conn.commit()
      cur.close()
      conn.close()

      # Authentication to get session token
      payload = 'username=xxxxxxx@gmail.com&password=xxxxxxxx'
      app_key = 'nIxxxxxohvJ'
      headers = {'Content-Type': 'application/x-www-form-urlencoded'}

      resp = requests.post('https://identitysso-cert.betfair.com/api/certlogin', data=payload, cert=('BA.crt', 'NEW_KEY.PEM'), headers=headers)

      if resp.status_code == 200:
      resp_json = resp.json()
      session_token = resp_json['sessionToken'] # Obtain session token

      # Fetch football data from Betfair API
      football_data = fetch_football_data(session_token, app_key)

      # Insert football data into PostgreSQL table
      if football_data:
      insert_football_data_into_postgres(football_data)
      print("Football data inserted into PostgreSQL table successfully.")
      else:
      print("Failed to fetch football data from Betfair API.")
      else:
      print("Request failed.")


      runcell(0, 'C:/Users/xxx/OneDrive/Desktop/BetfairScripts/untitled8.py')
      DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): identitysso-cert.betfair.com:443
      DEBUG:urllib3.connectionpool:https://identitysso-cert.betfair.com:443 "POST /api/certlogin HTTP/1.1" 400 964
      Request failed.​​

      Comment

      • HappyChappy
        Junior Member
        • Feb 2024
        • 5

        #4
        This works when on it's own if it helps -

        import requests

        openssl x509 -x509toreq -in certificate.crt -out CSR.csr -signkey privateKey.key


        payload = 'username=xxxx@gmail.com&password=xxxxxxx'
        headers = {'X-Application': 'nIxxxxvJ', 'Content-Type': 'application/x-www-form-urlencoded'}

        resp = requests.post('https://identitysso-cert.betfair.com/api/certlogin', data=payload, cert=('BA.crt', 'NEW_KEY.PEM'), headers=headers)

        if resp.status_code == 200:
        resp_json = resp.json()
        print (resp_json['loginStatus'])
        print (resp_json['sessionToken'])
        else:
        print ("Request failed.")​
        Last edited by HappyChappy; 20-03-2024, 01:27 PM.

        Comment

        • jabe
          Senior Member
          • Dec 2014
          • 705

          #5
          I hope that's a fake password. I'm not going to be able to take a good look for the rest of Wednesday, I'm afraid, but I'll look when I can. Someone else might comment in the meantime.

          Comment

          • jabe
            Senior Member
            • Dec 2014
            • 705

            #6
            I've been able to get back briefly. Something I've noticed is that the JSON for calls in my program includes a line that all calls go through that looks like this:

            Dim postData As String = "{""jsonrpc"": ""2.0"", ""method"": ""SportsAPING/v1.0/" & method & """, ""params"": {" & params & "},""id"": 1}"

            which suggests that the JSON string needs more than you're putting into yours.

            Could I suggest while trying to get a successful response from your request, you ask for something far simpler and where parameters are practically unnecessary? Perhaps one of the list calls brings back all instances of whatever and parameters aren't needed.

            Comment

            • HappyChappy
              Junior Member
              • Feb 2024
              • 5

              #7
              Hey, thank you for your response, yes I think I am just missing some parameters, trying to get something simpler first is a great suggestion I will try that

              Comment

              Working...
              X