How to properly run an API GET request with ODBC access? - r

Im trying to create an API that receives an ID, queries a MSSQL database and returns back a result.
#* #apiTitle IdCx
#* #apiDescription A test
#* #get /IdCx
#*
apiFn <- function(id) {
require(odbc)
require(glue)
dbcon <- dbConnect(odbc::odbc()
,dsn = "test"
,database = "testDB"
,uid = user1
,pwd = pass1
,Trusted_Connection= "No"
,encoding = "UTF-8"
)
IdCx = dbGetQuery(dbcon, glue_sql('SELECT max (CC.IdCx)
FROM table CC
where IdA in ({id})
'))
as.numeric(IdCx)
}
After creating the R file main.R, I execute it:
apiTest <- pr("main.R")
pr_run(apiTest)
But I get this error
{
"error": "500 - Internal server error",
"message": "Error in h(simpleError(msg, call)): error in evaluating the argument 'statement' in selecting a method for function 'dbGetQuery': error in evaluating the argument 'conn' in selecting a method for function 'dbQuoteLiteral': el argumento \".con\" is missing, with no default\n"
}
But if I deliberately insert a fixed id=1365350 inside the code (just for testing), the API will return a correct result
#* #apiTitle IdCx
#* #apiDescription A test
#* #get /IdCx
#*
apiFn<- function(id) {
require(odbc)
require(glue)
id=1365350
dbcon <- dbConnect(odbc::odbc()
,dsn = "venus"
,database = "DWHICV"
,uid = Sys.getenv("sql_reportes_id")
,pwd = Sys.getenv("sql_reportes_pw")
,Trusted_Connection= "No"
,encoding = "UTF-8"
)
IdCx = dbGetQuery(dbcon, glue_sql('SELECT max (CC.IdCx)
FROM hceCxCirugia CC
where IdAtencion in ({id})
'))
as.numeric(IdCx)
}
Including #* #param IdA wont fix the error

Figured it out. Eventhough I never used the parameter .con inside the glue_sql function when running it from RStudio, apparently is mandatory when using plumber API.
IdCx = dbGetQuery(dbcon, glue_sql('SELECT max (CC.IdCx)
FROM table CC
where IdA in ({id})
,.con = dbcon))

Related

Printing sprintf without quotes

I have some IDs that I want to eventually loop into a larger variable:
playerId <- c(12345, 23456, 34567)
But to first do that, I need to use sprintf to create the necessary lines of code that will run correctly in an API request that looks like something like this when I'm running one at a time:
POST(
'https://api.secure.com/v1/Test',
accept_json(),
content_type_json(),
add_headers(Authorization = VanAPI),
encode = "json",
body=list(playerId = 12345)
)
When I run the above request, it works just fine. But for the purposes of a loop, I want it to look like this:
POST(
'https://api.secure.com/v1/Test',
accept_json(),
content_type_json(),
add_headers(Authorization = ApiKey),
encode = "json",
PlayerIdLines
)
So what I'm doing is creating a series of the necessary line I need for each ID:
PlayerIdLines <- cat(sprintf('body=list(playerId = %s\n)', playerId))
When I first run that line, it produces this output:
> PlayerIdLines <- cat(sprintf('body=list(playerId = %s\n)', playerId))
body=list(targetId = 12345
) body=list(targetId = 23456
) body=list(targetId = 34567
)
But then after that, whenever I try to execute variable PlayerIdLines, all it does is return null:
> PlayerIdLines
NULL
Why is that happening? Why is it being stored as NULL?
EDIT: BASED ON MR FLICK'S ANSWER
I try running the following:
get_data <- function(url) {
POST(
'https://api.secure.com/v1/Test',
accept_json(),
content_type_json(),
add_headers(Authorization = VanAPI),
encode = "json",
body=list(playerId = playerId)
)
}
map_df(playerIds, get_data, .id = 'log') -> CreateDF
But I'm met with the following error:
Error: Argument 1 must be a data frame or a named atomic vector.

Authentification Scope Problems with Google Analytics API in Shiny Dashboard

I am setting up a Shiny Dashboard to get unsampled reports through the Google Analytics Report API. This is my first Shiny-Projekt so maybe the solution to my problem is very simple. Unfortunately i can not find anything which would help me. So welcome to my very first question on Stackoverflow :).
I already set the authentication scope to the highest and set an client web id in an own projekt. Basicly everything which is best practiced in all found tutourials (Big Respect to Mark Edmondson!).
library(shiny) # R webapps
library(googleAuthR) # auth login
# refresh authenticiaction token and set client scope
gar_set_client(web_json = "CLIENTID-JSONFILE", scopes = ("https://www.googleapis.com/auth/analytics"))
library(googleAnalyticsR)
####################
# Shiny: USER INTERFACE
####################
# Define UI
ui <- fluidPage(
# Authorization Login-Button
googleAuth_jsUI("auth", login_text = "Log In"),
# Drop-Down Menue: Account, Property, View
column(width=12, authDropdownUI("auth_dropdown", inColumns = FALSE)), # Modul Auswahl des Views 1 von 2
dateRangeInput("datepicker", NULL, start = Sys.Date()-30),
# The dimension selector (dropdown)
selectInput("dim", label = "Please select at least one dimension",
choices = dimension_options,
selected = c("date","hour","minute"),
multiple = TRUE),
# The metric dropdown
selectInput("metric", label = "Please select at least one and maximal ten metrics",
choices = metric_options,
selected = "sessions",
multiple = TRUE),
# Download Button
downloadButton("downloadData", "Download")
)
####################
# Shiny: SERVER LOGIK
####################
# Define server logic
server <- function(input, output, session) {
# get authorizatin token
auth <- callModule(googleAuth_js,"auth")
# Accountliste:
ga_accounts <- reactive({
req(auth())
with_shiny(
ga_account_list,
shiny_access_token = auth())
})
# Views: Greift auf die Accountliste zu
view_id <- callModule(authDropdown, "auth_dropdown",
ga.table = ga_accounts)
# Daten abrufen
ga_data <- reactive({
req(view_id())
req(input$datepicker)
req(input$dim)
req(input$metric)
with_shiny(
google_analytics,
view_id(),
date_range <- input$datepicker,
metrics <- input$metric,
dimensions <- input$dim,
max = -1, #kein Sampling
shiny_access_token = auth()
)
})
# Daten downloaden
output$downloadData <- downloadHandler(
filename = function() {
paste("ViewID_",view_id(), ".csv", sep="")
},
content = function(file){
write.csv2(ga_data(), file, row.names = FALSE)
})
}
# Run the application
shinyApp(ui = ui, server = server)
The Problem is, that i get the following Error-Code despite the Code worked a few days before:
Warning: Error in : API returned: Insufficient Permission: Request had insufficient authentication scopes.
93: stop
92: checkGoogleAPIError
91: _f
89: cachedHttrRequest
88: memDoHttrRequest
87: f
86: gar_api_page
85: f
84: with_shiny
83: <reactive:ga_accounts> [S:/GA_Report_Shiny/shinyapp_v0.R]
67: ga.table
66: <reactive>
50: pList
44: <observer>
1: runApp
You need "https://www.googleapis.com/auth/analytics.edit" to list GA accounts, which is what is needed for the ga.table function above.
The very first Shiny-Project you need to understand Google Analytics Report API. See below I mention API console support two type of credentials. OAuth 2.0 and API Keys.
// Create the service.
var service = new DiscoveryService(new BaseClientService.Initializer
{
ApplicationName = "Discovery Sample",
ApiKey="[YOUR_API_KEY_HERE]",
});
// Run the request.
Console.WriteLine("Executing a list request...");
var result = await service.Apis.List().ExecuteAsync();
// Display the results.
if (result.Items != null)
{
foreach (DirectoryList.ItemsData api in result.Items)
{
Console.WriteLine(api.Id + " - " + api.Title);
}
}
You can also refer them for a more complete solution.

How to use the zillow api with ZillowR

I want to access the GetDeepSearchResults info from the Zillow API.
My code:
library(ZillowR)
zapi_key = getOption('Myapikey')
GetDeepSearchResults(
address = '600 S. Quail Ct.',
zipcode = '67114',
rentzestimate = FALSE,
api_key = zapi_key
)
Error:
Error in GetDeepSearchResults(address = "600 S. Quail Ct.", zipcode = "67114", :
unused arguments (zipcode = "67114", api_key = zapi_key)
Why does this error occur? What can I do to fix this?
Edit: I changed the code according to the comments and got this:
My code:
library(ZillowR)
zapi_key = getOption('myapikey')
GetDeepSearchResults(
address = '600 S. Quail Ct.',
citystatezip = '67114',
rentzestimate = FALSE,
zws_id = 'myapikey',
url = "http://www.zillow.com/webservice/GetDeepSearchResults.htm"
)
Output:
$request
$request$address
NULL
$request$citystatezip
NULL
$message
$message$text
[1] "Error: invalid or missing ZWSID parameter"
$message$code
[1] "2"
$response
NULL
How can I fix this?
The unused arguments error is typical when you pass arguments, which are not parts of the function. So R doesn't know what to do with those and returns the error. You can check the documentation of the function with ?GetDeepSearchResults
This shows you the usage:
GetDeepSearchResults(address = NULL, citystatezip = NULL,
rentzestimate = FALSE, zws_id = getOption("ZillowR-zws_id"),
url = "http://www.zillow.com/webservice/GetDeepSearchResults.htm")
To have this work, you have to set your id first with (you can create an id on https://www.zillow.com/howto/api/APIOverview.htm):
set_zillow_web_service_id("youractualkey")
So you function does not have the argument zipcode and api_key. Let's change your arguments to some which exist:
GetDeepSearchResults(address='600 S. Quail Ct.', citystatezip ='67114',
rentzestimate=FALSE)
You surely recognized I did not use your api_key. This is because the default:zws_id = getOption("ZillowR-zws_id") calls your global 'ZillowR-zws_id' which you just set with the set_zillow_web_service_id() command. So it's not necessary to change the default value. But you can skip this when you use zws_id ="youractualkey" from zillow
I made a random account I set up for validating. This gives me the output:
$request
$request$address
NULL
$request$citystatezip
NULL
$message
$message$text
[1] "Error: this account is not authorized to execute this API call"
$message$code
[1] "6"
$response
NULL
So I could successfully contact the server and my key was recognized. The account authority is not R related and has to be set on the website.

MturkR, R, automatically posting microbatches

I am new to MTurk, but have some fluency with R. I am using the MTurkR package the first time, and I am trying to create "micro-batches" that post on MTurk over time. The code I am using can be found below (the XXXX parts are obviously filled with the correct values). I don't get any error messages, the code runs, and posts the HIT both in the Sandbox and in the real correctly. However, the HITs posted do not show up in the Sandbox Requester account, or the real requester account which means - as far as I understand - that I can't evaluate the workers who submit a completion code before they are paid automatically.
Could anyone point out where the error is, and how could I review the HITs?
Thanks.
K
##### Notes:
# 1) Change sandbox from TRUE to FALSE to run live (make sure to test in sandbox first!!)
##### Step 1: Load library, set parameters
#### Load MTurkR library
library(MTurkR)
#### HIT Layout ID
# Layout ID for the choice task
# my_hitlayoutid = "XXXX"
# Layout ID for the choice task in the Sandbox
my_hitlayoutid = "XXXX"
#### Set MTurk credentials
Sys.setenv(
AWS_ACCESS_KEY_ID = "XXXX",
AWS_SECRET_ACCESS_KEY = "XXXX"
)
#### HIT parameters
## Run in sandbox?
sandbox_val <- "FALSE"
## Set the name of your project here (used to retrieve HITs later)
myannotation <- "myannotation"
## Enter other HIT aspects
newhittype <- RegisterHITType(
title = "hope trial",
description = "Description",
reward = "2.5",
duration = seconds(hours = 1),
keywords = "survey, demographics, neighborhoods, employment",
sandbox = sandbox_val
)
##### Step 2: Define functions
## Define a function that will create a HIT using information above
createhit <- function() {
CreateHIT(
hit.type = newhittype$HITTypeId,
assignments = 2,
expiration = seconds(days = 30),
annotation = myannotation,
verbose = TRUE,
sandbox = sandbox_val,
hitlayoutid = my_hitlayoutid
)
}
## Define a function that will expire all running HITs
## This keeps HITs from "piling up" on a slow day
## It ensures that A) HIT appears at the top of the list, B) workers won't accidentally accept HIT twice
# expirehits <- function() {
# ExpireHIT(
# annotation = myannotation,
# sandbox = sandbox_val
# )
#}
##### Step 3: Execute a loop that runs createhit/expirehit functions every hour, and it will log the output to a file
## Define number of times to post the HIT (totalruns)
totalruns <- 2
counter <- 0
## Define log file (change the location as appropriate)
logfile <- file("/Users/kinga.makovi/Dropbox/Bias_Experiment/MTurk/logfile.txt", open="a")
sink(logfile, append=TRUE, type="message")
## Run loop (note: interval is hourly, but can be changed in Sys.sleep)
repeat {
message(Sys.time())
createhit()
Sys.sleep(10)
#expirehits()
counter = counter + 1
if (counter == totalruns){
break
}
}
## To stop the loop before it finishes, click the "STOP" button
## To stop logging, run sink()
You can't see HITs that are created via the API (through MTurkR or otherwise) in the requester website. It's a "feature". You'll have to access the HITs through MTurkR (e.g., SearchHITs() and GetHIT()).

Error running R Instagram example from R-Bloggers?

I'm getting an error running the R Instagram query example here: https://www.r-bloggers.com/analyze-instagram-with-r/
I'm guessing it has something to do with my Instagram client (status is "Sandbox Mode"), but not sure what to do. Here's the R code and output:
Code:
require(RCurl)
require(httr)
full_url <- oauth_callback()
full_url <- gsub("(.*localhost:[0-9]{1,5}/).*", x=full_url, replacement="\1")
print(full_url)
app_name <- "teamusainrio"
client_id <- "a36424058cdf424c8e8b2d5cc2af1b15"
client_secret <- "398863caad6a4171ad10eb201870065b"
scope = "basic"
instagram <- oauth_endpoint(
authorize = "https://api.instagram.com/oauth/authorize",
access = "https://api.instagram.com/oauth/access_token")
myapp <- oauth_app(app_name, client_id, client_secret)
ig_oauth <- oauth2.0_token(instagram, myapp,scope="basic", type = "application/x-www-form-urlencoded",cache=FALSE)
Output:
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
Input:
tmp <- strsplit(toString(names(ig_oauth$credentials)), '"')
token <- tmp[[1]][4]
username <- "therock"
user_info <- fromJSON(getURL(paste('https://api.instagram.com/v1/users/search?q=',username,'&access_token=',token,sep="")),unexpected.escape = "keep")
received_profile <- user_info$data[[1]]
Output/error:
Error in user_info$data[[1]] : subscript out of bounds
If I run the query from the above code directly into my browser,
https://api.instagram.com/v1/users/search?q=therock&access_token=511932783.a364240.562161d569354bf78b043c98cf938235
I receive the following:
{"meta": {"code": 200}, "data": []}

Resources