dcsimg
Results 1 to 7 of 7

Thread: [RESOLVED] Convert this Python piece of code to VB.NET?

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Sep 2013
    Posts
    28

    Resolved [RESOLVED] Convert this Python piece of code to VB.NET?

    This is an http request with custom headers in Python.

    Code:
    import requests
    import json
     
    endpoint = "https://api.betfair.com/exchange/betting/rest/v1.0/"
     
    header = { 'X-Application' : 'APP_KEY_HERE', 'X-Authentication' : 'SESSION_TOKEN_HERE' ,'content-type' : 'application/json' }
     
    json_req='{"filter":{ }}'
     
    url = endpoint + "listEventTypes/"
     
    response = requests.post(url, data=json_req, headers=header)
     
     
    print json.dumps(json.loads(response.text), indent=3)

    I want to send http request using same headers. I have done most things but couldn't figure out how to include filter. Here is my code in VB.NET.

    Code:
                Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create("https://api.betfair.com/exchange/betting/rest/v1/en/navigation/menu.json"), HttpWebRequest)
    
                myHttpWebRequest.Method = "GET"
                myHttpWebRequest.KeepAlive = True
                myHttpWebRequest.Accept = "application/json"
                myHttpWebRequest.Headers("X-Application") = "WcnmFApc9e8M5OA0"
                myHttpWebRequest.Headers("X-Authentication") = "GLksOhuoCPQTD6RK0TrlY/R+uKf4Zx9jOa5BUsuBwbg="
                myHttpWebRequest.Headers("Accept-Encoding") = "gzip,deflate"
    
                Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse, HttpWebResponse)
                Using responseStream = New GZipStream(myHttpWebResponse.GetResponseStream(), CompressionMode.Decompress)
                    Using reader As New StreamReader(responseStream, Encoding.Default)
                        RichTextBox1.Text = reader.ReadToEnd()
                    End Using
                End Using

  2. #2
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,162

    Re: Convert this Python piece of code to VB.NET?

    It's a standard POST request that is sending a JSON string to an API endpoint.

    The Betfair documentation here states
    You can POST a request to the API at:

    https://api.betfair.com/exchange/betting/rest/v1.0/<operation name>. So, to call the listEventTypes method, you would POST to: https://api.betfair.com/exchange/bet...istEventTypes/

    The POST data contains the request parameters. For listEventTypes, the only required parameter is a filter to select markets. You can pass an empty filter to select all markets, in which case listEventTypes returns the EventTypes associated with all available markets.

    Your current code is sending a request to a different endpoint using the GET method.

    You'll need to change the URL to the correct endpoint address (https://api.betfair.com/exchange/bet...istEventTypes/) and your myHttpWebRequest.Method to "POST".

    Then you have to send the JSON string '{ "filter" : { } }' to the server as part of the HttpWebRequest .
    To do this, you would typically
    • Convert the string to a Byte Array using a suitable Text Encoding.
    • Set the request's ContentLength Header to the array length.
    • Set the request's ContentType Header to "application/json".
    • Write the contents of the Byte Array to the HttpWebRequest's request stream.



    So your code should be something like:
    Code:
    Dim url As String = "https://api.betfair.com/exchange/betting/rest/v1.0/listEventTypes/"
    
    ServicePointManager.Expect100Continue = False
    Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
    
    myHttpWebRequest.Method = "POST"
    myHttpWebRequest.KeepAlive = True
    myHttpWebRequest.Accept = "application/json"
    myHttpWebRequest.Headers("X-Application") = "WcnmFApc9e8M5OA0"
    myHttpWebRequest.Headers("X-Authentication") = "GLksOhuoCPQTD6RK0TrlY/R+uKf4Zx9jOa5BUsuBwbg=n"
    myHttpWebRequest.Headers("Accept-Encoding") = "gzip,deflate"
    
    Dim postData As String = "{ ""filter"" : { } }"
    Dim dataBytes() As Byte = Encoding.UTF8.GetBytes(postData)
    
    myHttpWebRequest.ContentLength = dataBytes.Length
    myHttpWebRequest.ContentType = "application/json"
    
    Using reqStream As Stream = myHttpWebRequest.GetRequestStream()
        reqStream.Write(dataBytes, 0, dataBytes.Length)
    End Using
    
    Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse, HttpWebResponse)
    Using responseStream = New GZipStream(myHttpWebResponse.GetResponseStream(), CompressionMode.Decompress)
        Using reader As New StreamReader(responseStream, Encoding.Default)
            RichTextBox1.Text = reader.ReadToEnd()
        End Using
    End Using

    Note that the Betfair documentation also states:
    Expect- 100 Continue Header

    Please note: When using .NET you set the "Expect -100Continue" property to false. This property sits in the ServicePointManager class
    and I've included the necessary statement in the code above (ServicePointManager.Expect100Continue = False)


    Also note that the example code is passing an empty filter, so you'll get back all the available EventTypes in the response.


    One final point: why are you using Encoding.Default? Encoding.Default is almost always the wrong choice of encoding because it varies from PC to PC, based on user preference settings. Did UTF8 not work properly for you?

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Sep 2013
    Posts
    28

    Re: Convert this Python piece of code to VB.NET?

    Actually i have found code on internet and with help of you and some others, changed it a bit. Didn't know what is difference between Encoding.Default and Encoding.UTF8 though i changed it to UTF8 as you said and your above code worked perfectly. I got response something like below.

    Code:
    [{"eventType":{"id":"1","name":"Soccer"},"marketCount":14863},{"eventType":{"id":"2","name":"Tennis"},"marketCount":1751},{"eventType":{"id":"3","name":"Golf"},"marketCount":57},{"eventType":{"id":"4","name":"Cricket"},"marketCount":176},{"eventType":{"id":"5","name":"Rugby Union"},"marketCount":90},{"eventType":{"id":"1477","name":"Rugby League"},"marketCount":66},{"eventType":{"id":"6","name":"Boxing"},"marketCount":57},{"eventType":{"id":"7","name":"Horse Racing"},"marketCount":616},{"eventType":{"id":"8","name":"Motor Sport"},"marketCount":2},{"eventType":{"id":"27454571","name":"Esports"},"marketCount":56},{"eventType":{"id":"10","name":"Special Bets"},"marketCount":52},{"eventType":{"id":"998917","name":"Volleyball"},"marketCount":32},{"eventType":{"id":"11","name":"Cycling"},"marketCount":10},{"eventType":{"id":"2152880","name":"Gaelic Games"},"marketCount":10},{"eventType":{"id":"3988","name":"Athletics"},"marketCount":1},{"eventType":{"id":"6422","name":"Snooker"},"marketCount":23},{"eventType":{"id":"6231","name":"Financial Bets"},"marketCount":17},{"eventType":{"id":"7511","name":"Baseball"},"marketCount":9},{"eventType":{"id":"6423","name":"American Football"},"marketCount":5},{"eventType":{"id":"451485","name":"Winter Sports"},"marketCount":16},{"eventType":{"id":"7522","name":"Basketball"},"marketCount":333},{"eventType":{"id":"7524","name":"Ice Hockey"},"marketCount":141},{"eventType":{"id":"61420","name":"Australian Rules"},"marketCount":40},{"eventType":{"id":"468328","name":"Handball"},"marketCount":41},{"eventType":{"id":"3503","name":"Darts"},"marketCount":46},{"eventType":{"id":"26420387","name":"Mixed Martial Arts"},"marketCount":43},{"eventType":{"id":"4339","name":"Greyhound Racing"},"marketCount":407},{"eventType":{"id":"2378961","name":"Politics"},"marketCount":70},{"eventType":{"id":"72382","name":"Pool"},"marketCount":4}]

    Now i am trying to add filter and get listEvents with this code but it get all data and treating my filter as empty. What is wrong with this filter?

    Code:
    Dim postData As String = "{ ""filter"" : {""eventTypeId"":""4""} }"
    I used their Api-Ng Visualizer tool and it successfully sending request using Event Type ID = 4 as filter and cricket data returned as response.
    Last edited by Terrybogard911; Mar 4th, 2018 at 08:48 AM.

  4. #4

    Thread Starter
    Junior Member
    Join Date
    Sep 2013
    Posts
    28

    Re: Convert this Python piece of code to VB.NET?

    Another quick question, why sending http request to betfair Api doesn't work without vpn? I am forced to use vpn otherwise it returns error. I live in pakistan and i have used many application who display betfair odds and don't need vpn.

  5. #5
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,162

    Re: Convert this Python piece of code to VB.NET?

    Quote Originally Posted by Terrybogard911 View Post
    Didn't know what is difference between Encoding.Default and Encoding.UTF8 though i changed it to UTF8 as you said and your above code worked perfectly.
    The data you send to and receive from Betfair is a sequence of byte values. The Encoding determines how text is converted to/from those byte values. If your App and the Betfair API are using different character encodings, any text communicated can become garbled.

    As I mentioned earlier, Encoding.Default varies from PC to PC (and won't be UTF-8), so there's a good chance it will be different to the Encoding being used by the Betfair API.

    Ideally, you should specify the character encoding in the HTTP request headers, and Betfair should specify its character encoding in the response Headers.

    If the character encoding isn't specified, then my guess would be that UTF-8 is assumed, but whatever is used, Encoding.Default is guaranteed to fail at some point depending on the characters in the text you are sending/receiving (although you are less likely to run into problems if you are only using characters from the English alphabet; it's the accented or non English characters that would cause you grief).

    All this should be outlined in the documentation, but I haven't been able to find it yet.


    With regards to the documentation, most of the code examples given are for the json-RPC API (you are using the json-REST API), and those code examples do indeed contain headers that specify text encodings. I have no idea if those headers are used by the REST API though.



    Quote Originally Posted by Terrybogard911 View Post
    So what should be my next step if i want to get specific event markets like cricket. Should it be put
    Dim postData As String = "{ ""filter"" : {cricket} }" OR Dim postData As String = "{ ""filter"" : {4} }" and POST it to same Api endpoint?
    The first thing to do would be to try it...and consult the documentation when it doesn't work.

    Again, I haven't spotted anything in the documentation that shows how to set up a filter for the REST API. However there are plenty of examples given for the RPC endpoints such as for Request a List of Events for an Event Type:
    Code:
    {
    "filter": {
        "eventTypeIds": [
                          "1"
                        ],
        "marketStartTime": {
                            "from": "2014-03-13T00:00:00Z",
                            "to": "2014-03-13T23:59:00Z"
                           }
              }
    }
    which is filtering on 'Soccer' events (eventType Id = 1) between a certain time range.

    So for Cricket (eventType Id = 4) without also filtering by time range, I'd guess your filter would be:
    "{ ""filter"": { ""eventTypeIds"": [""4""] } }"
    or maybe:
    "{ ""filter"": { ""textQuery"": ""Cricket"" } }"

    But that's only a guess, because I don't have a valid session token to test with.

    So try using Dim postData As String = "{ ""filter"": { ""eventTypeIds"": [""4""] } }" in the code from post#2 above.

    BUT you'd probably want to use a different endpoint with the filter to get specific information about that specific event type (Cricket in your example).

    So you might pass the Cricket EventTypeId as a filter to a call to the ListEvents endpoint to get just the information about all cricket events. Then use some of that information to filter a call to the listMarketCatalogue endpoint to get specific market information for a specific Cricket event, and so on.

    Try following through theExample Requests to get an idea of the process.


    The keys for the filter can be found in the Betting Type Definitions ducumentation here
    Last edited by Inferrd; Mar 4th, 2018 at 08:59 AM. Reason: wrong Id

  6. #6
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,162

    Re: Convert this Python piece of code to VB.NET?

    Quote Originally Posted by Terrybogard911 View Post
    Another quick question, why sending http request to betfair Api doesn't work without vpn? I am forced to use vpn otherwise it returns error. I live in pakistan and i have used many application who display betfair odds and don't need vpn.
    Don't know. But in the blurb for their vendor program they state:
    Please note: Your Betfair account must be verified before your application will be considered. We do not accept Software Vendor licence applications from India, Pakistan, Bangladesh, Sri Lanka or UAE.
    so maybe they are also imposing restrictions for the APIs you are using?

  7. #7

    Thread Starter
    Junior Member
    Join Date
    Sep 2013
    Posts
    28

    Re: Convert this Python piece of code to VB.NET?

    Ok I got it. I was using filter like this.

    Code:
    "{ ""filter"" : {""eventTypeId"":""4""} }"
    Adding those brackets [ ] helped and its now working and i am now getting specific sports markets.

    Code:
    "{ ""filter"": { ""eventTypeIds"": [""1""] } }"
    Don't know. But in the blurb for their vendor program they state:
    Please note: Your Betfair account must be verified before your application will be considered. We do not accept Software Vendor licence applications from India, Pakistan, Bangladesh, Sri Lanka or UAE.
    so maybe they are also imposing restrictions for the APIs you are using?
    Maybe but i am still using those betting bots here in pakistan which provide betfair odds in realtime. Watch attached screenshot.
    Attached Images Attached Images  
    Last edited by Terrybogard911; Mar 4th, 2018 at 09:08 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width