在单个R代码中从设备获取多个api调用 [英] Get multiple api calls from a device in a single R code
问题描述
我目前正在从设备的api中检索一些数字数据.该代码可以完美运行而没有错误,但是现在我想在一个代码中从多个设备中获取数据,即如果我没有记错的话,可以进行多个API调用.由于有50台设备,因此通话次数将超过50.
I am currently retrieving some numeric data from an api of a device. The code runs perfectly without errors however NOW i want to fetch data from multiple devices in a single code i.e multiple api calls if i am not wrong. These would be more than 50 calls since there are 50 devices.
我目前正在为一台设备运行以下代码:
I am running the following code curently for one device :
url <-"https://example.com/api/GetDataBynum?num=ABCDevice.device#.parameter"
geturl <-httr::GET(url,add_headers(.headers=c('key'='')))
apidetails1<-content(geturl,"text", encoding ="UTF-8")
#和这个用于第二个设备号,依此类推,效率不高
#and this one for second device number and so on which is inefficient
url2 <-"https://example.com/api/GetDataBynum?num=ABCDevice.device#.parameter"
geturl2 <-httr::GET(url2,add_headers(.headers=c('key'='')))
apidetails2<-content(geturl2,"text", encoding ="UTF-8")
有没有办法在单个代码中运行多个api?
Is there any way to run multiple apis in single code ?
推荐答案
创建url的向量,并在 lapply
中使用它:
Create a vector of url's and use it in lapply
:
library(httr)
url <- sprintf('https://example.com/api/GetDataBynum?num=ABCDevice.device%s.parameter', data$dataf)
lapply(urls, function(x) {
geturl <- GET(x,add_headers(.headers=c('key'='')))
content(geturl,"text", encoding ="UTF-8")
}) -> result
如果要将数据合并到一个数据框中,可以执行结果<-do.call(rbind,result)
.
If you want to combine the data into one dataframe you can do result <- do.call(rbind, result)
.
这篇关于在单个R代码中从设备获取多个api调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!