Nicholas Bucher Ampudia Nicholas Bucher Ampudia - 1 month ago 7
JSON Question

POST encripted request with JSON body on R

I am trying to use R to post an encrypted request to an API.

Specifically the /v3/orders/ request.

It requires the use of an API

key
and
secret
, as well as an increasing
nonce
.

Using
openssl
,
jsonlite
and
httr
libraries:

The body has to be JSON encoded:

book<-"btc_eth"
side<-"sell"
major<-"0.1"
price<-"100"
type<-"limit"

Payload<-toJSON(data.frame(book=book,side=side,major=major,price=price,type=type))


It also requires an authorization header constructed with an sha256 encrypted
signature
.

N<-NONCE() # "1503033312"

method<-"POST"

Path<-"/v3/orders/"

Signature<-sha256(paste0(N,method,Path,Payload),secret)

header<-paste0("Bitso ",key,":",N,":",Signature)


Finally the request should look like this:

url<-"https://api.bitso.com/v3/orders/"

r<-POST(url, body = Payload, add_headers(Authorization=header))


I have been able to post requests with an empty payload to this API before, but this call sends unsupported media type error, something about the way I'm JSON encoding the paylod is causing this.

There's Ruby and PHP examples on how to place this request here.

Answer Source

So, I finally was able to send the request.

I have to thank Colin Fay for his response on how to eliminate the brackets.

The thing was, the header had to be constructed with the unbracketed JSON body, but the body had to be sent as a list with automatic JSON encoding as following:

NC<-NONCE()

mthd<-"POST"

Pyld<- toJSON(data.frame(book=book,side=side,major=major,price=price,type=type))

Pyld <- gsub("\\[|\\]", "", Pyld)

body<-list(book=book,side=side,major=major,price=price,type=type)

url<-"https://api.bitso.com/v3/orders/"

Pth<-"/v3/orders/"

hdr<-paste0("Bitso ",ky,":",NC,":",sha256(paste0(NC,mthd,Pth,Pyld),scrt))

r<-POST(url, body = body, add_headers(Authorization=hdr),encode="json",verbose())