Trying to retrieve Telraam data using R

I am trying to use the API with R but have difficulties retrieving the data from the server.

I tried:

library(httr)
library(jsonlite)
library(tidyverse)
library(hrbrthemes)

get_telraam_data <- function(id = "9000001463",
                       time_start = "2022-10-01 00:00:00Z",
                       time_end = "2022-10-02 00:00:00Z",
                       level = "segments",
                       format = "per-hour") {
  
  request_body <- data.frame(
    id = id,
    time_start = time_start,
    time_end = time_end,
    level = level,
    format = format
  )

  request_body_json <- toJSON(list(json = request_body), auto_unbox = TRUE)
  
  res <- POST(
    url = sprintf("https://telraam-api.net/v1/reports/traffic"),
    body = request_body_json,
    encode = "json",
    add_headers(.headers = c("X-Api-Key" = "xxx Access Token xxx")),
                verbose()
  )

  stop_for_status(res)

  content(res, as="text", encoding="UTF-8") %>%
    fromJSON(flatten=TRUE) %>%
    as_tibble() %>%
    readr::type_convert()
}

This leads to a bad request.
Error in get_telraam_data() : Bad Request (HTTP 400).

Where am I wrong?

This is an interesting question. Most of us aren’t familiar with R but it seems that the parameters are correct. I assume you entered your API key correctly?

I wonder if anyone else has any ideas? I think @Romain_Dalston might have some skills in this area? Any other data / R specialists who can assist with this syntax?

So the issue seems to be with the body of the request. Rather than passing the body as a JSON, you can generate the body (somewhat inelegantly) with paste0. This was a pain to get right with all the escaped and control characters, but this seems to work now:

get_telraam_data <- function(id = "348917",
                             time_start = "2020-10-30 07:00:00Z",
                             time_end = "2020-10-30 09:00:00Z",
                             level = "segments",
                             format = "per-hour") {
  
  request_body <- paste0("{\r\n",
                         "\"id\": \"", id, "\",\r\n",
                         "\"format\": \"", format, "\",\r\n",
                         "\"time_start\": \"", time_start, "\",\r\n",
                         "\"time_end\": \"", time_end, "\",\r\n",
                         "\"level\": \"", level, "\"\n}")
  
  res <- POST(
    url = sprintf("https://telraam-api.net/v1/reports/traffic"),
    body = request_body,
    add_headers(.headers = c("X-Api-Key" = "xxx"))
  )

  stop_for_status(res)

  content(res, as="text", encoding="UTF-8") |> 
    fromJSON(flatten=TRUE) %>%
    as_tibble() %>%
    readr::type_convert()

}

I don’t know if the issue with passing the body as a JSON is an issue with the API or with httr, but whatever variations I tried, I couldn’t get it to work either.