AREC 570 / ECON 530 / Unit 5
Dominitz and Manski, “More Data or Better Data? A Statistical Decision Problem” (Dominitz and Manski 2017)
The organization responsible for the source determines
An application programming interface provides a documented way for R (or other programming languages) to request selected records from that source
R is the programming language that sends each request and holds the returned data. RStudio is the application where you write R code in a script, run it, and see the results
Collecting data with code has three advantages over clicking through a website
Today we will run API requests in RStudio and try short exercises inside these slides
| Step | What happens | Streamflow example |
|---|---|---|
| 1. R function | You call a package function and list what you want | read_waterdata_daily() with a station, a parameter, and dates |
| 2. Request | The package adds those parameters to the service’s web address, called the endpoint | api.waterdata.usgs.gov/...?monitoring_location_id=USGS-06752260¶meter_code=00060 |
| 3. Data service | The agency’s server finds the matching records | USGS Water Data |
| 4. Response | The server returns the records in a format the service chooses: JSON or CSV for tables, GeoTIFF or NetCDF for grids | JSON text, one record per day |
| 5. R object | The package reads that format and returns a data frame, raster, or map layer | 183 rows, one per day |
Each service chooses the formats it offers. R packages read all of them
| Format | What it holds | Today’s examples | R reader |
|---|---|---|---|
| JSON | Records as labeled text | USGS Water Data; Census API; error messages | jsonlite, used inside dataRetrieval and tidycensus |
| CSV | Rows and columns as plain text | CDL acreage; NASA POWER through nasapower |
readr |
GeoTIFF (.tif) |
One grid of values with map coordinates | Cropland Data Layer | terra |
NetCDF (.nc) |
Grids over space and time, with units and metadata | NASA POWER regional request; gridMET | terra, ncdf4 |
| Shapefile, GeoPackage | Points, lines, and polygons | Census tract boundaries | sf |
Tables often travel as JSON or CSV. Grids travel as GeoTIFF or NetCDF, because the same grid written as text would be far larger
The USGS service returns text like this for each day (simplified)
dataRetrieval reads the JSON and turns the records into rows of a data frame
You then work with the data frame; the JSON is never saved unless you save it
format=JSON, CSV, or NETCDFContent-Type: application/json, text/csv, image/tiff, application/x-netcdfThe packages in today’s examples choose a format for you. nasapower, for example, requests CSV
Services use one of three arrangements
A key is a personal credential. Store it in your user environment file and keep it out of shared code and repositories
| Provider | Typical research uses |
|---|---|
| Census Bureau | Population, households, businesses, labor markets, trade |
| Other federal statistical agencies | Prices, income, employment, energy, finance |
| USDA | Production, prices, farm finances, food, soils, forests |
| Environment and natural resources | Water, weather, climate, land cover, pollution, hazards |
| International organizations | Cross-country development, agriculture, trade |
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| American Community Survey | Income, poverty, housing, and commuting by tract or county | tidycensus |
Yes |
| ACS Public Use Microdata | Person and household records | tidycensus |
Yes |
| Decennial Census | Population counts and demographics | tidycensus |
Yes |
| Population Estimates | Annual population, births, deaths, and migration | tidycensus |
Yes |
| SAIPE and SAHIE | County poverty, median income, and uninsured rates | censusapi |
Yes |
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| County and ZIP Business Patterns | Establishments, employment, and payroll by industry | censusapi |
Yes |
| Nonemployer Statistics | Self-employment and small businesses by industry | censusapi |
Yes |
| Economic Census and Annual Business Survey | Sales, ownership, and firm characteristics | censusapi |
Yes |
| Quarterly Workforce Indicators | Hires, separations, and earnings by worker group | censusapi |
Yes |
| LEHD Origin-Destination (LODES) | Where people live and work, by census block | lehdr |
No |
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| International Trade | Monthly imports and exports by product and partner | censusapi |
Yes |
| Economic Indicators | Retail sales, housing starts, and manufacturing | censusapi |
Yes |
| TIGER/Line boundaries | Tract, county, and ZIP code tabulation area maps | tigris |
No |
| Census Geocoder | Assigning addresses to tracts and blocks | tidygeocoder |
No |
Geographic identifiers and boundaries link nearly every source in this catalog
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| Bureau of Labor Statistics | CPI, PPI, employment, and wages (QCEW, LAUS, OEWS) | blsR |
Yes |
| Bureau of Economic Analysis | GDP and personal income by state and county | bea.R |
Yes |
| FRED and ALFRED | Macro and regional series, including past vintages | fredr |
Yes |
| IPUMS | Harmonized Census, ACS, and CPS microdata; NHGIS tables | ipumsr |
Yes |
| HUD User | USPS ZIP code crosswalks and Fair Market Rents | httr2 |
Yes |
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| Energy Information Administration | Energy prices, production, and consumption by state | eia |
Yes |
| CFPB HMDA | Mortgage applications and lending decisions | httr2 |
No |
| USAspending | Federal grants, contracts, and payments by place | httr2 |
No |
| Treasury Fiscal Data | Federal debt, receipts, and interest rates | httr2 |
No |
| FDIC BankFind | Bank branches and financial reports | httr2 |
No |
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| NASS Quick Stats | Acreage, yields, prices, inventories, and the Census of Agriculture | rnassqs |
Yes |
| NASS Cropland Data Layer | Annual 30-meter crop and land-cover map | CropScapeR |
No |
| AMS Market News | Cash grain, livestock, dairy, and specialty crop prices | httr2 |
Yes |
| FAS Open Data | Global supply and use (PSD), trade (GATS), export sales | httr2 |
Varies |
| ERS ARMS | Farm finances, costs of production, and practices | httr2 |
api.data.gov |
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| FoodData Central | Nutrient composition of foods | httr2 |
api.data.gov |
| NRCS Soil Data Access | Soil properties and productivity (SSURGO) | soilDB |
No |
| NRCS Air and Water Database | Snowpack and soil moisture (SNOTEL, SCAN) | soilDB |
No |
| Forest Inventory and Analysis | Forest area, volume, growth, and removals | rFIA |
No |
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| USGS Water Data | Streamflow and groundwater levels | dataRetrieval |
No |
| Water Quality Portal | Samples from federal, state, and tribal monitoring | dataRetrieval |
No |
| U.S. Drought Monitor | Weekly drought categories by county | httr2 |
No |
| OpenFEMA | Disaster declarations, flood insurance claims, and assistance | httr2 |
No |
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| NOAA NCEI | Daily station weather records (GHCN-Daily) | httr2 |
No |
| PRISM | Gridded U.S. temperature and precipitation | prism |
No |
| gridMET and Daymet | Daily gridded weather for exposure measures | climateR, daymetr |
No |
| NASA POWER | Global daily weather and solar radiation | nasapower |
No |
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| NASA Earthdata | MODIS and Landsat imagery: vegetation, land cover, fire | earthdatalogin, rstac |
Account |
| Google Earth Engine | Processing large satellite archives | rgee |
Account |
| EPA Air Quality System | Monitor-level air pollution | RAQSAPI |
Yes |
| EPA ECHO | Facility permits, inspections, and enforcement | echor |
No |
| EPA Envirofacts | Toxic releases (TRI) and greenhouse gas reporting | httr2 |
No |
| NREL developer APIs | Solar resource, utility rates, fueling stations | httr2 |
api.data.gov |
| Source | Economists use it for | R | Key Required |
|---|---|---|---|
| World Bank Indicators | Development indicators by country and year | WDI |
No |
| FAOSTAT | Agricultural production, trade, prices, and land use | FAOSTAT |
Varies |
| UN Comtrade | Bilateral trade by product | comtradr |
Yes |
| OECD Data Explorer | Country statistics, including agricultural support | rsdmx |
No |
| IMF | Financial statistics and commodity prices | imf.data |
No |
| Eurostat | EU regional and sectoral statistics | eurostat |
No |
Some providers distribute data only as files to download, or only to users who sign a license or data-use agreement
| Access | Examples |
|---|---|
| File download | RMA Summary of Business (crop insurance by county and crop); IRS Statistics of Income (income by ZIP code, county migration); ERS data products such as the Food Environment Atlas; state water-rights and land records |
| License or agreement | Scanner and point-of-sale data; restricted federal microdata |
If this is the case:
Download files with a short R script so the URL, file, and date are recorded
For licensed data, record the provider, version, delivery date, and license terms
rnoaa package left CRAN in 2024readNWIS functions in 2027Save the raw response and the retrieval date so the data can be reproduced after a service changes
| Catalog group | Source | Returned to R |
|---|---|---|
| USDA | Cropland Data Layer | Raster map or summary table |
| Environment: water | USGS Water Data | Daily time series |
| Environment: weather | NASA POWER | Daily weather table |
| Census Bureau | American Community Survey | Estimates, margins of error, and map geometry |
The four sources differ in access, unit of observation, and geography.
Each example begins with a small request that can be inspected before the request is expanded
In RStudio. The Request slides show code that contacts each agency’s server and downloads the 2024 data. You will run it from api_examples.R in the follow-along repository
In these slides. The Try it slides run R inside your web browser, with no installation
The browser version of R cannot install the API packages or contact most agency servers, so each Try it cell starts from rows of the real 2024 downloads typed into the cell. The PDF shows the code without running it
github.com/laurenchenarides/arec_570_demo
For today, download the Lecture 5.2 version as a ZIP file; Git is not needed yet
arec_570_demo.Rproj to open the project in RStudioapi_examples.R and run one line at a time with Ctrl+Enter (Cmd+Return on a Mac)The repository also holds the full API catalog (docs/api-catalog.md). Lectures 5.3 to 5.5 build on the same project
Run once in the RStudio Console. The list matches the top of api_examples.R
api_examples.R creates a data/raw folder inside the project and saves each download there
Question
Which crop and land-cover classes does the Cropland Data Layer assign in Larimer County in 2024?
Source
USDA NASS Cropland Data Layer through the CropScape service
Observation
Each raster cell has a modeled crop or land-cover class for a particular year
08069 is the five-digit Census code for Larimer County
The saved GeoTIFF contains a grid of land-cover codes and the information needed to locate those cells on a map
Change selected, then run the cell. The acreage comes from the 2024 Larimer County download; “All other classes” combines the remaining 29 classes
Questions to answer from the CDL documentation
The CDL records modeled land-cover classes. Parcel ownership, zoning, and management practices require additional sources
Question
What was the daily flow of the Cache la Poudre River during the 2024 growing season?
Source
USGS Water Data API
Observation
Each row reports a daily statistic for one parameter at one monitoring location
00060 is the USGS parameter code for discharge
The returned columns include date, value, unit, approval status, qualifiers, station geometry, and a time-series identifier
Change threshold, then run the cell. The values are daily mean discharge for July 1 to 14, 2024, from the streamflow download
Questions to answer from the USGS record
The gauge measures conditions at one point on a river network. A study of irrigation access may also require diversion service areas, water rights, or delivery records
Question
What temperature and precipitation conditions occurred near Fort Collins during the 2024 growing season?
Source
NASA Prediction Of Worldwide Energy Resources or POWER
Observation
Each row reports modeled weather conditions for a grid cell and day
AG selects parameters prepared for agricultural applications
The three requested measures are maximum temperature, minimum temperature, and precipitation
Change heat_threshold, then run the cell. The values are daily maximum temperature and precipitation for July 1 to 14, 2024, from the weather download
Questions to answer from the POWER documentation
Every location in a grid cell receives the same values, so conditions at individual fields can differ from the cell estimate
Question
How did maximum temperature vary across northern Colorado during the July 2024 heat wave?
Why a different request
The point request returns one grid cell. A regional request returns every cell in a box, over every day requested, in one NetCDF file
Request
NASA POWER, daily maximum temperature, 39.5 to 41.5 N and 104.5 to 106.5 W, July 10 to 16, 2024
From the POWER Data Access Viewer
data/raw, and rename itAnother year, region, or variable means repeating all seven steps
library(httr2)
library(terra)
request("https://power.larc.nasa.gov/api/temporal/daily/regional") |>
req_url_query(parameters = "T2M_MAX", community = "AG",
`latitude-min` = 39.5, `latitude-max` = 41.5,
`longitude-min` = -106.5, `longitude-max` = -104.5,
start = "20240710", end = "20240716", format = "NETCDF") |>
req_perform(path = "data/raw/power_tmax_2024-07.nc")
tmax <- rast("data/raw/power_tmax_2024-07.nc")
tmax # 15 grid cells (5 rows x 3 columns), 7 daily layers, degrees CEach argument replaces a click. The file is saved exactly as the server sent it

