问题描述
让我们说说有REST API的R代码,使用的是“管道工”包。 这是它的功能。
#' Date of sale
#' @get /date_of_sale
#' @param auth_key Auth key
#' @param user_id User ID
#' @example https://company.com/date_of_sale?auth_key=12345&user_id=6789
function(auth_key,user_id) {
# ...
}
假设还有另一个R脚本使用对此服务器的API请求
api_string <- "https://company.com/date_of_sale?auth_key=12345&user_id=6789"
date_of_sale <- jsonlite::fromJSON(api_string)
是否可以在第二个脚本中获得参数“ auth_key”和“ user_id”的描述,以全面解释每个参数的含义?例如,为“ auth_key”获取字符串“ Auth key”?还是完全有可能访问功能“ date_of_sale”元数据?
感谢任何想法吗?
解决方法
使用包含您提供的内容的文件plumber.R
。假设它在工作目录中。
在R
pr_read <- plumber::pr("plumber.R")
spec <- pr_read$getApiSpec()
spec$paths$`/date_of_sale`$get$parameters
spec
是一个R列表,其结构与OpenAPI文档相同。
如果您无权访问API水暖工文件,但您的API正在可以访问的地方运行。
spec <- jsonlite::fromJSON("{api_server}/openapi.json",simplifyDataFrame = FALSE)
spec$paths$`/date_of_sale`$get$parameters
再次遵循OpenAPI文档标准。
,由于这是一个API GET请求,因此除非您在API响应中明确包含该变量,否则您将无法访问该变量的描述。
我纯粹是为这个问题学习了一些R脚本,我想这就是您准备JSON API响应的方式。
您可以在JSON请求中执行类似的操作。
library(rjson)
auth_key <- "some_key";
user_id <- "340";
x <- list(auth_key = list(
type = typeof(auth_key),lenght = length(auth_key),attributes = attributes(auth_key),string = auth_key
),user_id = list(
type = typeof(user_id),lenght = length(user_id),attributes = attributes(user_id),string = user_id
),data = "your_data"
);
#x
json <- toJSON(x,indent=0,method="C" )
fromJSON( json )
您可能想看看这些。 https://stat.ethz.ch/R-manual/R-devel/library/base/html/typeof.html https://ramnathv.github.io/pycon2014-r/learn/structures.html https://rdrr.io/cran/rjson/man/toJSON.html https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/attributes