Search code examples
jsonrhttpposthttr

Using a JSON array in a POST request


I'm writing an API wrapper to query UK postcodes using httr package and everything works fine when I use GET requests. I'm slightly lost when it comes to using a POST request.

Here's what the documentation of the API says:

Accepts a JSON object containing an array of postcodes. Returns a list of matching postcodes and respective available data.

Accepts up to 100 postcodes.

POST https://api.postcodes.io/postcodes?q=[postcode]

Post Data

This method requires a JSON object containing an array of postcodes to be posted. E.g.

{ "postcodes" : ["PR3 0SG", "M45 6GN", "EX165BL"] }

I tried the following:

library(httr)

pc_json <- '{
  "postcodes" : ["PR3 0SG", "M45 6GN", "EX165BL"]
}'

r <- POST(paste0("https://api.postcodes.io/postcodes?q=", pc_json, encode = "json"))

But it returns this:

$status 1 400

$error 1 "Invalid JSON submitted. You need to submit a JSON object with an array of postcodes or geolocation objects"

The same happens when I trim the array and use this:

r <- POST("https://api.postcodes.io/postcodes?q=EX165BL")
content(r)

I read similar threads here and here, but they didn't make my problem any easier to solve.

Any ideas how to fix it?


Solution

  • Your almost there just need to format the postcodes as a list and use the body argument of POST then encode as json:

    library(httr)
    
    pc_json <- list(
      postcodes = c("PR3 0SG", "M45 6GN", "EX165BL")
    )
    res <- POST("https://api.postcodes.io/postcodes"
                , body = pc_json
                , encode = "json")
    appData <- content(res)