HTTP POST using httr in R - r

I am trying to adapt my curl request from running it in Terminal to R. For this I am using the httr package. My request is as follows and works from Terminal
curl -u user#email.com:password -H "Content-Type:application/json" -X POST "https://catalogue.onda-dias.eu/dias-catalogue/Products(48809a01-71bc-4669-8639-f0528abcdafe)/Ens.Order"
My attempt to use httr POST function is as follows:
pars <- list(username='user#email.com', password='password')
res<-POST("https://catalogue.onda-dias.eu/dias-catalogue/Products(48809a01-71bc-4669-8639-f0528abcdafe)/Ens.Order", body = pars, add_headers('Content-Type'='application/json'))
I am getting a 401 error code. Do you know how should I properly convert my request?

Try using httr:authenticate
require(httr)
headers = c('Content-Type' = 'application/json')
r <- httr::POST( url = 'https://catalogue.onda-dias.eu/dias-catalogue/Products(48809a01-71bc-4669-8639-f0528abcdafe)/Ens.Order'
, httr::add_headers(.headers=headers)
, httr::authenticate('user#email.com', 'password'))

Related

Password Grant generate token using HTTR package in R OAuth2

Brand new to API's and in a bit over my head. Reading a bit and searching around but still confused. I was given the following code to run in curl to generate a token using oauth2 with the password grant. I want to implement this code in R and running into some issues.
curl -H "Content-type: application/x-www-form-urlencoded" -H "Authorization: Basic xxxyyy123xxx==" -d "grant_type=password&username={username}&password={password}" https://{website}.com/rest/v2/oauth/token
When I run the above command in a terminal it generates a token which I have successfully used in R using this code:
token <- {character string generated by the above curl command}
call <- "https://{website}.com/rest/v2/services/APIService/getRegistryRecordByAccessionID?id={id#}"
df <- as.data.frame(fromJSON(content(httr::GET(call, add_headers(Authorization = paste("Bearer", token))), "text"), flatten = TRUE))
All I want is to generate the token in R instead of using another program like I have been. This is where my errors come up. The basic format I believe is:
token <- oauth2.0_token(endpoint = oauth_endpoint(
authorize = NULL,
access = "https://{website}.com/rest/v2/oauth/token"),
app = oauth_app(), #not sure how to set this up
use_basic_auth = T,
add_headers(Content-type = "application/x-www-form-urlencoded",
Authorization = "Basic xxxyyy123xxx==") #not sure if i need the authorization header here, I believe I need the content-type heder
)
From MrFlick's comments above, we can integrate the curl auhtorization commands into a POST using the httr package. We then look at the content of the object this returns which will include the access token in the first item in the list.
token <- content(httr::POST("https://{website}.com/rest/v2/oauth/token", body=list(grant_type="password", "username="{username}", password="{password}"), encode="form"))[[1]]

Post request status 500

I want to upload a jpg file to a server using python post request. I used a curl command that works fine:
curl --cacert C:\cacert.pem -u user:key -F "data=#picture.jpg" https://serverurl/users/pictures
I am using the following python request but it gives me a status 500 response.
picture = {'data' : ('picture',open('picture.jpg','rb'))}
req = requests.post(
'https://serverurl/users/pictures',
files=picture, auth=('user','key'))
Your curl command is POSTing a form with "data=#picture.jpg" while you are uploading a local file using requests. Have you read the doc?
Try something different:
session = requests.Session()
session.post('https://serverurl/users/pictures',
data={'data': 'picture.jpg'}, cert='C:\cacert.pem', auth=('user':'pass'))

httr POST authentication error

I am trying to structure a POST json request using httr. The API documentation proposes the following the CURL request:
curl -X POST -H "Authorization:Token XXXXXXXXX" -H "Content-Type: application/json" --data "{\"texts\":[\"A simple string\"]}" https://api.uclassify.com/v1/uclassify/topics/classify
My R httr implementation is the following:
POST("https://api.uclassify.com/v1/uClassify/Topics/classify",
encode="json",
add_headers('Authorization:Token'="XXXXXXXXX"),
body=("A simple string"))
But I received a 401 error message which indicates that my authentication failed. Any suggestion on how I can implement the CURL request on httr?
Just in case it can help somebody else, the below code works for me:
POST("https://api.uclassify.com/v1/uClassify/Topics/classify",
encode="json",
add_headers(Authorization = "Token XXXXXXXXX"),
body = "{\"texts\":[\"A simple string\"]}")

How do I get an API token using R, cURL command on cygwin terminal works (windows 8)

I am able to get a API authentication token using the curl command on cygwin terminal on windows
curl -X POST -d '{"username":"usenamexxx","password":"passwordxxx"}' https://demo.website.com/api/token
output looks like
{"token":"87JrlYIOQa6g6aXciJOxNUK81","_links":{"DiscoveryPage":{"title":"Available API Resources","href":"https://demo.website.com/api"}}}
but when I try the POST command from R using the httr package I get the following error
library(httr)
tokenURL <- "https://demo.website.com/api/token"
s <- POST(tokenURL,body = list(username = "usenamexxx",password = "passwordxxx" ))
Error in function (type, msg, asError = TRUE) :
Unknown SSL protocol error in connection to demo.website.com:443
What am I doing wrong. Is there a different way to use POST?
Sorry I cannot provide a reproducible example as I cannot share my authentication details. If there is a way to provide more details please let me know.

RCurl getURLContent detect content type through final redirect

This is a followup question to RCurl getURL with loop - link to a PDF kills looping :
I have the following getURL command:
require(RCurl)
#set a bunch of options for curl
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))
agent="Firefox/23.0"
curl = getCurlHandle()
curlSetOpt(
cookiejar = 'cookies.txt' ,
useragent = agent,
followlocation = TRUE ,
autoreferer = TRUE ,
httpauth = 1L, # "basic" http authorization version -- this seems to make a difference for India servers
curl = curl
)
x = getURLContent('http://timesofindia.indiatimes.com//articleshow/2933019.cms')
class(x)
#[1] "character"
attr(x, "Content-Type")
#"text/plain"
In a browser, the link above ends up redirecting to:
x = getURLContent('http://timesofindia.indiatimes.com/photo.cms?msid=2933009')
class(x)
#[1] "raw"
attr(x, "Content-Type")
#"application/pdf"
Assuming I know only the first link, how can I detect that the final location of the redirect (or redirects) is of a certain type (in this case PDF)?
Thanks!!
Maybe there's a better solution, but one way could be this:
# ...
h <- basicTextGatherer()
x = getBinaryURL('http://timesofindia.indiatimes.com//articleshow/2933019.cms',
headerfunction = h$update, curl = curl)
r <- gregexpr("Content-Type:.*?\n", h$value())
tail(regmatches(h$value(), r)[[1]], 1)
# [1] "Content-Type: application/pdf\r\n"
I have run into a similar issue trying to run getURLContent using digest authentication to get at binary data (using a non-standard mime type). I am running RCurl v1.95-4.1 on R 2.15.3.
If I run getURLContent without the binary=TRUE flag, it won't autoswitch to binary=TRUE because of the mime header for this data type, so it attempts to perform a rawToChar() and throws a 'embedded NULL in string' error. However the authentication does work.
If I add a binary=TRUE flag to the getURLContent call, it seems to cause issues with the authentication step, since I then get an 'Error: Unauthorized' response.
What finally worked was to replace getURLContent() with getBinaryURL() [as in the example above], which allowed the userpwd="u:p" authorization to work and delivered the binary data to my assigned object.
I think that the author of RCurl has made improvements to getURLContent's handling of binary data for v1.97, based on what I see in GitHub, so this may become a thing of the past...except for those of us still running older R setups.

Resources