epo3 epo3 - 1 year ago 103
HTTP Question

Using a JSON array in a POST request

I'm writing an API wrapper to query UK postcodes using

package and everything works fine when I use
requests. I'm slightly lost when it comes to using a

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:


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")

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

Any ideas how to fix it?

Answer Source

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


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)