如何通过 Julia HTTP 访问 API

DaK*_*ons 4 http julia

使用 Julia 访问 Betfair Exchange API

我已经使用 Julia 大约 2 个月了,最近一直在尝试使用 Julia 访问 Betfair API。关于此服务的注意事项在这里。 https://docs.developer.betfair.com/display/1smk3cen4v3lu3yomq5qye0ni/Getting+Started

虽然我可以让 Python 示例工作(并且我有一个 appKey 和 sessionToken,但未显示),但我无法成功将此 Python 转换为 Julia。

在下面的示例中,我收到 StatusError 400 响应(这是我得到的最接近的响应)。其他尝试表明 Bound 问题可能来自使用 {} 和 ' 的 Python 示例,然后我尝试将其翻译。

我查看了其他 Stackflow 问题,但发现它们没有与此示例相关的复杂性。

想知道是否有人有任何想法。提前致谢

using HTTP

url="https://api.betfair.com/exchange/betting/json-rpc/v1"
header = "\"X-Application\" : \"appKey\", \"X-Authentication\" : \"sessionToken\" ,\"content-type\" : \"application/json\" "

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

response = HTTP.post(url, data=[jsonrpc_req], headers=[header])

println(response.text)
Run Code Online (Sandbox Code Playgroud)

预期成绩。在 Python 中,我得到了 Betfair Sports and Market 的摘要。

{"jsonrpc":"2.0","result":[{"eventType":{"id":"1","name":"Soccer"},"marketCount":10668},{"eventType":{"id":"2","name":"Tennis"},"marketCount":4590},{"eventType":{"id":"3","name":"Golf"},"marketCount":43},{"eventType":{"id":"4","name":"Cricket"},"marketCount":394},{"eventType":{"id":"5","name":"Rugby Union"},"marketCount":37},{"eventType":{"id":"1477","name":"Rugby League"},"marketCount":24},{"eventType":{"id":"6","name":"Boxing"},"marketCount":27},{"eventType"
...etc...
Run Code Online (Sandbox Code Playgroud)

目前得到

HTTP.ExceptionRequest.StatusError(400, HTTP.Messages.Response:
400 Bad Request.
Run Code Online (Sandbox Code Playgroud)

Prz*_*fel 6

虽然与特定 REST 服务的交互是特定于问题的问题,但这里是一般准则。

首先,您需要正确格式化headers- HTTP.jl 手册中写道:“标头可以是任何[string(k) => string(v) for (k,v) in headers]产生的集合Vector{Pair}

由于我们没有 Betfair API 密钥,让我们看一个更通用的示例,使用https://postman-echo.com/它是一个免费的简单 API 测试,它只返回作为 JSON 的任何输入。

using HTTP
using JSON

headers = (("X-Application","appKey"),("X-Authentication","sessionToken"),
           ("content-type","application/json"))

url="https://postman-echo.com/post"

req = Dict("jsonrpc" => "2.0", "params" => Dict("filet" => Dict()))

response = HTTP.post(url, headers, JSON.json(req))
response_text = String(response.body)
json_obj = JSON.parse()
Run Code Online (Sandbox Code Playgroud)

现在让我们解析输出postman-echo.com

julia> display(JSON.parse(response_text))
Dict{String,Any} with 7 entries:
  "headers" => Dict{String,Any}("x-forwarded-port"=>"443","host"=>"postman-echo.com","x-application"=>"appKey","content-type"…  "json"    => Dict{String,Any}("params"=>Dict{String,Any}("filet"=>Dict{String,Any}()),"jsonrpc"=>"2.0")
  "files"   => Dict{String,Any}()
  "args"    => Dict{String,Any}()
  "data"    => Dict{String,Any}("params"=>Dict{String,Any}("filet"=>Dict{String,Any}()),"jsonrpc"=>"2.0")
  "url"     => "https://postman-echo.com/post"
  "form"    => Dict{String,Any}()
Run Code Online (Sandbox Code Playgroud)

您可以轻松地将上述代码应用于任何 RESTful JSON API。