#Reference: https://westus.dev.cognitive.microsoft.com/docs/services/56332331778daf02acc0a50b/operations/58076bdadcf4c40708f83791
key <- "d23652ea9f994cd287f93775666a34f7"
interpret_query <- function(query) {
query <- URLencode(query)
api_url <- paste("https://westus.api.cognitive.microsoft.com/academic/v1.0/interpret?query=", query, sep ="")
#Setting key value, will throw error if env var not set
key <- get_academic_key()
#Sending request
result <- httr::GET(api_url, httr::add_headers(.headers = c("Ocp-Apim-Subscription-Key" = key)))
#Throwing error if request does not return json
if (httr::http_type(result) != "application/json") {
stop("API did not return json", call. = FALSE)
}
#Converting JSON to R-usable object
output <- httr::content(result)
#Throwing error if status code != 200
if (httr::status_code(result) != 200) {
stop(
paste(
"API request failed.\nStatus code:",
output$statusCode, "\nMessage:",
output$message
),
call. = FALSE
)
}
n <- NROW(output)
#Coverting output to a dataframe
#output <- data.frame(matrix(unlist(output), nrow = n, byrow = T))
#names(output) <- c("Id", "Language", "Kind", "Specification", "Implementation")
output
}
evaluate <- function(query) {
expr <- interpret_query(query)
api_url <- paste("https://westus.api.cognitive.microsoft.com/academic/v1.0/evaluate?expr=", URLencode(expr$interpretations[[1]]$rules[[1]]$output$value), sep ="")
#Setting key value, will throw error if env var not set
key <- get_academic_key()
#Sending request
result <- httr::GET(api_url, httr::add_headers(.headers = c("Ocp-Apim-Subscription-Key" = key)))
#Throwing error if request does not return json
if (httr::http_type(result) != "application/json") {
stop("API did not return json", call. = FALSE)
}
#Converting JSON to R-usable object
output <- httr::content(result)
#Throwing error if status code != 200
if (httr::status_code(result) != 200) {
stop(
paste(
"API request failed.\nStatus code:",
output$statusCode, "\nMessage:",
output$message
),
call. = FALSE
)
}
n <- NROW(output)
#Coverting output to a dataframe
#output <- data.frame(matrix(unlist(output), nrow = n, byrow = T))
#names(output) <- c("Id", "Language", "Kind", "Specification", "Implementation")
output
}
get_academic_key <- function() {
key <- Sys.getenv('KEY_A')
if (identical(key, "")) {
stop("Please set env var KEY_A to your key for the Academic Search APIS. Key provided by Microsoft (https://www.microsoft.com/cognitive-services)",
call. = FALSE)
}
key
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.