Trying to get data from an API - r

I'm trying to get some appointment data from a practice management software. I have an API key but I have no experience in the area.
I have tried to convert Curl code with little success. The api documentation is here https://github.com/redguava/cliniko-api
I am trying to convert this curl code
curl https://api.cliniko.com/v1/appointments \
-u API_KEY: \
-H 'Accept: application/json' \
-H 'User-Agent: APP_VENDOR_NAME (APP_VENDOR_EMAIL)'
What I've tried: (yes this is from a curl to r converter)
require(httr)
headers = c(
`Accept` = 'application/json',
`User-Agent` = 'APP_VENDOR_NAME (APP_VENDOR_EMAIL)'
)
res <- httr::GET(url = 'https://api.cliniko.com/v1/appointments',
httr::add_headers(.headers=headers),
httr::authenticate('API_KEY', 'INSERTED MY API KEY'))
Any ideas would be greatly appreciated

httr::authenticate takes input username and password in the form httr::authenticate(username,password).
Curl's authenticate takes argument username and password joined by by a :, i.e. username:password.
In the example from the API documentation the curl command authenticates the username:password combination API_KEY:. Looking closely, we can see that after the : is blank. From this we can determine the username field should be 'API_KEY' and the password field should be ''.
So you should change your curl command to:
require(httr)
headers = c(
`Accept` = 'application/json',
`User-Agent` = 'APP_VENDOR_NAME (APP_VENDOR_EMAIL)'
)
res <- httr::GET(url = 'https://api.cliniko.com/v1/appointments',
httr::add_headers(.headers=headers),
httr::authenticate('API_KEY', ''))
Where API_KEY is your provided API key.

Related

Has anyone tried the Piwik PRO api in R?

I would like to use the Piwik PRO api in R, but cannot find an example for the code.
Does anyone know how to format this into R code? (Or can help me point to a source which will help me to do this myself?)
curl -X POST 'https://<domain>/auth/token' -H "Content-Type: application/json" --data '{
"grant_type": "client_credentials",
"client_id": "your_generated_client_id",
"client_secret": "your_generated_client_secret"
}'
I would suggest using the httr package.
Authentication code should look something like this:
library(httr)
url <- ""
payload <- "{ \"grant_type\": \"client_credentials\", \"client_id\": \"\", \"client_secret\": \"\" }"
encode <- "json"
response <- VERB("POST", url, body = payload, add_headers(Content_Type = 'application/json'), content_type("application/json"), encode = encode)
content(response, "text")

Write a complicated curl request's R equivalent

