使用R中的httr转换curl调用,并使用多个调用



我正在尝试"翻译";下面的curl调用,这样我就可以用R(使用httr(进行API调用,但运气不好。我试过curlconverter,并在这里使用了这个建议。但是,我要访问的API有多层,括号到处都是,这使转换复杂化。对于一个将动态转换这种重复出现的逻辑的函数,有什么建议吗?

卷曲呼叫:

curl -X POST 'https://api.notion.com/v1/databases/897e5a76ae524b489fdfe71f5945d1af' 
-H 'Authorization: Bearer '"$NOTION_API_KEY"'' 
-H 'Notion-Version: 2021-05-13' 
-H "Content-Type: application/json" 
--data '{
"filter": {
"or": [
{
"property": "In stock",
"checkbox": {
"equals": true
}
},
{
"property": "Cost of next trip",
"number": {
"greater_than_or_equal_to": 2
}
}
]
},
"sorts": [
{
"property": "Last ordered",
"direction": "ascending"
}
]
}'

期望结果(功能(

api_call(page, token, filters)

这个问题有点难回答,因为您有访问密钥,因此没有人可以测试代码以确保它有效。然而,就简单地将curl调用转换为httr代码而言,我认为以下代码可以做到这一点

library(httr)
library(jsonlite)
# Create the body of the POST request
json_body <- list(
"filter" = list(
"or" = list(
list(
"property" = "In stock",
"checkbox" = list(
"equals" = "true"
)
),
list(
"property" = "Cost of next trip",
"number" = list(
"greater_than_or_equal_to" = 2
)
)
)
),
"sorts" = list(
list(
"property" = "Last ordered",
"direction" = "ascending"
)
)
)
# Make post request
request <- POST(
url = "https://api.notion.com/v1/databases/897e5a76ae524b489fdfe71f5945d1af", 
add_headers("Authorization" = paste("Bearer", notion_api_key),
"Notion-Version" = "2021-05-13"),
body = json_body, 
encode = "json"
)

就定义一个动态创建主体的函数而言,这只是一个类似于上面例子的格式化过滤器的问题。

最新更新