'Having trouble getting a curl command to work in R

I have a working curl command:

curl -d '{"query":"query {\n    accountBalances (first: 5) {\n        nodes {\n            id\n            accountId\n            tokenId\n            total\n        }\n    }\n    accounts (first: 5) {\n        nodes {\n            id\n            address\n            mark\n        }\n    }\n}","variables":null}' -H 'Content-Type: application/json' https://api.subquery.network/sq/AcalaNetwork/karura-tokens

I am trying to make it work in R. For example

library(httr)
baseurl <- 'https://api.subquery.network/sq/AcalaNetwork/karura-tokens'
body <- '{"query":"query {\n    accountBalances (first: 5) {\n        nodes {\n            id\n            accountId\n            tokenId\n            total\n        }\n    }\n    accounts (first: 5) {\n        nodes {\n            id\n            address\n            mark\n        }\n    }\n}","variables":null}'
POST(url = 'https://api.subquery.network/sq/AcalaNetwork/karura-tokens',
     body  = 'query {\n    accountBalances (first: 5) {\n        nodes {\n            id\n            accountId\n            tokenId\n            total\n        }\n    }\n    accounts (first: 5) {\n        nodes {\n            id\n            address\n            mark\n        }\n    }',
     add_headers('Content-Type: application/json'))

or this

library(RCurl)
postForm(baseurl,
         data = body,
         .opts = list(httpheader = c('Content-Type' = 'application/json', Accept = 'application/json')))

Can anyone show me where I am going wrong?



Solution 1:[1]

A more appropriate translation would be be

POST(url = baseurl,
     body  = list(
       query = 'query {\n    accountBalances (first: 5) {\n        nodes {\n            id\n            accountId\n            tokenId\n            total\n        }\n    }\n    accounts (first: 5) {\n        nodes {\n            id\n            address\n            mark\n        }\n    }',
       variables = NA
     ),
     encode = 'json')

Here we pass a list for the values you want to submit and set the encoding type to json to POST will do the encoding for us.

Solution 2:[2]

Here is one way to get it to work, using a library for GraphQL.

library(ghql)
x <- GraphqlClient$new()
url <- 'https://api.subquery.network/sq/AcalaNetwork/karura-tokens'
query <- 'query { accountBalances (first: 5) { nodes { id accountId tokenId total } } }'

method = "test"
cli <- GraphqlClient$new(url)
qry <- Query$new()
qry$query(method, query)
result <- cli$exec(qry$queries[[method]])

I am just annoyed that I couldn't figure how to do it with a simple POST form.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MrFlick
Solution 2 Roger J Bos CFA