Plumber是一个R包,它使用少量特殊的单行注释将您现有的R代码转换为Web API。
什么是Web API?对于某些人来说,API(应用程序编程接口)是听说过但很少见的东西。但是,无论可见与否,API都是日常数字生活的一部分。实际上,即使您当时不认识它,您也可能已经在R中使用了Web API!几个R包只是流行的Web API(例如tidycensus和)的包装gh。Web API是用于在网络上共享信息的框架,最常见的是通过HTTP。
我们来看一个例子。
# plumber.R
#* Echo back the input
#* @param msg The message to echo
#* @get /echo
function(msg=""){
list(msg = paste0("The message is: '", msg, "'"))
}
#* Plot a histogram
#* @png
#* @get /plot
function(){
rand <- rnorm(100)
hist(rand)
}
#* Return the sum of two numbers
#* @param a The first number to add
#* @param b The second number to add
#* @post /sum
function(a, b){
as.numeric(a) + as.numeric(b)
}
创建好这一份代码之后,在R语言的终端输入:
library(plumber)
r <- plumb("plumber.R") # Where 'plumber.R' is the location of the file shown above
r$run(port=8000)
可以使用浏览器或终端访问此URL,以运行R函数并获取结果。例如,http:// localhost:8000 / plot将显示一个直方图,而http:// localhost:8000 / echo?msg = hello将回显提供的“ hello”消息。
- 参考:水管工文档
- RStudio 1.2中的管道工集成
- RViews博客:James Blair的REST API和Plumber
- 视频:Jeff Allen将您的R代码转换为API
- 网络研讨会:Jeff Pipen的Plumber管道API
可能会出现的bug
Error: 'is_present' is not an exported object from 'namespace:lifecycle'
解决方案未知
网友评论