Skip to content

Instantly share code, notes, and snippets.

@randyphoa
Last active November 9, 2022 05:20
Show Gist options
  • Save randyphoa/fea7973b6a1a14542c1f05dfd832109c to your computer and use it in GitHub Desktop.
Save randyphoa/fea7973b6a1a14542c1f05dfd832109c to your computer and use it in GitHub Desktop.
R Shiny App
library(httr)
library(shiny)
library(jsonlite)
DEPLOYMENT_ID <- "93562b3a-19d5-42db-a52a-f4846dd7d487"
VERSION <- "2022-09-27"
SPACE_ID = "399a2bce-40b5-457a-8e18-de978043e2c8"
API_KEY = "xxx"
CPD_URL = "https://cpd-cpd.itzroks-550003aw18-rmaez9-6ccd7f378ae819553d37d5f2ee142bd6-0000.au-syd.containers.appdomain.cloud"
USERNAME = "admin"
httr::set_config(httr::config(ssl_verifypeer = FALSE, ssl_verifyhost = FALSE))
getHeaders <- function() {
headers <- c("cache-control"="no-cache", "Content-Type"="application/json")
url <- stringr::str_interp("${CPD_URL}/icp4d-api/v1/authorize")
body <- stringr::str_interp('{"username":"${USERNAME}","api_key":"${API_KEY}"}')
r <- POST(
url,
add_headers(
.headers = headers
),
body=fromJSON(body),
encode="json"
)
token <- httr::content(r)$token
headers <- c("Authorization"=stringr::str_interp("Bearer ${token}"), "Content-Type"="application/json", "Accept"="application/json")
return(headers)
}
ui <- function(req) {
if (identical(req$REQUEST_METHOD, "GET")) {
htmlTemplate("index.html")
} else if (identical(req$REQUEST_METHOD, "POST")) {
body <- rawToChar(req$rook.input$read(-1))
url <- stringr::str_interp("${CPD_URL}/ml/v4/deployments/${DEPLOYMENT_ID}/predictions")
query <- list(version=VERSION)
r <- POST(
url,
add_headers(
.headers = getHeaders()
),
query=query,
body=body,
encode="raw"
)
content <- jsonlite::toJSON(
list(
fields = unlist(httr::content(r)$predictions[[1]]$fields),
values = lapply(httr::content(r)$predictions[[1]]$values, unlist)
)
)
httpResponse(
status = 200L,
content_type = "application/json",
content = content
)
}
}
attr(ui, "http_methods_supported") <- c("GET", "POST")
server <- function(input, output) { }
addResourcePath("static", "static")
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment