Skip to content
Field Guide

Python, R & Julia · 10 minutes

The same two calls, in the language you already work in

There are only two requests worth learning: the full history for places you can name, and one latest value for every country inside a region. Everything below is those two, written to the same contract — a tidy frame, the provenance carried on every row, and absence reported rather than quietly dropped.

A scenario first, because the contract exists for a reason

A real request, and the three lines of it that matter more than the fetching.

Somebody asks

“Can I get conflict deaths against GDP per capita, as a scatter?”

A colleague preparing a background note, who has seen the chart elsewhere

GDP per capita, current US dollars

undata/unicef/SPP_GDPPC
Found by
Search, read down to the eighth result
Covers
210 countries · 2024 for every country — a genuine cross-section

Conflict-related deaths per 100,000 population

undata/sdg/VC_DTH_TOTR
Found by
Four graph walks down the SDG framework
Covers
14 countries · 2022, 2023 and 2024

The call this scenario needs

GET /core/api/v2/observation

One value per place across a whole region. The containment expression is evaluated inside the graph, so this is one request rather than a loop over country codes.

Python
import pandas as pd
import requests

BASE = "https://unsd-datacommons.gcp.un-icc.cloud"

PARENT = "Earth"


def latest(variable: str) -> pd.DataFrame:
    """One value per country, with the reference year kept alongside it."""
    # Repeated keys, so a list of tuples rather than a dict.
    params = [
        ("date", "LATEST"),
        ("variable.dcids", variable),
        ("entity.expression", f"{PARENT}<-containedInPlace+{{typeOf:Country}}"),
        ("select", "date"), ("select", "value"),
        ("select", "entity"), ("select", "variable"),
    ]
    r = requests.get(f"{BASE}/core/api/v2/observation", params=params, timeout=30)
    r.raise_for_status()

    by_entity = r.json()["byVariable"][variable]["byEntity"]
    return pd.DataFrame([
        {"entity": entity,
         "year": block["orderedFacets"][0]["observations"][0]["date"],
         "value": block["orderedFacets"][0]["observations"][0]["value"]}
        for entity, block in by_entity.items()
        if block.get("orderedFacets")
    ])


X = "undata/unicef/SPP_GDPPC"
Y = "undata/sdg/VC_DTH_TOTR"

x, y = latest(X), latest(Y)

# An inner join across two agencies keeps only the places that have
# both. Print the three counts before you plot: the join is where
# countries disappear, and it never says so.
points = x.merge(y, on="entity", suffixes=("_x", "_y"))
print(f"x: {len(x):>4} countries")
print(f"y: {len(y):>4} countries")
print(f"both: {len(points):>4} countries   <- every point you will plot")

# Two agencies, two reporting cycles: the years are unlikely to match.
print("x years:", sorted(x["year"].unique()))
print("y years:", sorted(y["year"].unique()))

What the data does that the question did not expect

210 countries, 14 countries, and every point you plot is a country at war

GDP per capita returns 210 countries. The conflict death rate returns 14. The inner join keeps 14, and those 14 are Afghanistan, the Central African Republic, DR Congo, Ethiopia, Iraq, Lebanon, Libya, Mali, Myanmar, the Palestinian Territories, the Philippines, South Sudan, Syria and Ukraine. Norway, Costa Rica and Japan are not zero on this indicator — they are absent from the response entirely, because a country with no conflict files no conflict-death return. A scatter of these two series cannot say anything about whether conflict and income are related across countries, because every peaceful country has been removed from the sample before the chart is drawn. The chart would not be imprecise. It would be answering a different question from the one asked.

python — the whole finding, in six lines
x = latest_in("Earth", "undata/unicef/SPP_GDPPC")   # GDP per capita
y = latest_in("Earth", "undata/sdg/VC_DTH_TOTR")    # conflict deaths /100k

points = x.merge(y, on="entity", suffixes=("_gdp", "_conflict"))

print(len(x), len(y), len(points))      # 210 14 14
print(sorted(names(points["entity"].tolist())))
# ['Afghanistan', 'Central African Republic', 'Congo [DRC]', 'Ethiopia',
#  'Iraq', 'Lebanon', 'Libya', 'Mali', 'Myanmar', 'Palestinian Territories',
#  'Philippines', 'South Sudan', 'Syria', 'Ukraine']

That last list is the whole analysis. Printing the names of the surviving entities — not just the count — is what turns “the join dropped some countries” into “the join kept only countries at war”. The first is a data-quality note. The second stops the chart.

Make it an assertion when the script runs unattended. A monthly refresh that quietly loses a country produces a chart nobody re-reads.

python — fail loudly rather than plot quietly
retained = len(points) / min(len(x), len(y))
assert retained > 0.8, (
    f"join kept {len(points)} of {min(len(x), len(y))} places — "
    "check what the missing ones have in common before plotting"
)

In R the same check is stopifnot(nrow(points) / min(nrow(x), nrow(y)) > 0.8); in Julia, @assert over the same ratio. The discipline is identical and the grammar is the only thing that changes.

If you do plot it, plot it honestly

python — matplotlib, with the sample stated in the title
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7, 5))
ax.scatter(points["value_gdp"], points["value_conflict"])

# Income spans 353 to 7,330 dollars: linear puts eleven of fourteen
# points in the left quarter of the plot.
ax.set_xscale("log")
ax.set_xlabel("GDP per capita, current US$ (2024)")
ax.set_ylabel("Conflict deaths per 100,000 (2022–2024)")

# The sample belongs in the title, not in a footnote nobody screenshots.
ax.set_title(f"Among the {len(points)} countries reporting conflict deaths\n"
             f"({len(x)} countries have GDP per capita)")

for _, row in points.iterrows():
    ax.annotate(row["name"], (row["value_gdp"], row["value_conflict"]),
                fontsize=7, alpha=0.7)

fig.text(0.01, 0.01, "Source: UNICEF and SDG collections via data.un.org",
         fontsize=7, alpha=0.6)

No regression line, deliberately. scipy.stats.linregress will return a slope and a p-value for these fourteen points and both are statements about which countries file conflict-death returns, not about conflict and income.

The full discovery trail for this one — including the two searches that failed and the four graph walks that did not — is on the scenarios page.

The contract, before the code

Three rules. They are what make these snippets longer than a one-liner, and they are the reason the output is publishable.

One row per observation

variable, entity, date, value — long, never wide. Pivot at the point of display, so a new year of data does not change the schema.

The facet rides along

The numbers arrive in data; the unit, observation period and agency arrive separately in facets, keyed by an id on each block. Join them at fetch time or you will lose them.

Empty is reported, not dropped

An entity with no data is silently absent from the response. A function that returns a shorter frame without saying so is how a missing country becomes an invisible one.

Python

Requests and pandas, no client library. This is the module that was run against the live platform while the page was written; the no data for: line below the code is its real output.
undc.py
"""Tidy frames from the UN System Data Commons. No API key required."""

import pandas as pd
import requests

BASE = "https://unsd-datacommons.gcp.un-icc.cloud"
SESSION = requests.Session()
# Identify yourself. This is unmetered public infrastructure with no quota
# protecting it from you, so a contactable user agent is basic courtesy.
SESSION.headers["User-Agent"] = "my-office-analysis (you@example.org)"


