I have the following code in python which returns a 200 status:
> credentials = {
> 'grant_type': 'client_credentials',
> 'scope':'various scopes go here'
> }
> response = requests.post('https://sample_website.com/oauth/token',
> headers = {"Authorization": "Basic {}".format(signed_request),
> "Content-Type":"application/x-www-form-urlencoded"},
> data = credentials
> )
when i try the following code using the same signed_request I get a 401 error
credentials <- "{'grant_type': 'client_credentials','scope':'various scopes'}"
response <- POST(url = 'https://sample_website.com/oauth/token',
add_headers(
Authorization = signed_request,
'Content-Type' = 'application/x-www-form-urlencoded'
),
accept('application/json'),
body = credentials,
encode = 'json',
verbose()
)
I can't figure out what I am doing wrong but I'm assuming that I am not formatting the body correct or there might be an issue with the headers I am passing.
Your body is appropriate for the content type "application/json", but not for "x-www-form-urlencoded". The easiest solution is to pass a list, and let R take care of serialising it for you.
body <- list(
grant_type="client_credentials",
scope="scopes"
)
POST(url=*,
add_headers(Authorization=paste("Basic", signed_request)),
body=body,
encode="form"
)
Depending on what it is you're doing, you may also want to try the httr2 package (the successor to httr) and its built-in OAuth authentications options, among which is client credentials.
Related
I'm trying to create authenticate into the Letterboxd API using R and the httr package. The Letterboxd docs give instructions, but I am not sure how to put everything together into a URL.
I know the url is:
url <- "https://api.letterboxd.com/api/v0/auth/token"
And then they want my username and password, presumably as JSON, but what I'll write as a named list since I'm doing this in R:
login_info <- list(
grant_type = "password",
username = "myemail#gmail.com",
password = "extremelysecurepassword"
)
I've tried various calls, using GET(), oauth2.0_token(), oauth_endpoint() functions from the httr package.
I feel like I have all the necessary information and am circling around a solution, but I can't quite nail it.
The docs contain this information:
When generating or refreshing an access token, make a form request to the /auth/token endpoint with Content-Type: application/x-www-form-urlencoded and Accept: application/json headers
(Full text is linked to above)
And I'm not sure how to add that information; in working with APIs through R, I'm used to just sending URLs with UTM parameters, but the inputs they want don't work here using ? and &.
I'm aware of this related post, but it looks like it relies on having a secret token already. And I don't seem to be able to generate a secret token inside of the GUI of Letterboxd.com, which is again what I'm used to doing with authentication. I think I need to feed it those sources of information above in login_info to the url, but I don't quite know how to connect the dots.
How do I authenticate to the Letterboxd API using R?
This runs for me but I get a 401 Unauthorized since you correctly did not supply valid credentials. It looks like there is a python library for this API https://github.com/swizzlevixen/letterboxd if you need hints how to make subsequent requests.
sign_request() is mimicking python library's api.py#L295-L304
sign_request <- function(apisecret, url, method, body = "") {
signing_bytes <- as.raw(c(charToRaw(method), 0, charToRaw(url), 0, charToRaw(body)))
# https://stackoverflow.com/a/31209556/8996878
# https://stackoverflow.com/q/54606193/8996878
digest::hmac(key = apisecret, object = signing_bytes, algo = "sha256", serialize = FALSE)
}
url <- "https://api.letterboxd.com/api/v0/auth/token"
login_info <- list(
grant_type = "password",
username = "myemail#gmail.com",
password = "extremelysecurepassword"
)
apikey <- "mytopsecretapikey"
apisecret <- "YOUR_API_SECRET"
method <- "POST"
params <- list(
apikey = apikey,
nonce = uuid::UUIDgenerate(),
timestamp = round(as.numeric(Sys.time()))
)
# now we need to sign the request
body <- paste(names(login_info), login_info, sep = "=", collapse = "&")
body <- URLencode(body)
body <- gsub("#","%40", body) # something URLencode doesn't do but post does
destination <- httr::parse_url(url)
destination$query <- params
post_url_with_params <- httr::build_url(destination)
signature <- sign_request(apikey, post_url_with_params, method, body)
token_request <- httr::POST(url, httr::add_headers(
"Accept" = "application/json",
"Authorization" = paste0("Signature ", signature)
),
query = params,
body = login_info, encode = "form", httr::verbose()
)
token_body <- httr::content(token_request, type = "application/json")
# look for the value of"access_token"
Trying to send POST request in R but didn't work. I tried:
require(httr)
token_endpoint = '...'
client_id = '...'
client_secret = 'pgGj9n4Sdl8cfM4cKNnjYcLVGSIyQxhm3ydCX3IRbdc='
scope = 'icdapi_access'
grant_type = 'client_credentials'
r <- POST(token_endpoint, add_headers('client_id'= client_id,
'client_secret'= client_secret,
'scope'= scope,
'grant_type'= grant_type))
with package httr following a Python version of this https://github.com/ICD-API/Python-samples/blob/master/sample.py
but I don't know where to find access_token in r
Also I don't know where should I
Essentially, you need to retrieve the content object in your response data and have it parsed. Consider sending JSON content type as a config parameter (i.e., unnamed parameter). Since it is json, convert the content with rawToChar and pass it into jsonlite::fromJSON(). You may need to dig inside api_json to retrieve needed data.
library(httr)
library(jsonlite)
...
response <- httr::POST(
token_endpoint,
add_headers(
'client_id'= client_id,
'client_secret'= client_secret,
'scope'= scope,
'grant_type'= grant_type)
),
httr::content_type_json()
)
api_json <- jsonlite::fromJSON(rawToChar(response$content))
I have a question about to add body to GET request.
In Postman, I easily add body raw json to tab Body
In R, I use httr::GETand I can not find any option to add them. I try to use option query, but it return error 500 "Missing parameter username"
This is my code (sorry about fake data):
library(httr)
api <- ".........................../users/authorize"
query <- list("username": "xxxxx", "password": "xxxxxxxxxxxx")
resp <- GET(api, query = query)
stop_for_status(resp)
# Error: Internal Server Error (HTTP 500).
content(resp, type = "text", encoding = "utf-8")
# [1] "{\"status\":\"0\",\"error_code\":\"S002\",\"errors\":\"Missing param [username].\"}"
Can anybody help me to this case? Thank you so much.
Try this:
resp <- httr::POST(body = query, encode = "json")
I am having trouble with DELETE requests in R. I have been successful in making GET and POST requests using the below code. Any help / pointers will be appreciated.
It will require an api.key, secret & passphrase from GDAX to work.
Here is my function:
library(RCurl)
library(jsonlite)
library(httr)
library(digest)
cancel_order <- function(api.key,
secret,
passphrase) {
api.url <- "https://api.gdax.com"
#get url extension----
req.url <- "/orders/"
#define method----
method = "DELETE"
url <- paste0(api.url, req.url)
timestamp <-
format(as.numeric(Sys.time()), digits = 13) # create nonce
key <- base64Decode(secret, mode = "raw") # encode api secret
#create final end point----
what <- paste0(timestamp, method, req.url)
#create encoded signature----
sign <-
base64Encode(hmac(key, what, algo = "sha256", raw = TRUE)) # hash
#define headers----
httpheader <- list(
'CB-ACCESS-KEY' = api.key,
'CB-ACCESS-SIGN' = sign,
'CB-ACCESS-TIMESTAMP' = timestamp,
'CB-ACCESS-PASSPHRASE' = passphrase,
'Content-Type' = 'application/json'
)
##------------------------------------------------
response <- getURL(
url = url,
curl = getCurlHandle(useragent = "R"),
httpheader = httpheader
)
print(rawToChar(response)) #rawToChar only on macOS and not on Win
}
The error I get is "{\"message\":\"invalid signature\"}" even though the same command will code and signature will work with GET & POST.
Ref: GDAX API DOCs
just a guess as I am not familiar with the API, but perhaps you are missing the 'order-id' ...
look at: https://docs.gdax.com/?javascript#cancel-an-order
Ok. I took #mrflick's advise and pointed my connection to requestbin based on his feedback on a different but related question.
After careful inspection, I realized that the my request for some reason was treated as a POST request and not a DELETE request. So I decided to replace the getURL function with another higher level function from RCurl for it to work.
response <- httpDELETE(
url = url,
curl = getCurlHandle(useragent = "R"),
httpheader = httpheader
)
Everything else remains the same. Apparently there never was an issue with the signature.
I have added this function now to my unofficial wrapper rgdax
EDIT::
The unofficial wrapper is now official and on CRAN.
I am looking to do a simple GET request (from the Aplos API) in R using the httr package. I'm able to obtain a temporary token by authenticating with an API key, but then I get a 401 "Token could not be located" once trying to use the token to make an actual GET request. Would appreciate any help! Thank you in advance.
AplosURL <- "https://www.aplos.com/hermes/api/v1/auth/"
AplosAPIkey <- "XYZ"
AplosAuth <- GET(paste0(AplosURL,AplosAPIkey))
AplosAuthContent <- content(AplosAuth, "parsed")
AplosAuthToken <- AplosAuthContent$data$token
#This is where the error occurs
GET("https://www.aplos.com/hermes/api/v1/accounts",
add_headers(Authorization = paste("Bearer:", AplosAuthToken)))
This is a Python snippet provided by the API documentation:
def api_accounts_get(api_base_url, api_id, api_access_token):
# This should print a contact from Aplos.
# Lets show what we're doing.
headers = {'Authorization': 'Bearer: {}'.format(api_access_token)}
print 'geting URL: {}accounts'.format(api_base_url)
print 'With headers: {}'.format(headers)
# Actual request goes here.
r = requests.get('{}accounts'.format(api_base_url), headers=headers)
api_error_handling(r.status_code)
response = r.json()
print 'JSON response: {}'.format(response)
return (response)
In the python example, the return of the auth code block is the api_bearer_token which is base64 decoded and rsa decrypted (using your key) before it can be used.
...
api_token_encrypted = data['data']['token']
api_bearer_token = rsa.decrypt(base64.decodestring(api_token_encrypted), api_user_key)
return(api_bearer_token)
That decoded token is then used in the api call to get the accounts.
The second issue I see is that your Authorization header does not match the example's header. Specifically, you are missing the space after "Bearer:"
headers = {'Authorization': 'Bearer: {}'.format(api_access_token)}
vs
add_headers(Authorization = paste("Bearer:", AplosAuthToken)))
Likely after addressing both of these you should be able to proceed.