Search code examples
rapicurlhttr

Writing a proper API request in R for curl -X POST


I am new to this topic and reviewed several SO answers before, but still cannot figure it out.

Trying to access API, using R:

curl -X POST "http://api.spending.gov.ua/api/rest/1.0/transactions" -H "accept: application/json" -H 
"Content-Type: application/json" -d "{ \"payers_edrpous\": [ \"string\" ], \"recipt_edrpous\": [ 
\"string\" ], \"startdate\": \"string\", \"enddate\": \"string\", \"regions\": [ 0 ]}"

My current stage

library(httr)
r <- GET("http://api.spending.gov.ua/api/rest/1.0/transactions")

status_code(r)

This works, I have 200 response. But how to write a query to get data in json format? Appreciate any tips.


Solution

  • The link from @dcruvolo was helpful.

    In order get to this to work, you need to start with some valid values. From the API link in the question, there is a test page to order to test the submittal:

    enter image description here

    One can substitute in test values and then press the "Execute" button submit values. Attempted values from the comments above, valid enough not to cause an error but also did not return any valid results.

    To perform the POST in R here is an example:

    posting<-'{
      "payers_edrpous": [
        "00013534"
      ],
      "recipt_edrpous": [
        ""
      ],
      "startdate": "2020-03-01",
      "enddate": "2020-03-28",
      "regions": [
        0
      ]
    }'
    
    library(httr)
    r <- POST("http://api.spending.gov.ua/api/rest/1.0/transactions", body=posting, 
              httr::add_headers(`accept` = 'application/json'), 
              httr::content_type('application/json')) #encode="json"
    content(r)
    

    Posting is the JSON body to pass, edit this as necessary. All variables are strings except "regions" where it is an integer, not sure what the valid range is.

    Sorry this is the best I can do. Good luck.