Writing Curl POST in R - r

What is the correct way of writing this Curl POST in R?
I would like to have R read the contents of a file as "values" in the post form.
curl -X POST https://api.priceapi.com/jobs \
-d "token=token" \
-d "country=country" \
-d "source=source" \
-d "currentness=currentness" \
-d "completeness=completeness" \
-d "key=key" \
-d 'values=<values>'
So far I have this-
library(RCurl)
library(RJSONIO)
url = "https://api.priceapi.com/jobs"
file.name = ".../output 1 .txt"
results = postForm(url, token="token",
country="country,
source="source",
currentness="currentness",
completeness="completeness,
key="key",
values=fileUpload(filename = file.name))
It returns "Error: Bad Request"
I also tried it using httr post request-
r = POST(url, body = list(token="token",
country="country,
source="source",
currentness="currentness",
completeness="completeness,
key="key",
values=upload_file(file.name)) )
Here upload_file is not uploading the contents of the file but, I am guessing it is passing the path to the file (as a string) into the "values" parmeter.
Naturally that does not return the correct results.
The result of the httr POST request is;
Response [https://api.priceapi.com/jobs]
Date: 2016-12-13 10:11
Status: 400
Content-Type: application/json; charset=utf-8
Size: 228 B
{
"success": false,
"reason": "parameter value invalid",
"parameter": "value",
"valid values": "An array or a string containing values separated by newline",
"comment": "Make sure the parameter 'value' has a valid value!"

I could solve this by using
file=readLines(".../output 1.txt")
inputValues <- paste(file,collapse="\n")
and then passing inputValues in the values parameter.

Related

Change project key with bitbucket rest api

I am trying to write a script to move repos in a project to another project but I am getting a 400 error whenever I try.
My python requests line looks like:
url = 'https://bitbucketserver.com/rest/api/1.0/projects/example1/repos/repo1'
token = 'TokenString'
response = requests.put(url, headers={'Content-Type': 'application/json', 'Authorization': 'Bearer' + token}, data={'project': {'key': 'NEW_PROJECT'}}, verify=False)
I get a response 400 that says 'Unexpected character ('p' (code112)): expected a valid value (number, string, array, object, true, false, or null) at [Source: com.atlassian.stash.internal.web.util.web.CountingServletInputStream#7ccd7631; line 1, column 2]
I'm not sure where my syntax is wrong
Not python, but work for me via curl:
curl -u 'USER:PASSWORD' --request PUT \
--url 'https://stash.vsegda.da/rest/api/1.0/projects/OLD_PROJECT/repos/REPO_TO_MOVE' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{
"project": {"key":"NEW_PROJECT"}
}'
Maybe can someone help.

Implement curl request in R

I am trying to access the Amadeus travel API
To obtain a token, the given curl is:
curl "https://test.api.amadeus.com/v1/security/oauth2/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"
My RScript Attempt is:
library("httr")
# Get Token
response <- POST("https://test.api.amadeus.com/v1/security/oauth2/token",
add_headers("Content-Type" = "application/x-www-form-urlencoded"),
body = list(
"grant_type" = "client_credentials",
"client_id" = API_KEY,
"client_secret" = API_SECRET),
encode = "json")
response
rsp_content <- content(response, as = "parsed", type = "application/json")
rsp_content
Resulting in the error:
Response [https://test.api.amadeus.com/v1/security/oauth2/token]
Date: 2021-07-23 00:59
Status: 400
Content-Type: application/json
Size: 217 B
{
"error":"invalid_request",
"error_description": "Mandatory grant_type form parameter missing",
"code": 38187,
"title": "Invalid parameters"
}
>
What is the correct way to call this API to obtain a token using R?
The curl -d option is used to send data in the same way an HTML form would. To match that format, use encode="form" rather than encode="json" in the call to POST().

How to pass the curl -F parameter in the httr package?

Hi I try to translate this curl instruction using httr
curl -H "Authorization: Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd" -F file=#test.txt -F filename=test.txt -F parent_dir=/ http://cloud.seafile.com:8082/upload-api/73c5d117-3bcf-48a0-aa2a-3f48d5274ae3
Without the -F parameter the instruction is :
httr::POST(
url = "http://cloud.seafile.com:8082/upload-api/73c5d117-3bcf-48a0-aa2a-3f48d5274ae3",
add_headers(Authorization = "Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd")
)
)
I think I have to use the httr::upload_file function but I didn't manage to use this without error.
Do you have any idea how I can do that ?
Regards
Here is how to construct this curl request with httr package. I used httpbin.org to test the request sent.
You'll use POST filling the body with a list. encode argument controls how this list will be handle and by default it is the correct multipart you need.
res <- httr::POST(
url = "http://httpbin.org/post",
httr::add_headers(Authorization = "Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd"),
# Add the file and metadata as body using a list. Default encode is ok
body = list(
file = httr::upload_file("test.txt"),
filename = "test.txt",
parent_dir = "/"
)
)
httr_ouput <- httr::content(res)
One way to check this is ok is to compare output with the curl command you know is working
out <- sys::exec_internal(
'curl -H "Authorization: Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd" -F file=#test.txt -F filename=test.txt -F parent_dir=/ http://httpbin.org/post'
)
curl_output <- jsonlite::fromJSON(rawToChar(out$stdout))
#compare body
identical(curl_output$files, httr_ouput$files)
#> TRUE
identical(curl_output$form, httr_ouput$form)
#> TRUE
You can also do it with the crul package, another wrapper above curl; The logic is identical
con <- crul::HttpClient$new(
url = "http://httpbin.org/post"
)
crul_req <- con$post(
body = list(
file = crul::upload("test.txt"),
filename = "test.ext",
parent_dir = "/"
)
)
crul_output <- jsonlite::fromJSON(crul_req$parse())

Reading API - code from Curl to R

I am trying to read a json from an authenticated API using R, but not sucessfully.
I have the Curl code and tried to convert it to R using "curlconverter" library and also tried to get it using "httr" library.
curl -X GET \
'https://api.cartolafc.globo.com/auth/liga/gurudocartola-com?orderBy=campeonato&page=1' \
-H 'Cache-Control: no-cache' \
-H 'x-glb-token: mytoken'
I would appreciate a solution to write this code in R.
library(curlconverter) # devtools::install_github("hrbrmstr/curlconverter")
u <- "curl -X GET 'https://api.cartolafc.globo.com/auth/liga/gurudocartola-com?orderBy=campeonato&page=1' -H 'Cache-Control: no-cache' -H 'x-glb-token: mytoken'"
straighten(u) %>%
make_req()
That makes:
httr::VERB(verb = "GET", url = "https://api.cartolafc.globo.com/auth/liga/gurudocartola-com?orderBy=campeonato&page=1",
httr::add_headers(`Cache-Control` = "no-cache",
`x-glb-token` = "mytoken"))
which very straightforwardly (if one has done any research before posting a question) translates to:
httr::GET(
url = "https://api.cartolafc.globo.com/auth/liga/gurudocartola-com",
httr::add_headers(
`Cache-Control` = "no-cache",
`x-glb-token` = "mytoken"
),
query = list(
`orderBy` = "campeonato",
`page` = 1L
)
)
The back-ticks are there solely to remind me they are parameters (and, they sometimes contain dashes or other chars which force a back-tick quote).

RCurl postForm fetching incorrect data

I am trying to replicate the following in R
curl -XPOST -H 'Content-Type: application/json' -d '{"input":{"webpage/url":"http://http://www.mutualart.com/Exhibitions/Richard-Hamilton/4BC4569A3DCC902A"}}' "https://api.import.io/store/connector/13235010-2b34-4ddb-b8b7-245f12158424/_query?_user=63d1abec-6dde-4387-a5ac-75208005a0cb&_apikey=YOUR_API_KEY"
Under Linux, this works and I get the right output (page URL in the output matches x). But, in R, I get the incorrect output - I get the output for http://www.mutualart.com/Exhibitions/Bailey-s-Stardust/14180718CB6BBBFF
My R Code so far is
x= list(items=c("http://www.mutualart.com/Exhibitions/Richard-Hamilton/4BC4569A3DCC902A"))
headers <- list('Accept' = 'application/json', 'Content-Type' = 'application/json')
uri <- "http://api.import.io/store/connector/13235010-2b34-4ddb-b8b7-245f12158424/_query?_user=63d1abec-6dde-4387-a5ac-75208005a0cb&_apikey=rhq3RoF9oXsoFLwPVfM%2Fkk7ephcJg0bqfbj51PPYhEbkITRm%2Fn23TvtJU4wVWfOkPBjL0sdhZTH5tZg%2Bom72iw%3D%3D"
postForm(uri, .opts=list(postfields=toJSON(x), httpheader=headers))

Resources