Write a complicated curl request's R equivalent - r

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")

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")

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.

Trying to get data from an API

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.

Retrieve API data with requests

I am trying to retrieve switch data via the Meraki API. Instructions and samples for the API's are here:
# https://dashboard.meraki.com/api_docs#return-a-switch-port
Sample Request
$ curl -L \
-H 'X-Cisco-Meraki-API-Key: <key>' \
-H 'Content-Type: application/json' \
-X GET 'https://dashboard.meraki.com/api/v0/devices/[serial]/switchPorts/[number]'
Sample Response
Successful HTTP Status: 200
{
"number": 1,
"name": "my port",
"tags": "dorm-room limited",
"enabled": true,
"type": "access",
"vlan": 10,
"voiceVlan": 20,
"poeEnabled": true,
"isolationEnabled": false,
"rstpEnabled": true,
"stpGuard": "disabled",
"accessPolicyNumber": "asdf1234",
"linkNegotiation": "Auto negotiate"
}
I am using Python's requests instead of curl. My code is: (NOTE I have altered the serial number and API key just for this post. I use the correct values when I run the code)
import requests
headers = {
'X-Cisco-Meraki-API-Key': '1111111111111111111111111111111111111111',
'Content-Type': 'application/json',
}
# response = requests.get('https://dashboard.meraki.com/api/v0/devices/[serial]/switchPorts/[number]', headers=headers)
response = requests.get('https://dashboard.meraki.com/api/v0/devices/1111-2222-3333/switchPorts/1', headers=headers)
print(response)
# <Response [200]>
I am getting back <Response [200]> instead of the JSON data that the API above shows.
My HTTP Status is correct, however. What am I missing in order to actually get back the JSON data?
Use print(response.content) instead of print(response).
If you want to save the data in a file, you can use:
content=response.content
data=open("name_you_want.json","wb")
data.write(content)
data.close()
use print (response.text)
instead of print(response)
because its printing response status code instead of body text and i guess you want to print response body
With .content & json.loads you should be able to parse JSON
import requests,json
response = requests.get('https://dashboard.meraki.com/api/v0/devices/1111-2222-3333/switchPorts/1')
json = json.loads(response.content)
print(json.get('name'))
To access curl using python, you can run this:
import requests
headers = {
'accept': 'text/html',
'Cookie': 'token=5e1a8b55b0249136a60423aa02b9120a845fa4122ac98ce4e771aec5d772d7d7a18ac22f18cd47727d00bddc2ebcc5cddf8a402d7a302ddffdeb7c6e15cb2a7005f857112',
}
response = requests.get("http://link-ui3.enter.com/data/1.0/auth/getUserByToken", headers=headers)
print(response.status_code)
print (r.json)
# You will get your json response

API 1.1 requesting twitter bearer token using r

I have searched this forum and tried several things that seemed relevant, but with no success. If anyone can spot what I'm missing I would be very grateful.
I am trying to get a bearer token using application only authorization as explained at https://dev.twitter.com/docs/auth/application-only-auth so that I can GET follower s/ids.
I have constructed a request in r using rstudio with my consumer key & secret in Base64 encoded form.
library(httr)
POST(url="https://api.twitter.com/oauth2/token", config=add_headers(
c('Host="api.twitter.com"',
'User-Agent="NameOfMyApp"',
'Authorization="Basic MyKeyandSecretBase64Encoded"',
'Content-Type="application/x-www-form-urlencoded;charset=UTF-8"',
'Content-Length="29"',
'Accept-Encoding="gzip"')), body="grant_type=client_credentials")
In response I receive:
Response [https://api.twitter.com/oauth2/token]
Status: 403
Content-type: application/json; charset=utf-8
{"errors":[{"label":"authenticity_token_error","code":99,"message":"Unable to verify your credentials"}]}
I tried resetting my credentials but it made no difference.
I'm a few weeks late, but for anyone like me who stumbles across this page, here is some code that works for me, returning a bearer token:
POST(url="https://api.twitter.com/oauth2/token",
config=add_headers(c("Host: api.twitter.com",
"User-Agent: [app name]",
"Authorization: Basic [base64encoded]",
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
"Content-Length: 29",
"Accept-Encoding: gzip")),
body="grant_type=client_credentials")
Once you have a bearer token, you put it in the header of a GET like so:
GET("https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=justinbieber&count=5000",
config=add_headers(c("Host: api.twitter.com",
"User-Agent: [app name]",
"Authorization: Bearer [bearer token]",
"Accept-Encoding: gzip")))
A late response, but the existing answer wasn't working for me. So here's a solution with a modification of the GET request.
add_headers() uses a named vector. This requires the hyphenated header names to be bracketed with backticks (``). So your POST() call should be:
response <- POST(url = "https://api.twitter.com/oauth2/token",
config = add_headers(.headers = c(Host = "api.twitter.com",
`User-Agent` = "NameOfMyApp",
Authorization = "Basic [base64encoded]",
`Content-Type` = "application/x-www-form-urlencoded;charset=UTF-8",
`Content-Length` = "29",
`Accept-Encoding` = "gzip")),
body = "grant_type=client_credentials")
Within a successful response the application access token can be accessed with:
bearer_token <- jsonlite::fromJSON(rawToChar(response$content))$access_token
You can then verify this with a GET request, such as:
GET("https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=justinbieber&count=100",
config = add_headers(.headers = c(Host = "api.twitter.com",
`User-Agent` = "NameOfMyApp",
Authorization = paste("Bearer", bearer_token),
`Accept-Encoding` = "gzip")))

Resources