r - 在 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)
解决方案
This question is a bit difficult to answer, since you have the access key and therefore nobody can test code to make sure it works. However, in terms of simply translating the curl call to httr
code, I think the following code will do so.
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"
)
In terms of defining a function that creates the body dynamically, that's simply a question of formatting the filters similarly to the above example.
推荐阅读
- python - 每次在循环中调用 Python 函数参数时,如何更新它?
- r - 根据 R 中的 id 和 year 列创建增量列 year
- reactjs - 如何发送带有查询的 Apollo 请求(graphql)?
- javascript - 确定某物是否是 JavaScript 中的普通对象的方法
- laravel - Laravel 8 中的 Route::get 格式
- java - mockito spy 没有像我预期的那样行事
- arrays - 如何在 json 模式中添加所需的子数组?
- sql - 在 ORACLE 上从表 A 更新到表 B
- shell - 使用正则表达式将 shell 中的日志文件过滤到变量中
- arrays - Julia 索引数组的奇怪答案