def series(variables: list[str], entities: list[str]) -> pd.DataFrame:
    """Full time series for every (variable, entity) pair, one row per observation."""
    payload = {"variables": variables, "entities": entities}
    r = SESSION.post(f"{BASE}/api/observations/series", json=payload, timeout=30)
    r.raise_for_status()
    body = r.json()
    facets = body.get("facets", {})

    rows, empty = [], []
    for variable, by_entity in body["data"].items():
        for entity, block in by_entity.items():
            observations = block.get("series") or []
            if not observations:
                empty.append((variable, entity))   # absent is not zero
                continue
            facet = facets.get(block.get("facet"), {})
            for obs in observations:
                rows.append({
                    "variable": variable,
                    "entity": entity,
                    "date": obs["date"],
                    "value": obs["value"],
                    "unit": facet.get("unitDisplayName"),
                    "period": facet.get("observationPeriod"),
                    "source": facet.get("provenanceUrl"),
                })

    if empty:
        print(f"no data for: {empty}")

    frame = pd.DataFrame(rows)
    if frame.empty:
        return frame
    # date is "2024", sometimes "2024-06". Only the year is safe to make a number;
    # parsing it as a date would invent a day nobody measured.
    frame["year"] = frame["date"].str.slice(0, 4).astype(int)
    return frame.sort_values(["variable", "entity", "date"], ignore_index=True)
using it
>>> df = series(
...     ["undata/sdg/VC_DTH_TOTN"],
...     ["country/SSD", "country/COD", "country/ATA"],
... )
no data for: [('undata/sdg/VC_DTH_TOTN', 'country/ATA')]

>>> df.head(2)
                 variable       entity  date  value    unit period                                  source  year
0  undata/sdg/VC_DTH_TOTN  country/COD  2015    945  Number    P1Y  https://unstats.un.org/sdgs/dataportal  2015
1  undata/sdg/VC_DTH_TOTN  country/COD  2016    836  Number    P1Y  https://unstats.un.org/sdgs/dataportal  2016

Antarctica is in the request on purpose. It resolves to a real place, the platform answers 200, and the response simply has no block for it. A loop that indexes straight into body["data"][variable][entity] raises KeyError here; one that uses .get without reporting returns a frame two countries wide and says nothing. Neither is what you want in a script somebody else will run.

In a notebook, replace the print with a warnings.warn or an assertion. In a pipeline, raise: a country that has silently vanished from a monthly report is worth failing a job over.

the regional call — one latest value per country
def latest_in(region: str, variable: str, place_type: str = "Country") -> pd.DataFrame:
    """One latest value per child place of `region` — a ranking, in one request."""
    # Repeated keys, so a list of tuples rather than a dict. requests encodes
    # the arrows and braces in the expression for you; hand-built URLs do not,
    # and an unencoded -> comes back as HTTP 400 with no explanation.
    params = [
        ("date", "LATEST"),
        ("variable.dcids", variable),
        ("entity.expression", f"{region}<-containedInPlace+{{typeOf:{place_type}}}"),
        ("select", "date"), ("select", "value"),
        ("select", "entity"), ("select", "variable"),
    ]
    r = SESSION.get(f"{BASE}/core/api/v2/observation", params=params, timeout=30)
    r.raise_for_status()
    body = r.json()
    facets = body.get("facets", {})

    rows = []
    for var, by_entity in body["byVariable"].items():
        for entity, block in by_entity["byEntity"].items():
            for facet_block in block.get("orderedFacets", []):
                facet = facets.get(facet_block["facetId"], {})
                for obs in facet_block["observations"]:
                    rows.append({
                        "variable": var, "entity": entity,
                        "date": obs["date"], "value": obs["value"],
                        "unit": facet.get("unitDisplayName"),
                        "source": facet.get("provenanceUrl"),
                    })
                break   # orderedFacets is ranked — the first is the preferred source

    frame = pd.DataFrame(rows)
    if frame.empty:
        return frame
    return frame.assign(name=names(frame["entity"].tolist()))


def names(dcids: list[str]) -> list[str]:
    """Human-readable place names, so a chart does not read `country/SSD`."""
    r = SESSION.post(f"{BASE}/api/place/name", json={"dcids": list(set(dcids))}, timeout=30)
    r.raise_for_status()
    lookup = r.json()
    return [lookup.get(d, d) for d in dcids]

The shape is different, and deliberately so. This endpoint nests one more level: byVariable → byEntity → orderedFacets[] → observations[]. The extra level exists because more than one agency may publish the same variable for the same place, and the list is ranked. Taking the first is the right default; iterating all of them and keeping facetId is what you do when the point of the analysis is that two sources disagree.

