Search code examples
rgeojsonr-sfhttr

R httr POST request for native-lands.ca


I am attempting a Polygon Overlap (POST request) from: https://native-land.ca/resources/api-docs/

What I have below returns an empty list:

library(sf)
library(geojsonsf)
library(httr)

# Create a polygon
lon = c(-114.88984, -114.05445)
lat = c(48.99889,49.46062)
poly_df = data.frame(lon, lat)

poly <- poly_df %>% 
  st_as_sf(coords = c("lon", "lat"), 
           crs = 4326) %>% 
  st_bbox() %>% 
  st_as_sfc()  %>%
  st_as_sf

poly$id=1:length(poly)

# Convert sf into geoJSON
geo <-  sf_geojson(poly)

# Set up POST request
body <- list(maps = "territories", polygon_geojson = geo)
url <- "https://native-land.ca/wp-json/nativeland/v1/api/index.php"
r <- POST(url, body = body)

# View request
content(r, "text") 

I am not sure what I am missing here...


Solution

  • Your JSON is not properly formed. Your body is an R list. There's probably a better way to do this, but

    body <- paste0('{"maps" : "territories", "polygon_geojson" :', geo, '}')
    

    works.