Using a JSON array in a POST request [duplicate]
Asked Answered
F

1

7

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?

Folks answered 8/8, 2016 at 13:24 Comment(3)
You and @marty_c might want to collaborate on a pkg. But why not write a pkg that syncs the data and then does all the processing locally vs hit an API server? it'll be way faster & more efficient in the long run.Homesteader
thanks for this contact. my plan in the long run was to query the data locally. the file holding the entire data seems pretty large so including this in the package is out of question. but it could be downloaded separately.Folks
You can also put any JSON array into something that will pass through r with the fromJSON() function from the httr package.Scissor
D
14

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)
Doty answered 8/8, 2016 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.