# cd ~/iCloud/website/data; Rscript --vanilla _update_qmd_folder.R bls only=api.qmd# sh ~/iCloud/website/website_short.shhere::i_am("data/bls/api.qmd")source(here::here("code", "R-markdown", "init_insee.R"))# The blsAPI package (mikeasilva/blsAPI, GitHub-only, archived from CRAN in# 2023) used to wrap these calls. It is replaced here by direct httr/jsonlite# requests against the public BLS API v1 (no registration key -- limits: 25# series and 10 years per request, 25 requests/day), matching the pattern# the other api.qmd pages use.bls_series <-function(seriesid, startyear =NULL, endyear =NULL) { base <-"https://api.bls.gov/publicAPI/v1/timeseries/data/"if (length(seriesid) ==1&&is.null(startyear) &&is.null(endyear)) { resp <- httr::GET(paste0(base, seriesid)) } else { body <-list(seriesid =as.list(seriesid))if (!is.null(startyear)) body$startyear <-as.character(startyear)if (!is.null(endyear)) body$endyear <-as.character(endyear) resp <- httr::POST(base,body = jsonlite::toJSON(body, auto_unbox =TRUE), httr::content_type_json()) } parsed <- httr::content(resp, "text", encoding ="UTF-8") |> jsonlite::fromJSON(flatten =TRUE)if (!identical(parsed$status, "REQUEST_SUCCEEDED"))stop(paste(parsed$message, collapse ="; ")) series <- parsed$Results$series purrr::map_dfr(seq_len(nrow(series)), function(i) { d <- series$data[[i]]if (is.null(d) ||length(d) ==0) return(tibble::tibble()) tibble::as_tibble(d) |> dplyr::transmute(seriesID = series$seriesID[i], year, period, periodName,value =as.numeric(value)) |> dplyr::arrange(year, period) })}# QCEW slices are served as plain CSV from a separate endpoint (no key).bls_qcew_industry <-function(year, quarter, industry) { readr::read_csv(sprintf("https://data.bls.gov/cew/data/api/%s/%s/industry/%s.csv", year, quarter, industry),show_col_types =FALSE)}
data <-bls_series("LAUCN040010000000005")data |>print_table_conditional()
California Unemployment rate
One (very) annoying limitation of the keyless BLS API (v1) is that you can only retrieve up to 10 years of data per request (20 years with a v2 registration key).
Code
data <-bls_series(c("LASST050000000000003", "LASST060000000000003"),startyear =2009,endyear =2018)data |>head(10) |>print_table_conditional()
seriesID
year
period
periodName
value
LASST050000000000003
2009
M01
January
7.0
LASST050000000000003
2009
M02
February
7.3
LASST050000000000003
2009
M03
March
7.6
LASST050000000000003
2009
M04
April
7.8
LASST050000000000003
2009
M05
May
7.9
LASST050000000000003
2009
M06
June
7.9
LASST050000000000003
2009
M07
July
7.9
LASST050000000000003
2009
M08
August
7.8
LASST050000000000003
2009
M09
September
7.8
LASST050000000000003
2009
M10
October
7.8
BLS QCEW
Code
# Example: Construction data (industry 1012) for the first quarter of 2017Construction <-bls_qcew_industry(year ="2017", quarter ="1", industry ="1012")Construction |>head(10) |>print_table_conditional()