the check to run before you call it a cross-section
hdi = latest_in("SouthernAsia", "undata/undphdro/HDI_hdi")
hdi["date"].unique()          # array(['2023'], dtype=object) — one year, clean

hom = latest_in("africa", "undata/unodc/VIC_HOM_RT")
hom["date"].unique()          # 11 distinct years, 2009–2025 — a ranking, not a snapshot

Both were run live. The first genuinely is a cross-section because HDI is a modelled composite on one annual cycle; the second is national administrative reporting and spans more than a decade. The query is identical. Only the data generating process differs, and only this check tells you which you have.

Or let a package do the plumbing

undata: the same contract, already written

undata is a Python package built on everything this guide found: it routes around the firewall, knows the UN M49 countries, regions and groups by name, takes SDG numbers, keeps the source and year on every row, and reports missing countries and mixed years as warnings instead of dropping them. It also runs the SDG progress assessment, draws publication-ready charts, and ships an MCP connector. It is unofficial, written by the author of this guide.

python — pip install undata
import undata as un

table = un.latest("3.1.1", "Southern Asia")   # an SDG number, a region by name
print(un.describe(table))                     # the finding in words, years included
un.save(table, "maternal-mortality.xlsx")     # sources and gaps on their own sheets

un.progress("3.1.1", "LDCs", better="lower", target=70)   # on track for 2030?

PyPI ↗ · Twelve use cases with real output ↗ · API reference ↗

R

httr2 and purrr. Same contract, same output columns — so a colleague can hand you either frame and the rest of the analysis is unchanged.
undc.R
library(httr2)
library(purrr)
library(dplyr)
library(tibble)

BASE <- "https://unsd-datacommons.gcp.un-icc.cloud"

undc_series <- function(variables, entities) {
  resp <- request(BASE) |>
    req_url_path("/api/observations/series") |>
    req_body_json(list(variables = variables, entities = entities)) |>
    req_user_agent("my-office-analysis (you@example.org)") |>
    req_retry(max_tries = 3) |>
    req_perform()

  # simplifyVector = FALSE keeps the nested lists as lists. Let jsonlite
  # simplify and a single-country response collapses into a different shape
  # from a multi-country one, which is a very unpleasant bug to find later.
  body <- resp_body_json(resp, simplifyVector = FALSE)
  facets <- body$facets

  rows <- imap(body$data, function(by_entity, variable) {
    imap(by_entity, function(block, entity) {
      obs <- block$series
      if (is.null(obs) || length(obs) == 0) {
        warning("no data for ", variable, " / ", entity, call. = FALSE)
        return(NULL)
      }
      facet <- facets[[block$facet]]
      tibble(
        variable = variable,
        entity   = entity,
        date     = map_chr(obs, "date"),
        value    = map_dbl(obs, "value"),
        unit     = facet$unitDisplayName  %||% NA_character_,
        period   = facet$observationPeriod %||% NA_character_,
        source   = facet$provenanceUrl     %||% NA_character_
      )
    }) |> list_rbind()
  }) |> list_rbind()

  if (nrow(rows) == 0) return(rows)

  rows |>
    mutate(year = as.integer(substr(date, 1, 4))) |>
    arrange(variable, entity, date)
}
the regional call in R
undc_latest_in <- function(region, variable, place_type = "Country") {
  expression <- sprintf("%s<-containedInPlace+{typeOf:%s}", region, place_type)

  resp <- request(BASE) |>
    req_url_path("/core/api/v2/observation") |>
    # .multi = "explode" is the bit that matters: four select= keys, not one
    # comma-joined value. Without it the server returns 400.
    req_url_query(
      date              = "LATEST",
      variable.dcids    = variable,
      entity.expression = expression,
      select            = c("date", "value", "entity", "variable"),
      .multi            = "explode"
    ) |>
    req_perform()

  body   <- resp_body_json(resp, simplifyVector = FALSE)
  facets <- body$facets

  imap(body$byVariable, function(v, variable) {
    imap(v$byEntity, function(e, entity) {
      first <- e$orderedFacets[[1]]          # ranked; first is preferred
      facet <- facets[[first$facetId]]
      tibble(
        variable = variable,
        entity   = entity,
        date     = map_chr(first$observations, "date"),
        value    = map_dbl(first$observations, "value"),
        source   = facet$provenanceUrl %||% NA_character_
      )
    }) |> list_rbind()
  }) |> list_rbind()
}