I have a curl request:
curl -k --insecure -X POST https://somehttp -H 'Content-Type: application/x-www-form-urlencoded' -H 'cache-control: no-cache' -d 'grant_type=password&client_id=my_id&username=admin&password=admin&client_secret=k6897pyy-1h7l-11q0-lp10-s20sg4erlq44' | jq .access_token
How could i write that request in R. I've seen examples of simple ones, but not this complicated.
Obviously I can't test this with the example you provided, but this should get you close. First ensure you populate these variables correctly:
url <- "http://www.somehttp.com"
my_id <- "my_id"
username <- "admin"
password <- "admin"
my_secret <- "k6897pyy-1h7l-11q0-lp10-s20sg4erlq4"
Now the following code prepares the request, sends it, and parses the response (I'm assuming it is json)
library(httr)
H <- add_headers(`Content-Type`= "application/x-www-form-urlencoded",
`cache-control` = "no-cache")
form_body <- list(grant_type = "password",
client_id = my_id,
username = username,
password = password,
client_secret = my_secret)
res <- POST(url = url, body = form_body, encode = "form", H)
content(res, "parsed")

Authenticate using httr package when Making API Requests

I'm learning how to fetch data using an API in R. I understand that the aim of httr is to provide a wrapper for the curl package.
The documentation I'm following so that I make requests to the API has the following HTTP request format. This code below will be used to generate a token
curl -s \
-d "client_id=clientid” \
-d "username=user” \
-d "password=pwd” \
-d "grant_type=password" \
-d "scope=openid email" \
"https://auth.com/token"
Afterward, I'll use the token to now communicate with the API using this request
curl --header "Content-Type: application/json" \
--header "Accept: application/+json" \
--header "Authorization: Bearer token_goes_here“ \
--request GET \
--url "https://api-sitename.org/sections?parent_id=0"
Initially, I run these two requests in a terminal and they were successful, I got a response in JSON format. My question is, how do I run these requests in an R script such that I get a responses and they're it's stored in R studio global environment? My goal is to finally load the dataset from the API to the Rstudio working environment.
T
Here is something to get you started:
library(httr)
resp <- POST("https://auth.com/token",
body=list(client_id="clientid",
username="user",
password="pwd",
grant_type="password",
scope="openid email")
)
#parse for auth token here
content(resp, "text")
get_resp <- GET("https://api-sitename.org/sections?parent_id=0",
add_headers("Content-Type"="application/json",
Accept="application/+json",
"Authorization"=paste("Bearer", token))
I was able to successfully get my API call in R by replacing the content in header to body.
Here is my code
#' Th base url
base_url <- "your/url/endpoint/for/token"
# base64 encoded client id, my end-point requires to encone the client id to base64
c_id <- RCurl::base64(txt = "clinetid:sceret", mode = "character")
#' headers
headers <- httr::add_headers(
"Authorization" = paste("Basic",c_id, sep = " ")
)
# move everything else to the body. grant_type and password were requested by the endpoint
body <- list(
username = "your username",
password = "your password",
grant_type = "password",
scope = "read"
)
#' post call to get the token
httr::POST(
url = base_url,
body = body,
config = headers,
httr::accept_json()
)
When I had the user name and password in the body, I received 400 and 403 errors. Once I moved them o the body received 200 status and the token was successfully retrieved. If you can provide what you tried in R, can help you troubleshoot.

R post/postform upload issue

I am trying to upload a file to a platform via an API
CUrl request from terminal works fine
curl -v --trace-ascii trace.txt -H "Authorization: Bearer XXXX-XXXX-XXXX-XXXX" -F "file=#test1234.txt;type=text/txt" https://xxx.YYYY/upload
But in R when I use the Post I get status 500 error
outfilename="/Volumes/Work/texttest.txt"
POST(url="https://xxx.YYYY/upload",body = upload_file(
path = outfilename,
type = 'text/txt'),
verbose(),add_headers(Authorization=paste0("Bearer ",btoken$access_token)))
or
postForm(uri="https://xxx.YYYY/upload",file = fileUpload(
filename = outfilename, contentType = 'text/txt'),
add_headers(Authorization=paste0("Bearer ",btoken$access_token)))
Can anyone help please ?
EDIT: Got it to work with postForm, will be great if someone helps on why it does not work with POST
httpheader <- c(Authorization=paste0("Bearer ",btoken$access_token))
status<-postForm(uri=paste0(server,"upload"),file = fileUpload(filename = outfilename),.opts=list(httpheader=httpheader))
For POST, the most similar translation is
POST(url="https://xxx.YYYY/upload",
body = list(file=upload_file(
path = outfilename,
type = 'text/txt')
),
verbose(),
add_headers(Authorization=paste0("Bearer XXXX-XXXX-XXXX-XXXX"))
)
Notice how the body= is a list. This submits the data as form-data which is what the curl -F option does.
Note that I find that using a site like http://requestb.in/ can make it easier to troubleshoot these problems. By posting to that site, you can see exactly what is sent to the server and see how the request different between the two methods.

How to authenticate with reddit using RCurl

I've been trying to authenticate with Reddit from R using RCurl based on this example from Reddit's github:
curl -X POST -d 'grant_type=password&username=reddit_bot&password=snoo' --user 'p-jcoLKBynTLew:gko_LXELoV07ZBNUXrvWZfzE3aI' https://ssl.reddit.com/api/v1/access_token
I've tried to convert it to an RCurl command like so:
postForm("https://ssl.reddit.com/api/v1/access_token?grant_type=password",
username = "MyUserName",
password = "MyPassword",
.opts = list(userpwd = "MyClientid:MySecret")
)
But I get an error: Error: Unauthorized
I'm not sure what I'm doing really with the conversion of the curl command to Rcurl. Thanks for any help you could provide!
Try this httr code:
library(httr)
POST("https://ssl.reddit.com/api/v1/access_token",
body = list(
grant_type = "password",
username = "MyUserName",
password = "MyPassword"
),
encode = "form",
authenticate("p-jcoLKBynTLew", "gko_LXELoV07ZBNUXrvWZfzE3aI")
)

Resources