Spingelhoff
Spingelhoff

Reputation: 1

Why is my request (HTTR2) to the Statistics Canada API returning a 406 Error and how would I fix this?

I wanted to get data from the Statistics Canada API. For some reason, all the requests I send seem to return a 406 error. I'm not entirely sure what I'm doing wrong.

I created the request as follows:

req <- request("https://www150.statcan.gc.ca/t1/wds/rest/getDataFromVectorsAndLatestNPeriods")

resp <- req |>
  req_method("POST") |>
  req_body_json(
    list(
      vectorId = 41690973,
      latestN = 10
    )
  ) |>
  req_perform()

A dry run gives me the following:

POST /t1/wds/rest/getDataFromVectorsAndLatestNPeriods HTTP/1.1
Host: www150.statcan.gc.ca
User-Agent: httr2/1.0.1 r-curl/5.2.1 libcurl/7.81.0
Accept: */*
Accept-Encoding: deflate, gzip, br, zstd
Content-Type: application/json
Content-Length: 34

{"vectorId":41690973,"latestN":10}

The error I get:

Error in `req_perform()`:
! HTTP 406 Not Acceptable.

Am I missing something?

I've tried some packages that target Statistics Canada and they are able to get a proper response so I assume there has to be some formatting issue on my part...

Upvotes: 0

Views: 121

Answers (1)

margusl
margusl

Reputation: 17574

In their request example they send an array with a single object:

POST URL:
https://www150.statcan.gc.ca/t1/wds/rest/getDataFromVectorsAndLatestNPeriods

POST BODY:
[{"vectorId":32164132, "latestN":3}]

Your request is slightly different as it sends just the object,

{"vectorId":41690973,"latestN":10}

Try nesting your payload in another list() to address this:

library(httr2)
req <- request("https://www150.statcan.gc.ca/t1/wds/rest/getDataFromVectorsAndLatestNPeriods")

resp <- req |>
  req_method("POST") |>
  req_body_json(
    list(
      list(
        vectorId = 41690973,
        latestN = 10
      )
    )
  ) |>
  req_perform()

resp_status_desc(resp)
#> [1] "OK"

Upvotes: 2

Related Questions