The one R-specific trap is query encoding. The containment expression contains <- and braces, and four select parameters must arrive as four separate keys. req_url_query(..., .multi = "explode") does both; pasting the URL together by hand does neither, and the error you get back is a bare 400.

%||% comes from purrr (and from base R 4.4 onwards). It is doing real work here: HDI facets carry no unitDisplayName at all, so the field is absent rather than empty, and an unguarded facet$unitDisplayName would return NULL and collapse the tibble column.

list_rbind() rather than the older map_dfr(), which purrr 1.0 superseded. Returning NULL from the inner function is how a country with no data drops out of the bind — after a warning, not silently.

Julia

HTTP.jl, JSON3 and DataFrames. Building the frame column-first keeps the schema concrete, which matters more here than it does in Python.
undc.jl
using HTTP, JSON3, DataFrames

const BASE = "https://unsd-datacommons.gcp.un-icc.cloud"
const AGENT = ["User-Agent" => "my-office-analysis (you@example.org)"]

function undc_series(variables::Vector{String}, entities::Vector{String})
    body = JSON3.write((; variables, entities))
    resp = HTTP.post("$BASE/api/observations/series",
                     ["Content-Type" => "application/json"; AGENT], body)
    payload = JSON3.read(resp.body)

    # Declared up front so every column has a concrete type. Pushing
    # NamedTuples into an untyped vector works until one facet is missing a
    # unit and the eltype quietly becomes Any.
    df = DataFrame(
        variable = String[], entity = String[], date = String[],
        value    = Float64[], year   = Int[],
        unit     = Union{String,Missing}[],
        source   = Union{String,Missing}[],
    )

    for (variable, by_entity) in pairs(payload.data),
        (entity, block)       in pairs(by_entity)

        obs = get(block, :series, nothing)
        if obs === nothing || isempty(obs)
            @warn "no data" variable entity      # absent is not zero
            continue
        end
        facet = payload.facets[Symbol(block.facet)]

        for o in obs
            date = String(o.date)
            push!(df, (String(variable), String(entity), date,
                       Float64(o.value), parse(Int, first(date, 4)),
                       get(facet, :unitDisplayName, missing),
                       get(facet, :provenanceUrl, missing)))
        end
    end

    sort!(df, [:variable, :entity, :date])
end
the regional call in Julia
function undc_latest_in(region::String, variable::String;
                        place_type::String = "Country")
    # A vector of pairs, not a Dict — repeated keys are the whole point, and a
    # Dict would keep only the last select=.
    query = ["date"              => "LATEST",
             "variable.dcids"    => variable,
             "entity.expression" => "$region<-containedInPlace+{typeOf:$place_type}",
             "select" => "date", "select" => "value",
             "select" => "entity", "select" => "variable"]

    resp    = HTTP.get("$BASE/core/api/v2/observation", AGENT; query)
    payload = JSON3.read(resp.body)

    df = DataFrame(variable = String[], entity = String[], date = String[],
                   value = Float64[], source = Union{String,Missing}[])

    for (variable, v) in pairs(payload.byVariable),
        (entity, e)   in pairs(v.byEntity)

        facets = get(e, :orderedFacets, nothing)
        facets === nothing && continue
        first_facet = facets[1]                  # ranked; first is preferred
        facet = payload.facets[Symbol(first_facet.facetId)]

        for o in first_facet.observations
            push!(df, (String(variable), String(entity), String(o.date),
                       Float64(o.value), get(facet, :provenanceUrl, missing)))
        end
    end

    sort!(df, :value, rev = true)
