equivalence of -d parameter in curl in httr package of R - r

I'm following the official manual of opencpu package in R. In chapter 4.3 Calling a function It uses curl to test API:
curl http://your.server.com/ocpu/library/stats/R/rnorm -d "n=10&mean=100"
and the sample output is:
/ocpu/tmp/x032a8fee/R/.val
/ocpu/tmp/x032a8fee/stdout
/ocpu/tmp/x032a8fee/source
/ocpu/tmp/x032a8fee/console
/ocpu/tmp/x032a8fee/info
I can use curl to get similar result, but when I try to send this http request using httr package in R, I don't know how to replicate the result. Here is what I tried:
resp <- POST(
url = "localhost/ocpu/library/stats/R/rnorm",
body= "n=10&mean=100"
)
resp
the output is:
Response [HTTP://localhost/ocpu/library/stats/R/rnorm]
Date: 2015-10-16 00:51
Status: 400
Content-Type: text/plain; charset=utf-8
Size: 30 B
No Content-Type header found.
I guess I don't understand what's the equivalence of curl -d parameter in httr, how can I get it correct?

Try this :)
library(httr)
library(jsonlite)
getFunctionEndPoint <- function(url, format) {
return(paste(url, format, sep = '/'))
}
resp <- POST(
url = getFunctionEndPoint(
url = "https://public.opencpu.org/ocpu/library/stats/R/rnorm",
format = "json"),
body = list(n = 10, mean = 100),
encode = 'json')
fromJSON(rawToChar(resp$content))

Related

Could somebody assist with doing API calls with 'httr' package in R?

I tried to do a API call to get data from a website called BirdEye. They have a developer website with instructions on API calls. However, I am having trouble converting curl code into R code using httr package.
Example:
curl -H "content-type: application/json" -H "accept:application/json" -X POST -d { "fromDate":"04/01/2013", "toDate":"05/3/2015", "updateFromDate":"04/01/2013", "updateToDate":"05/3/2015", "sources":["google","citysearch"], "ratings":[1,2,3,4,5,0],"searchStr":"Awesome","subBusinessIds":[145308764185002,145308769721320,145308702026610],"tags":["tag_1","tag_2"] } "https://api.birdeye.com/resources/v1/review/businessId/755009344_1?sindex=0&count=25&api_key=92bcd6e0-c102-43fd-8a67-1a7be5258451" -v
Here is what I did:
headers <- c('Accept' = 'application/json', 'Content-Type' = 'application/json')
body_content <- list('fromDate' = '2019-01-01', 'toDate' = '2019-05-01', 'sources' = 'google', 'ratings' = c(1, 2, 3, 4, 5, 0))
resp <- POST(url ="https://api.birdeye.com/resources/v1/review/businessId/xxxxxxxxxx?sindex=0&count=20&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxx",
body = body_content, content_type("application/json"), accept("application/json"))
But I got an error message below:
Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
Warning message:
In charToRaw(enc2utf8(val)) :
argument should be a character vector of length 1
all but the first element will be ignored
Could someone help with the issue? Appreciate it!

R: Httr package - connection with API, Error 1200: description" : "__all__ : img or url parameter is needed

