Making Filtered API Requests Using R

I was wondering if there was a way to send API requests that return only a filtered set of records based upon specific conditions. You can read about how Knack has made this possible here.

In this post I want to share how I translated the JavaScript code presented by Knack into R. You can see the code I used to retrieve only the records specified within a date range.

# Load dependent packages
library(jsonlite)
library(httr)

# Set the api base url
api_url <-
  "https://api.knack.com/v1/objects/object_23/records"

# Set boundaries for date range
# The date formatting is necessary
date_start <- format(as.Date('2021-11-01'), "%m/%d/%Y")
date_end <- format(as.Date('2021-11-30'), "%m/%d/%Y")

# Set filters
# Refer to the Knack Documentation for more details
filters <- list(match = "and",
                rules = data.frame(
                  field = "field_170",
                  operator = c("is after", "is before"),
                  value = c(date_start, date_end)
                ))

# Convert filters list to JSON and URL encode
filters_string <- toJSON(filters, auto_unbox = TRUE, pretty = TRUE)
api_url <-
  paste0(api_url,
         '?rows_per_page=1000&filters=',
         URLencode(filters_string))

# Send the GET request
result <- GET(
  api_url,
  add_headers(
    "X-Knack-Application-Id" = "YOUR APP ID",
    "X-Knack-REST-API-Key" = "YOUR APP API KEY"
  )
)

# Retrieve the result
data <- fromJSON(content(result, as = "text"))

If you have any questions about how to modify this to suit your own needs, please let me know in the comments.

2 Likes