James Willcox James Willcox - 3 months ago 62
R Question

Accept HTTP Request in R shiny application

I have a shiny app that I have made that needs to get its data from another server, i.e. the other server when the shiny app is opened sends a request to the shiny app to open the app and feed it the data that it needs.

To simulate this I can send the following to the R shiny app when I open the app in firefox:

http://localhost:3838/benchmark-module/?transformerData=data/TransformerDataSampleForShiny.json


This is a simple get request that sends the sting called :
"Transformer Data"
with contents "data/TransformerDataSampleForShing.json" to the shiny app.

When I use the code it works fine:

#(Abridged code, I am only showing the start of the code)
shinyServer(function(input, output) {
jsonFile <- "data/TransformerDataSampleForShiny.json"
JSONdata <- fromJSON(jsonFile)


but when I want to do the exact same thing except rather than hard coding the string "data/TransformerDataSampleForShiny.json" i want to receive that string from the http request above. How do I do this?? I have tried the code:

shinyServer(function(input, output) {
jsonFile <- input$transformerData
JSONdata <- fromJSON(jsonFile)


and I have also tried:

....
jsonFile <- input$TransformerData


but none of these have worked.

SO the main question is, is how do I code to recieve HTTP requests? I would like to receive strings from HTTP GET requests and or JSON files from POST requests.

Just to clarify I DONT want to send post or get requests from R. I want to receive them. I can't use the httr package or the httpRequest package for receiving

Thanks so much!

Answer

You can receive GET requests using session$clientData. An example run the following

library(shiny)
runApp(list(
  ui = bootstrapPage(
    textOutput('text')
  ),
  server = function(input, output, session) {
    output$text <- renderText({
      query <- parseQueryString(session$clientData$url_search)
      paste(names(query), query, sep = "=", collapse=", ")
    })
  }
), port = 5678, launch.browser = FALSE)

and navigate to

http://127.0.0.1:5678/?transformerData=data/TransformerDataSampleForShiny.json

See @Xin Yin answer for a method to expose POST requests.

Comments