I am very newbie in HTTR and connection with API by R. I cannot connect with F.A.C.E API (documentation: https://face-api.sightcorp.com/dev-documentation/)
library(httr)
library("XML")
library("jsonlite")
library(RCurl)
key = 'XXX'
img = 'C:\\my_image.jpg'
The query:
my_json <- POST('https://api-face.sightcorp.com/api/detect/', add_headers(app_key = key, img = img, ethnicity = TRUE ))
print(my_json)
and the answer:
Response [https://api-face.sightcorp.com/api/detect/]
Date: 2019-02-19 20:26
Status: 200
Content-Type: application/json
Size: 88 B
{
"error_code" : 1200,
"description" : "__all__ : img or url parameter is needed."
How shall I implement img or url adress into the code to obtain API analysis?
The solution is as follows:
my_body = list('app_key'=key, 'img'= upload_file(img.url))
my_json <- POST('https://api-face.sightcorp.com/api/detect/',body = my_body)

How to pass user and password in new_handle in curl R

I have curl request that is working file, which is as follows:
curl -XGET "https://xxxx.com/xxx" -u "username:password"
How I want to do it using curl package in R
I have following code,
library(curl)
clCall <- new_handle(url = 'https://xxxx.com/xxx')
handle_setopt(clCall, customrequest = "XGET")
Now I don't know how to pass username and password in this curl request
You should set httpauth and userpwd options too:
h <- curl::new_handle()
curl::handle_setopt(
handle = h,
httpauth = 1,
userpwd = "user:passwd"
)
resp <- curl::curl_fetch_memory("https://httpbin.org/basic-auth/user/passwd", handle = h)
jsonlite::fromJSON(rawToChar(resp$content))
#> $authenticated
#> [1] TRUE
#>
#> $user
#> [1] "user"

Simple Curl -H in R

I want to do
curl -H "Authorization: Basic YOUR_API_KEY" -d '{"classifier_id":155, "value":"TEST"}' "https://www.machinelearningsite.com/language/classify"
I tried
h = getCurlHandle(header = TRUE, userpwd = YOUR_API_KEY, netrc = TRUE)
out <- getURL("https://www.machinelearningsite.com/language/classify?classifier_id=155&value=TEST", curl=h,ssl.verifypeer=FALSE)
but it says method not allowed
It's much easier to translate curl command-line arguments into httr calls:
library(httr)
result <- GET("https://www.machinelearningsite.com/language/classify",
add_headers(Authorization=sprintf("Basic %s", YOUR_API_KEY),
query=list(classifier_id=155, value="TEST")))
ideally, YOUR_API_KEY would be an environment variable, so you can change that to:
result <- GET("https://www.machinelearningsite.com/language/classify",
add_headers(Authorization=sprintf("Basic %s", Sys.getenv("YOUR_API_KEY")),
query=list(classifier_id=155, value="TEST")))
You can then do:
content(result)
To retrieve the actual data.

RCurl JSON data to JIRA REST add issue

I'm trying to POST data to JIRA Project using R and I keep getting: Error Bad Request. At first I thought it must be the JSON format that I created. So I wrote the JSON to file and did a curl command from console (see below) and the POST worked just fine.
curl -D- -u fred:fred -X POST -d #sample.json -H "Content-Type: application/json" http://localhost:8090/rest/api/2/issue/
Which brings the issue to my R code. Can someone tell me what am I doing wrong with the RCurl postForm?
Source:
library(RJSONIO)
library(RCurl)
x <- list (
fields = list(
project = c(
c(key="TEST")
),
summary="The quick brown fox jumped over the lazy dog",
description = "silly old billy",
issuetype = c(name="Task")
)
)
curl.opts <- list(
userpwd = "fred:fred",
verbose = TRUE,
httpheader = c('Content-Type' = 'application/json',Accept = 'application/json'),
useragent = "RCurl"
)
postForm("http://jirahost:8080/jira/rest/api/2/issue/",
.params= c(data=toJSON(x)),
.opts = curl.opts,
style="POST"
)
rm(list=ls())
gc()
Here's the output of the response:
* About to connect() to jirahost port 80 (#0)
* Trying 10.102.42.58... * connected
* Connected to jirahost (10.102.42.58) port 80 (#0)
> POST /jira/rest/api/2/issue/ HTTP/1.1
User-Agent: RCurl
Host: jirahost
Content-Type: application/json
Accept: application/json
Content-Length: 337
< HTTP/1.1 400 Bad Request
< Date: Mon, 07 Apr 2014 19:44:08 GMT
< Server: Apache-Coyote/1.1
< X-AREQUESTID: 764x1525x1
< X-AUSERNAME: anonymous
< Cache-Control: no-cache, no-store, no-transform
< Content-Type: application/json;charset=UTF-8
< Set-Cookie: atlassian.xsrf.token=B2LW-L6Q7-15BO- MTQ3|bcf6e0a9786f879a7b8df47c8b41a916ab51da0a|lout; Path=/jira
< Connection: close
< Transfer-Encoding: chunked
<
* Closing connection #0
Error: Bad Request
You might find it easier to use httr which has been constructed with
the needs of modern APIs in mind, and tends to set better default
options. The equivalent httr code would be:
library(httr)
x <- list(
fields = list(
project = c(key = "TEST"),
summary = "The quick brown fox jumped over the lazy dog",
description = "silly old billy",
issuetype = c(name = "Task")
)
)
POST("http://jirahost:8080/jira/rest/api/2/issue/",
body = RJSONIO::toJSON(x),
authenticate("fred", "fred", "basic"),
add_headers("Content-Type" = "application/json"),
verbose()
)
If that doesn't work, you'll need to supply the output from a successful
verbose curl on the console, and a failed httr call in R.

Resources