end

JSON3 gives you symbols, and the keys contain slashes. pairs(payload.data) yields Symbol("undata/sdg/VC_DTH_TOTN"), so String(variable) is needed before it goes into a String column. The same applies to the facet id, which is a numeric string in the JSON and therefore payload.facets[Symbol(block.facet)] on the way back.

get(facet, :unitDisplayName, missing) rather than facet.unitDisplayName for the same reason as in R: the field is genuinely absent on some facets, and property access on a JSON3.Object throws rather than returning nothing.

If you prefer working with vectors of NamedTuples, that is fine — DataFrame(rows) accepts them. Declare the element type explicitly if you do, or the first missing unit turns the whole column into Any and every downstream operation gets slower and less type-safe.

The one cross-language trap: repeated query parameters

The regional call sends select= four times and entity.expression with arrows and braces. Every HTTP library expresses that differently, and getting it wrong returns a bare HTTP 400.
How to send repeated query keys in each language
LanguageThe form that worksThe form that fails
Python (requests)params=[("select", "date"), ("select", "value")]params={"select": "date,value"} — one comma-joined key
R (httr2)req_url_query(select = c("date", "value"), .multi = "explode")the default .multi = "error", or paste0() into the URL
Julia (HTTP.jl)query = ["select" => "date", "select" => "value"]query = Dict(...) — the last select wins, the rest are lost
curl--data-urlencode 'select=date' --data-urlencode 'select=value'putting <- and {} in the URL unencoded
Power Query (M)POST the lists in the body with Json.FromValueQuery = [select = {"date","value"}] — a list is not a valid Query value

The last row is why the Power BI page uses the POST form throughout: Power Query's Query record cannot express a repeated key, and building the URL by hand forfeits scheduled refresh.

Cache it — this is unmetered public infrastructure

There is no API key, which means there is no quota standing between an enthusiastic loop and a service the whole system shares.
python — two lines, and a notebook re-run costs nothing
import requests_cache   # pip install requests-cache

# Annual statistics. A day is a conservative TTL; a week is defensible.
SESSION = requests_cache.CachedSession(
    "undc-cache", expire_after=86_400,
    allowable_methods=("GET", "POST"),   # the series endpoint is a POST
)

allowable_methods is the part people miss: requests-cache caches GET only by default, and the series endpoint is a POST, so without it nothing is cached and you will not notice.

The other half of courtesy is batching. Several variables and several entities go in one request and return the cross product; a loop over fifty countries is fifty round trips for a result one containment expression would have fetched. The cookbook makes the same point at more length, and this site obeys it — one request per panel, with a committed snapshot so a reader reloading ten times does not cost the UN ten round trips per chart.

For R, httr2::req_cache() in the pipeline above. For Julia, write the frame to Parquet or Arrow and read it back if the file is newer than your TTL — there is no equivalent drop-in.

A notebook that runs all of this

Standard library only — no pandas, no install, no key. It works in Colab, in Jupyter and as a plain script.

The companion notebook walks the same ground against the live platform: one series, the facet join that gives it meaning, a regional ranking, a graph walk and an MCP call. Nineteen cells, nothing to configure.

What this page leaves you with

Takeaway

Two calls cover almost everything. Named places with full history, or one latest value across a region. Learn their two response shapes and the rest of the API is discovery, not fetching.

Takeaway

Write the empty branch first. Every snippet here reports the entity that came back with nothing, because that is the single most common way an analysis goes quietly wrong — not a crash, a frame that is one country short.

Takeaway

Guard the optional facet fields. unitDisplayName is genuinely absent on some facets. Python .get, R %||%, Julia get(…, missing) — the same defect in three grammars.

Takeaway

Check the reference years before calling it a comparison. One line — df["date"].unique() — separates a cross-section from a ranking that spans a decade. Run it every time.

↑ ↓ to move · Enter to open · A match inside a video opens the lesson at the moment the words are said.