Has anyone tried the Piwik PRO api in R? - 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")

Related

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.

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

How do I make curl to POST a parameter, reading its value from a file?

I’m playing with GitHub web hooks and I want to use curl to post some sample JSON. The request is supposed to contain a payload POST parameter with the JSON string as a value. As an example, this works:
$ curl --form payload='{"foo":1}' http://somewhere
But I need to read the JSON from a file (say foo.json). Replacing the JSON string by #foo.json posts the payload in the request body:
--------------------------8d0c6d3f9cc7da97
Content-Disposition: form-data; name="payload"; filename="foo.json"
Content-Type: application/octet-stream
{'foo':1}
--------------------------8d0c6d3f9cc7da97--
That’s not really what I want, I need the payload to be passed as a parameter. How do I do that?
Maybe silly but try this:
cat foo.json | xargs -I % curl --form payload='%' http://example.com
Just wrote this little thing and it worked:
var=`cat some.json` && curl --form payload="$var" http://lvh.me/test/index.php
Here’s an alternative Perl testing script. Pass the target URL as the first argument, feed the JSON to STDIN:
#!/usr/bin/env perl
use strict;
use warnings;
use LWP;
my $target = shift #ARGV or die "Need a target URL";
my $ua = LWP::UserAgent->new;
my $payload = do { local $/; <STDIN> };
my $response = $ua->post($target, { payload => $payload });
print $response->as_string;

Resources