terra reads each day as one layer of a rasterFort Collins sits in one of the two hottest cells on July 12. The cells to its west, over the mountains, ran 8 to 9 degrees cooler
| Download by hand | API request in a script | |
|---|---|---|
| Record of choices | Notes, if you write them | The code is the record |
| Another year, region, or variable | Repeat every step | Change one value, or loop |
| Consistency | A wrong box or date is easy to miss | The same request every time |
| A coauthor reproduces it | Follows your written steps | Runs the script |
| When a request fails | A website message | An error the script reports. A box smaller than 2 degrees returns a JSON message saying so |
| Best suited to | A first look at the data | Repeated or growing requests |
Downloading by hand is reasonable for exploring a source. Once the data enter the analysis, write the request as code
Question
How does median household income vary across census tracts in Larimer County?
Source
American Community Survey five-year estimates
Observation
Each row reports an estimate and margin of error for one variable and geographic area
The Census Bureau requires a key for every request
Until your key is active, skip section 4 of api_examples.R; sections 1 to 3 need no key
Open the user-level environment file from R
Add one line, save the file, and restart R (Session > Restart R)
Check that R can read it: nzchar(Sys.getenv("CENSUS_API_KEY")) returns TRUE
The file stays in your home directory, outside every project. Scripts read the key with Sys.getenv("CENSUS_API_KEY")
The result contains a geographic identifier, name, estimate, margin of error, and tract geometry
The default margin of error describes a 90 percent confidence interval
Change relative_moe_limit, then run the cell. The four tracts are illustrative values with the same columns as the ACS download
Questions to answer from the ACS documentation
ACS data describe the population and socioeconomic setting; exposure measures come from other sources
| Source | Unit returned by the request | Time | Geography |
|---|---|---|---|
| Cropland Data Layer | Raster cell | Annual | Grid |
| USGS Water Data | Gauge and day | Daily | Monitoring point |
| NASA POWER | Grid cell and day | Daily | Weather grid |
| Census ACS | Estimate and area | Five-year period | Census tract |
A combined dataset requires a written rule for assigning pixels, gauges, weather cells, and census areas to the study units
For every join record
The combined analytic sample includes the observations that satisfy all source coverage and matching rules
Dominitz and Manski ask how to allocate a fixed budget across collection processes that differ in cost and information (Dominitz and Manski 2017)
API access reduces the time required to retrieve additional observations
Research time is also required to
Question: How should a researcher allocate one additional week across these tasks?
| Project need | Useful access method |
|---|---|
| A defined subset repeated across places or periods | API request |
| Most records in a fixed release | Bulk download |
| A few values needed once | Web table or manual download |
| Repeated data cleaning and analysis | Scripted retrieval with archived raw files |
Choose the method after reviewing the source documentation update schedule and request limits
Keep these items with the project
Store API keys in the user environment file and exclude that file from version control
Write one line for each item, specific enough that a classmate could start the same search
Share your plan in about one minute. Template: docs/data-plan.md in the follow-along repository
| Item | Demo project |
|---|---|
| Outcome or exposure | Low-flow days and heat days on the Cache la Poudre River, 2024 growing season |
| Approach | Secondary, combined from public APIs |
| Sources and access | USGS Water Data (API, no key); NASA POWER (API, no key) |
| Unit of observation | Day: gauge-day for streamflow, grid cell-day for weather |
| Open question | How to assign one gauge and one weather grid cell to farms across the county |
| Next step | This week, request 2015 to 2024 for the same gauge and count revised values by year |
On your laptop, complete Parts One and Two of docs/setup-rstudio.md
usethis and a personal access tokenBring the laptop that you used to complete this exercise with you to class.
Make sure usethis::git_sitrep() runs without errors and nzchar(Sys.getenv("CENSUS_API_KEY")) returns TRUE.
We will copy the demo repository into your GitHub account together in class.
APIs provide scripted access to secondary data
R packages translate requests and responses into familiar R objects
Source documentation defines the population, measures, timing, geography, and uncertainty
Small requests make the returned structure easier to inspect
Retrieval records support reproducibility
Data joins help define the final analytic sample