Search code examples
rapimime-typeshttr

Why is R HTTR content statement not producing the expected request body?


I am using R to call on Cybersource API. When I use the GET request I obtain a successful response of 200. When I read the body of the the response rather than get the csv data back I get a path to a csv file path. I wonder what I am doing wrong.

content(request) gives

 "/space/download_reports/output/dailyreports/reports/2018/10/27/testrest/TRRReport-7931d82d-cf4a-71fa-e053-a2588e0ab27a.csv"

The result of content(request) should be the data not a file path.

Here is a the code

library('httr')
merchant<-'testrest'
vcdate<-'Wed, 29 May 2019 10:09:48 GMT'
ho<-'apitest.cybersource.com'
URL<-'https://apitest.cybersource.com/reporting/v3/report-downloads?organizationId=testrest&reportDate=2018-10-27&reportName=TRRReport'
sign<-'keyid="08c94330-f618-42a3-b09d-e1e43be5efda", algorithm="HmacSHA256", headers="host (request-target) v-c-merchant-id", signature="7cr6mZMa1oENhJ5NclGsprmQxwGlo1j3VjqAR6xngxk="'
req<-GET(URL, add_headers(.headers=c('v-c-merchant-id'=merchant, 'v-c-date'=vcdate, 'Host'=ho, 'Signature'=sign)))
content(req)

Here is Cybersource test api where you can verify the data produced.

https://developer.cybersource.com/api/reference/api-reference.html

I am trying to download a report under the reporting tab


Solution

  • Honestly I'm not exactly sure what's going on here, but I do think I was able to get something to work.

    The API seems to like to return data in application/hal+json format which is not one that httr normally requests. You can say you'll accept anything with accept("*") So you can do your request with:

    req <- GET(URL, add_headers('v-c-merchant-id'=merchant, 
      'v-c-date'=vcdate, 
      'Host'=ho, 
      'Signature'=sign), accept("*"))
    

    Now we are actually getting the data back that we want, but httr doesn't know how to automatically parse it. So we need to parse it ourselves. This seems to do the trick

    readr::read_csv(rawToChar(content(req)), skip=1)
    

    There seems to be a header row which we skip with skip= and then we parse the rest as a CSV file with readr::read_csv.