使用 R 构建 RESTful API

Building RESTful API using R

我正在考虑使用编程语言 R 构建一个 RESTful API,主要是为了将我的机器学习模型以 API格式。 我知道有一些选项,例如导出到 PMML、PFA 和使用其他语言来处理 API 部分。但是,我想坚持使用相同的编程语言,想知道 R 中是否有类似 Flask/Django/Springbook 的框架?

我看了一下 servr/shiny,但我真的不认为 RESTful 是它们的设计目的。 R中有没有更好用的更好的解决方案?

我有两种选择供您选择:

plumber

plumber allows you to create a REST API by decorating your existing R source code with special comments.

一个小示例文件:

# myfile.R

#* @get /mean
normalMean <- function(samples=10){
  data <- rnorm(samples)
  mean(data)
}

#* @post /sum
addTwo <- function(a, b){
  as.numeric(a) + as.numeric(b)
}

从 R 命令行:

> library(plumber)
> r <- plumb("myfile.R")  # Where 'myfile.R' is the location of the file shown above
> r$run(port=8000)

有了这个你会得到这样的结果:

$ curl "http://localhost:8000/mean"
 [-0.254]
$ curl "http://localhost:8000/mean?samples=10000"
 [-0.0038]

Jug

Jug is a small web development framework for R which relies heavily upon the httpuv package. It’s main focus is to make building APIs for your code as easy as possible. It is not supposed to be either an especially performant nor an uber stable web framework. Other tools (and languages) might be more suited for that. It’s main focus is to easily allow you to create APIs for your R code. However, the flexibility of Jug means that, in theory, you could built an extensive web framework with it.

它非常容易学习并且有 nice vignette

一个 Hello-World 示例:

library(jug)

jug() %>%
  get("/", function(req, res, err){
    "Hello World!"
  }) %>%
  simple_error_handler_json() %>%
  serve_it()

这是为那些想要比较 API 开发与 R - plumber、Rserve 和 rApache 的人准备的。

基本上,并发请求按 httpuvplumber 中排队,因此它本身并不高效。作者推荐多个 docker 容器,但它可能很复杂并且需要资源。

还有其他技术,例如 RserverApacheRserve 分叉进程,可以配置 rApache 预分叉以处理并发请求。

请参阅以下帖子进行比较

https://www.linkedin.com/pulse/api-development-r-part-i-jaehyeon-kim/ https://www.linkedin.com/pulse/api-development-r-part-ii-jaehyeon-kim/

添加到此答案列表中:

一定要看看 Jeroen Ooms 的 OpenCPU

好处:

  1. 简单明了:opencpu服务器上安装的任何R包都可以通过http调用。

  2. 只需专注于创建 R 包,剩下的由 opencpu 处理。

  3. 您可以return一个关系table结果,一个单个值甚至指针(又名临时会话密钥)到 R 对象 [想象一个巨大的 object/dataset,您可以从其他更有限的平台 process/manipulate ;) ]

  4. CI/CD,您的包裹托管在 Github.

  5. 如果您使用的是服务器版本,opencpu 通过利用 Nginx 缓存和负载平衡.

    设计为并发和异步
  6. 使用 AppArmor 在 Ubuntu 上实施 安全。或者如果你使用 fedora,你可以设置 public-private 证书身份验证,感谢后端的 Apache 服务器。感谢 rApache!

  7. 上面太复杂了: 你也可以在你的本地机器上使用opencpu::ocpu_start_app()启动一个单一的用户会话并提供你的功能(缺点是安全)

  8. 需要用户界面?只需使用 javascript 创建一个 UI,将其存储在 R 包的 www 文件夹中,用户就可以在他们的网络浏览器上打开它并使用您的功能。

这 post 不公平地对待 opencpu。我真的建议您阅读他在 OpenCPU

顶部的链接

玩玩 https://cloud.opencpu.org/ocpu/test or https://www.opencpu.org/apps.html