1

I am trying to "translate" the curl call below, so that I can make an API call with R (using httr), with no luck. I have tried curlconverter and using the suggestion here. However, the API I want to access has multiple layers, and parenthesis are all over the place, which complicate conversion. Any suggestions for a function that will translate this recurring logic dynamically?

curl call:

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"
        }
      ]
    }'

Desired outcome (function)

api_call(page, token, filters)
eflores89
  • 339
  • 2
  • 10
  • 27

1 Answers1

2

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.

Daniel Molitor
  • 644
  • 4
  • 11