Suggestions needed for building R server REST API's that I can call from external app?

后端 未结 2 696
醉酒成梦
醉酒成梦 2020-12-24 14:14

I\'ve seen lots of articles about consuming data in R from other RESTful API services, but I have really struggled to find any articles about the reverse. I\'m interested i

相关标签:
2条回答
  • 2020-12-24 15:00

    You can use httpuv to fire up a basic server then handle the GET/POST requests. The following isn't "REST" per se, but it should provide the basic framework:

    library(httpuv)
    library(RCurl)
    library(httr)
    
    app <- list(call=function(req) {
    
      query <- req$QUERY_STRING
      qs <- httr:::parse_query(gsub("^\\?", "", query))
    
      status <- 200L
      headers <- list('Content-Type' = 'text/html')
    
      if (!is.character(query) || identical(query, "")) {
        body <- "\r\n<html><body></body></html>"
      } else {
        body <- sprintf("\r\n<html><body>a=%s</body></html>", qs$a)
      }
    
      ret <- list(status=status,
                  headers=headers,
                  body=body)
    
      return(ret)
    
    })
    
    message("Starting server...")
    
    server <- startServer("127.0.0.1", 8000, app=app)
    on.exit(stopServer(server))
    
    while(TRUE) {
      service()
      Sys.sleep(0.001)
    }
    
    stopServer(server)
    

    I have the httr and RCurl packages in there since you'll probably end up needing to use some bits of both to parse/format/etc requests & responses.

    0 讨论(0)
  • 2020-12-24 15:04

    node-rio provides a way to talk to rserve (a TCP/IP server that allows the use of R functions) from node.js.

    Here is an example of use (from the documentation):

    var rio = require('rio');
    rio.evaluate("as.character('Hello World')");
    
    0 讨论(0)
提交回复
热议问题