首页 > 解决方案 > 在 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)

标签: rcurlhttrnotion-api

解决方案


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.


推荐阅读