Translating Python (requests) API call to R (httr)

Viewed 55

As the title suggest, I am having a hard time querying an API with httr in R, which works well in Python using requests. I am not sure what I am doing wrong, and don't have much experience with these type of requests. I've been searching around, but can't seem to find the answer, any help would be appreciated. API endpoint documentation: https://docs.scifeon.com/developer/reference/http-api/endpoints/query

Works in python:

import requests

username = "myemail@web.com"
personal_access_token = "mytoken"
url = "https://provider/api/query/dataset"

header = {"Content-Type": "application/json"}
query = [
{
    "eClass": "Fermentation", 
    "collection": "fermentations", 
    "filters": [{ "field": "attributes.experiment", "value": "expnumber"},], 
}
]

response = requests.request("POST", 
                    url, 
                    headers=header, 
                    json=query, 
                    auth=(
                        username, 
                        personal_access_token
                        )
                    )

response.json()

This python snippet gives the expected json output. However, this does not work in R:

library(httr)
library(jsonlite)

username = "myemail@web.com"
personal_access_token = "mytoken"
url = "https://provider/api/query/dataset"

query <- list(eClass = "Fermentation",
            collection = "fermentations",
            filters = list(field = "attributes.experiment", value = "expnumber"))

response <- POST(url,
     add_headers("Content-Type" = "application/json"),
     authenticate(username, personal_access_token),
     body = query, 
     encode = 'json'
     )

content(response)

The R response is:

[[1]]
[[1]]$code
[1] 1

[[1]]$message
[1] "Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'."

[[1]]$hint
[1] ""

[[1]]$exception
[[1]]$exception$message
[1] "Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'."

[[1]]$exception$stackTrace
[1] ""

[[1]]$exception$innerException
NULL


[[1]]$stacktrace
[1] ""
1 Answers

After reading the documentation more closely, I found that the query just needed to be in JSON format. The following works in R now:

library(httr)
library(jsonlite)

username = "myemail@web.com"
personal_access_token = "mytoken"
url = "https://provider/api/query/dataset"

query_json <- data.frame(eClass = "Fermentation", 
                         collection = "fermentations")
filters <- data.frame(field = "attributes.experiment", 
                      value = "expnumber")
query_json[1, "filters"][[1]] <- list(filters)
query_json <- toJSON(query_json)

response <- POST(url,
                 add_headers("Content-Type" = "application/json"),
                 authenticate(username, personal_access_token),
                 body = query_json, 
                 encode = 'json'
)

content(response)
Related