import requests
from urllib.parse import urlencode
from io import BytesIO
import geopandas
# set host, like http://localhost:8000, to where your Data Hub is running
DH_HOST = ""
# Your personal API authentication token
# ATTENTION: tokens should not be included in production code!
# I.e, use a environment variable to store the token and set it like this:
# DH_TOKEN = os.environ["DH_TOKEN"]
DH_TOKEN = ""
def dh_shapes(query: dict):
response = requests.get(
f"{DH_HOST}/api/shapes/geometry?{urlencode(query)}",
headers={"X-API-Key": DH_TOKEN}
)
if response.status_code == 200:
gdf = geopandas.read_file(BytesIO(response.content))
d = response.json()
else:
raise Exception(f"Request failed ({response.status_code}): {response.text}")
return gdf
region_gdf = dh_shapes({
"shape_type": "region",
# Simplify geometry to reduce complexity/size in unit of Shapes,
# for WGS84 degree: 0.001 ~> 111.3m
# https://shapely.readthedocs.io/en/latest/manual.html#object.simplify
# "simplify": 0.01
})
# ===== LOAD LIBRARIES =====
library(httr)
library(sf)
# ===== CONFIGURATION =====
# set host, like http://localhost:8000, to where your Data Hub is running
DH_HOST <- ""
# Your personal API authentication token
# ATTENTION: tokens should not be added to production code!
# I.e, use a .Renviron file to store the token and set it like this:
# DH_TOKEN <- Sys.getenv("DH_TOKEN")
DH_TOKEN <- ""
# ===== MAIN FUNCTION =====
dh_shapes <- function(query_params) {
response <- GET(
url = paste0(DH_HOST, "/api/shapes/geometry"),
query = query_params,
add_headers("X-API-Key" = DH_TOKEN)
)
# Check if the request was successful (status code 200)
if (status_code(response) != 200) {
stop(sprintf("Request failed (%d): %s",
status_code(response),
content(response, "text")))
}
# reading GeoJSON
gdf <- st_read(
rawToChar(content(response, "raw")),
quiet = TRUE
)
return(gdf)
}
# ===== EXAMPLE USAGE =====
region_gdf <- dh_shapes(list(
shape_type = "region"
# Simplify geometry to reduce complexity/size in unit of Shapes,
# for WGS84 degree: 0.001 ~> 111.3m
# https://shapely.readthedocs.io/en/latest/manual.html#object.simplify
# "simplify": 0.01
)
)