Assignment 5


Introduction

This assignment uses the GovInfo API to collect congressional hearing documents and examine how government data can be accessed programmatically. I focus on hearings of the Senate Committee on Foreign Relations and compare the results from the GovInfo search interface with those returned by the API.

The main distinction is between finding documents and making their contents usable as data. Although the API provides structured metadata and direct links to different document formats, the availability of a downloadable file does not necessarily mean that its contents can be analyzed without further processing.

1. Searching GovInfo manually

Before using the API, I searched the GovInfo search page for hearings of the Senate Committee on Foreign Relations. I sorted the results by publication date, with the newest documents first, and exported the results for comparison with the API.

I saved the website export locally. I also recorded the query generated by the search page.

Search details

The website export will serve as the reference list for checking whether the API returns the same ten hearings.

2. Connecting to the GovInfo API

2.1. Preparing the R environment

The API key is stored in my local .Renviron file rather than in this document. This keeps the key out of the code and the public website repository.

I load the packages needed to send requests, process JSON responses, and organize the results.

library(purrr)
library(magrittr) # Alternatively, load tidyverse

Attaching package: 'magrittr'
The following object is masked from 'package:purrr':

    set_names
library(rjson)
library(jsonlite)

Attaching package: 'jsonlite'
The following objects are masked from 'package:rjson':

    fromJSON, toJSON
The following object is masked from 'package:purrr':

    flatten
library(data.table)

Attaching package: 'data.table'
The following object is masked from 'package:purrr':

    transpose
The following object is masked from 'package:base':

    %notin%
library(readr)
library(httr2)
library(knitr)
library(tibble)
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:data.table':

    between, first, last
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
api_key <- Sys.getenv("GOVINFO_API_KEY")

if (identical(api_key, "")) {
  stop("GOVINFO_API_KEY is missing. Check .Renviron and restart R.")
}

I first test the connection by requesting the available GovInfo collections.

collections_response <- request("https://api.govinfo.gov/collections") |>
  req_url_query(api_key = api_key) |>
  req_perform()

collections <- collections_response |>
  resp_body_json(simplifyVector = TRUE)

head(collections$collections)
  collectionCode               collectionName packageCount granuleCount
1      ANNUALREP               Annual Reports         3686            2
2          BILLS          Congressional Bills       291770           NA
3     BILLSTATUS    Congressional Bill Status       173390           NA
4        BILLSUM Congressional Bill Summaries         9749           NA
5         BUDGET         United States Budget          459         7172
6           CCAL      Congressional Calendars         6445       101477

The Congressional Hearings collection is identified by CHRG The API also provides collection information and package metadata, which can be used without downloading the full documents.

2.2. Searching for the hearings

The GovInfo API accepts a JSON request body for searches. The request below uses the website’s search language to find Congressional Hearings associated with the Senate Committee on Foreign Relations. Results are sorted by publication date in descending order.

search_body <- list(
  query = 'collection:(CHRG) AND "Committee on Foreign Relations"',
  pageSize = 100,
  offsetMark = "*",
  sorts = list(
    list(
      field = "publishdate",
      sortOrder = "DESC"
    )
  )
)

search_response <- request("https://api.govinfo.gov/search") |>
  req_url_query(api_key = api_key) |>
  req_body_json(search_body) |>
  req_perform()

search_data <- search_response |>
  resp_body_json(simplifyVector = FALSE)

names(search_data)
[1] "count"      "offsetMark" "results"   

The response contains the search results and pagination information. I inspect the first result to check which fields are available before extracting the package identifiers.

if (length(search_data$results) == 0) {
  stop("No results returned. Check the search query and API response.")
}

str(search_data$results[[1]], max.level = 2)
List of 11
 $ title           : chr "Arms Control and Transforming International Security Functions at the State Department"
 $ packageId       : chr "CHRG-119shrg63909"
 $ granuleId       : chr "CHRG-119shrg63909"
 $ lastModified    : chr "2026-08-20T14:06:08Z"
 $ governmentAuthor:List of 2
  ..$ : chr "Congress"
  ..$ : chr "Senate"
 $ dateIssued      : chr "2026-03-24"
 $ collectionCode  : chr "CHRG"
 $ dateIngested    : chr "2026-07-06"
 $ download        :List of 5
  ..$ premisLink: chr "https://api.govinfo.gov/packages/CHRG-119shrg63909/premis"
  ..$ txtLink   : chr "https://api.govinfo.gov/packages/CHRG-119shrg63909/granules/CHRG-119shrg63909/htm"
  ..$ zipLink   : chr "https://api.govinfo.gov/packages/CHRG-119shrg63909/zip"
  ..$ modsLink  : chr "https://api.govinfo.gov/packages/CHRG-119shrg63909/granules/CHRG-119shrg63909/mods"
  ..$ pdfLink   : chr "https://api.govinfo.gov/packages/CHRG-119shrg63909/granules/CHRG-119shrg63909/pdf"
 $ relatedLink     : chr "https://api.govinfo.gov/related/CHRG-119shrg63909"
 $ resultLink      : chr "https://api.govinfo.gov/packages/CHRG-119shrg63909/granules/CHRG-119shrg63909/summary"

2.3. Selecting the ten most recent hearings

I use the package identifiers returned by the API to identify individual documents. I keep the publication date and title alongside each identifier so that the final list can be checked against the website export.

api_results <- map_dfr(search_data$results, function(x) {
  tibble(
    packageId = x$packageId %||% NA_character_,
    title = x$title %||% NA_character_,
    publishdate = x$publishdate %||% NA_character_,
    packageLink = x$packageLink %||% NA_character_
  )
})

api_results <- api_results |>
  filter(!is.na(packageId)) |>
  distinct(packageId, .keep_all = TRUE) |>
  arrange(desc(publishdate))

latest_hearings <- api_results |>
  slice_head(n = 10)

latest_hearings |>
  select(publishdate, title, packageId)
# A tibble: 10 × 3
   publishdate title                                                   packageId
   <chr>       <chr>                                                   <chr>    
 1 <NA>        Arms Control and Transforming International Security F… CHRG-119…
 2 <NA>        A Pathway to European Energy Security                   CHRG-119…
 3 <NA>        Countering Terrorism in North Africa: Opportunities an… CHRG-119…
 4 <NA>        NATO Summit 2025: An Assessment of Transatlantic Secur… CHRG-119…
 5 <NA>        East Africa & the Horn: At a Turning Point or Breaking… CHRG-119…
 6 <NA>        Shared Threats: Indo Pacific Alliances and Burden Shar… CHRG-119…
 7 <NA>        PRC Influence and the Status of Taiwan's Diplomatic Al… CHRG-119…
 8 <NA>        Advancing American Interests in the Western Hemisphere  CHRG-119…
 9 <NA>        Interdicting Illicit Drug Trafficking: A View from the… CHRG-119…
10 <NA>        After Assad: Navigating Syria Policy                    CHRG-119…

If the first response does not contain ten suitable results, I would request the next page using the returned offsetMark, continuing until ten qualifying hearings are available. I would also verify that the returned titles actually correspond to the intended committee, since search results may include documents that mention the committee without being hearings of that committee.

3. Downloading the documents

3.1. Retrieving package metadata

The package summary endpoint provides metadata and links to available document formats. This allows me to examine the options before deciding which files to download.

get_package_summary <- function(package_id) {
  request(
    paste0(
      "https://api.govinfo.gov/packages/",
      package_id,
      "/summary"
    )
  ) |>
    req_url_query(api_key = api_key) |>
    req_perform() |>
    resp_body_json(simplifyVector = FALSE)
}

first_summary <- get_package_summary(latest_hearings$packageId[[1]])

names(first_summary)
 [1] "documentType"      "congress"          "heldDates"        
 [4] "session"           "documentNumber"    "detailsLink"      
 [7] "title"             "branch"            "collectionName"   
[10] "download"          "pages"             "chamber"          
[13] "relatedLink"       "suDocClassNumber"  "granulesLink"     
[16] "dateIssued"        "packageId"         "collectionCode"   
[19] "governmentAuthor2" "governmentAuthor1" "publisher"        
[22] "docClass"          "lastModified"      "category"         
[25] "otherIdentifier"  
str(first_summary$download, max.level = 2)
List of 3
 $ premisLink: chr "https://api.govinfo.gov/packages/CHRG-119shrg63909/premis"
 $ zipLink   : chr "https://api.govinfo.gov/packages/CHRG-119shrg63909/zip"
 $ modsLink  : chr "https://api.govinfo.gov/packages/CHRG-119shrg63909/mods"

3.2. Creating a local download directory

I save the documents outside the website’s published output directory. The downloaded files and the log are local working data, not content to publish on GitHub Pages.

download_dir <- "data/govinfo_downloads"
dir.create(download_dir, recursive = TRUE, showWarnings = FALSE)

3.3. Downloading the ten PDFs

The following function retrieves the PDF link from each package summary, downloads the file, and records whether the download succeeded. It also records errors so that failed requests can be investigated rather than silently ignored.

I was having trupiuble downloading the PDFs because they didn’t seem to be available as easily as the manual, hence I downloaded the zip fails which include the PDFs.

get_zip_link <- function(summary) {
  links <- summary$download
  
  if (is.null(links) || is.null(links$zipLink)) {
    return(NA_character_)
  }
  
  links$zipLink
}

download_hearing <- function(package_id, title) {
  tryCatch({
    summary <- get_package_summary(package_id)
    zip_url <- get_zip_link(summary)
    
    if (is.na(zip_url) || !nzchar(zip_url)) {
      stop("No ZIP link was available.")
    }
    
    # Append the API key to the ZIP URL
    zip_url <- paste0(
      zip_url,
      if (grepl("\\?", zip_url)) "&" else "?",
      "api_key=",
      api_key
    )
    
    file_path <- file.path(
      download_dir,
      paste0(package_id, ".zip")
    )
    
    request(zip_url) |>
      req_perform(path = file_path)
    
    tibble(
      packageId = package_id,
      title = title,
      file = file_path,
      status = "success",
      error = NA_character_
    )
  }, error = function(e) {
    tibble(
      packageId = package_id,
      title = title,
      file = NA_character_,
      status = "failed",
      error = conditionMessage(e)
    )
  })
}

download_log <- purrr::map2_dfr(
  latest_hearings$packageId,
  latest_hearings$title,
  download_hearing
)

download_log
# A tibble: 10 × 5
   packageId         title                                    file  status error
   <chr>             <chr>                                    <chr> <chr>  <chr>
 1 CHRG-119shrg63909 Arms Control and Transforming Internati… data… succe… <NA> 
 2 CHRG-119shrg63707 A Pathway to European Energy Security    data… succe… <NA> 
 3 CHRG-119shrg64059 Countering Terrorism in North Africa: O… data… succe… <NA> 
 4 CHRG-119shrg61565 NATO Summit 2025: An Assessment of Tran… data… succe… <NA> 
 5 CHRG-119shrg60820 East Africa & the Horn: At a Turning Po… data… succe… <NA> 
 6 CHRG-119shrg60819 Shared Threats: Indo Pacific Alliances … data… succe… <NA> 
 7 CHRG-119shrg60060 PRC Influence and the Status of Taiwan'… data… succe… <NA> 
 8 CHRG-119shrg60032 Advancing American Interests in the Wes… data… succe… <NA> 
 9 CHRG-119shrg61202 Interdicting Illicit Drug Trafficking: … data… succe… <NA> 
10 CHRG-119shrg59893 After Assad: Navigating Syria Policy     data… succe… <NA> 

I save the log locally so that I can check which documents were downloaded successfully.

write_csv(
  download_log,
  file.path(download_dir, "download_log.csv")
)

download_log |>
  count(status)
# A tibble: 1 × 2
  status      n
  <chr>   <int>
1 success    10

3.4. Comparing the API results with the website export

I compare the package identifiers from the API with those from the manually exported CSV. GovInfo’s export can contain introductory rows or metadata before the actual table, so I first inspect the file structure.

manual_file <- "data/govinfo-search-results.csv"

if (file.exists(manual_file)) {
  manual_results <- read_csv(
    manual_file,
    show_col_types = FALSE
  )
  
  # Check that the file was imported with the expected columns
  names(manual_results)
  head(manual_results, 5)
} else {
  stop("CSV export not found. Check the file path: ", manual_file)
}
Warning: One or more parsing issues, call `problems()` on your data frame for details,
e.g.:
  dat <- vroom(...)
  problems(dat)
# A tibble: 5 × 19
  index collection         packageId granuleId title detailsLink pdfLink pdfSize
  <chr> <chr>              <chr>     <chr>     <chr> <chr>       <chr>   <chr>  
1 1     Congressional Hea… CHRG-119… CHRG-119… Behi… https://ww… https:… 36.9 MB
2 2     Congressional Hea… CHRG-119… CHRG-119… Defe… https://ww… https:… 52.8 MB
3 3     Congressional Hea… CHRG-119… CHRG-119… Arms… https://ww… https:… 343.0 …
4 4     Congressional Hea… CHRG-119… CHRG-119… THE … https://ww… https:… 23.2 MB
5 5     Congressional Hea… CHRG-119… CHRG-119… Deep… https://ww… https:… 6.4 MB 
# ℹ 11 more variables: htmlLink <chr>, htmlSize <chr>, xmlLink <lgl>,
#   xmlSize <chr>, otherLink1 <lgl>, other1Size <chr>, otherLink2 <lgl>,
#   other2Size <chr>, teaser <chr>, historical <lgl>, publishdate <date>
head(manual_results, 8)
# A tibble: 8 × 19
  index collection         packageId granuleId title detailsLink pdfLink pdfSize
  <chr> <chr>              <chr>     <chr>     <chr> <chr>       <chr>   <chr>  
1 1     Congressional Hea… CHRG-119… CHRG-119… Behi… https://ww… https:… 36.9 MB
2 2     Congressional Hea… CHRG-119… CHRG-119… Defe… https://ww… https:… 52.8 MB
3 3     Congressional Hea… CHRG-119… CHRG-119… Arms… https://ww… https:… 343.0 …
4 4     Congressional Hea… CHRG-119… CHRG-119… THE … https://ww… https:… 23.2 MB
5 5     Congressional Hea… CHRG-119… CHRG-119… Deep… https://ww… https:… 6.4 MB 
6 6     Congressional Hea… CHRG-119… CHRG-119… U.S.… https://ww… https:… 295.3 …
7 7     Congressional Hea… CHRG-119… CHRG-119… A Pa… https://ww… https:… 8.8 MB 
8 8     Congressional Hea… CHRG-119… CHRG-119… Coun… https://ww… https:… 305.6 …
# ℹ 11 more variables: htmlLink <chr>, htmlSize <chr>, xmlLink <lgl>,
#   xmlSize <chr>, otherLink1 <lgl>, other1Size <chr>, otherLink2 <lgl>,
#   other2Size <chr>, teaser <chr>, historical <lgl>, publishdate <date>
# Check which collections appear in the manual export
if ("collection" %in% names(manual_results)) {
  manual_results |>
    count(collection, sort = TRUE)
}
# A tibble: 4 × 2
  collection                                n
  <chr>                                 <int>
1 Congressional Hearings                  995
2 Bulk Submission                           5
3 3032                                      1
4 Senate Committee on Foreign Relations     1
# Check the package IDs and titles, if available
manual_results |>
  select(any_of(c("collection", "packageId", "title", "publishdate"))) |>
  head(10)
# A tibble: 10 × 4
   collection             packageId         title                    publishdate
   <chr>                  <chr>             <chr>                    <date>     
 1 Congressional Hearings CHRG-119shrg64352 Behind the Label: Forei… 2026-07-15 
 2 Congressional Hearings CHRG-119hhrg63520 Defending Main Street: … 2026-03-25 
 3 Congressional Hearings CHRG-119shrg63909 Arms Control and Transf… 2026-03-24 
 4 Congressional Hearings CHRG-119shrg63409 THE DEPARTMENT OF ENERG… 2026-03-19 
 5 Congressional Hearings CHRG-119hhrg64201 Deepseek and Unitree Ro… 2026-03-17 
 6 Congressional Hearings CHRG-119shrg64385 U.S. Leadership at the … 2026-03-17 
 7 Congressional Hearings CHRG-119shrg63707 A Pathway to European E… 2026-02-04 
 8 Congressional Hearings CHRG-119shrg64059 Countering Terrorism in… 2026-02-03 
 9 Congressional Hearings CHRG-119shrg63403 Truth in Labeling: Amer… 2026-01-29 
10 Congressional Hearings CHRG-119shrg63883 Nomination to the Natio… 2025-12-03 

Prepare the manual and API package IDs

manual_ids <- manual_results |>
  transmute(packageId = trimws(as.character(packageId))) |>
  filter(!is.na(packageId), packageId != "") |>
  distinct()

api_ids <- latest_hearings |>
  transmute(packageId = trimws(as.character(packageId))) |>
  filter(!is.na(packageId), packageId != "") |>
  distinct()

# Check how many unique records each source contains
tibble(
  source = c("Manual export", "API results"),
  number_of_records = c(nrow(manual_ids), nrow(api_ids))
)
# A tibble: 2 × 2
  source        number_of_records
  <chr>                     <int>
1 Manual export              1000
2 API results                  10

Create the comparison table.

manual_only <- anti_join(manual_ids, api_ids, by = "packageId") |>
  mutate(source = "Manual only")

api_only <- anti_join(api_ids, manual_ids, by = "packageId") |>
  mutate(source = "API only")

matching_ids <- inner_join(
  manual_ids,
  api_ids,
  by = "packageId"
)

knitr::kable(
  matching_ids,
  caption = "Package IDs Matching in Manual GovInfo Export and API Results",
  col.names = "Package ID",
  align = "l"
)
Package IDs Matching in Manual GovInfo Export and API Results
Package ID
CHRG-119shrg63909
CHRG-119shrg63707
CHRG-119shrg64059
CHRG-119shrg61565
CHRG-119shrg60820
CHRG-119shrg60819
CHRG-119shrg60060
CHRG-119shrg60032
CHRG-119shrg61202
CHRG-119shrg59893

Check how many records match.

matching_ids <- inner_join(manual_ids, api_ids, by = "packageId")

tibble(
  measure = c(
    "Matching package IDs",
    "Manual-only package IDs",
    "API-only package IDs"
  ),
  count = c(
    nrow(matching_ids),
    nrow(manual_only),
    nrow(api_only)
  )
)
# A tibble: 3 × 2
  measure                 count
  <chr>                   <int>
1 Matching package IDs       10
2 Manual-only package IDs   990
3 API-only package IDs        0

4. Report

Difficulties with the collection process

One of the main difficulties was figuring out how to get from the search results to the actual documents. The GovInfo website makes it possible to search and export records, but I still needed to make sure that the results corresponded to the hearings I was looking for. With the API, I could retrieve the records in R and sort them by publication date, but I had to understand how the search query worked and how the information was organized in the API response.

Downloading the documents was another challenge. I initially tried to retrieve PDF links from the package summaries, but the response did not include a direct PDF link. Instead, it provided a ZIP download link, so I changed my code to download the hearing packages as ZIP files. This also showed me that keeping a download log matters since finding a document through the API does not necessarily mean that the file has been downloaded successfully.

a. How usable are the downloaded documents as data?

The hearing documents contain useful information, but the PDFs are not ready to analyze directly. To turn them into a table or text corpus, I would first need to extract the text and organize it into a consistent format. For example, I could record the hearing date, title, speaker, and statements made during the hearing. I would also need to check the extracted text for formatting problems, since tables, speaker labels, and other document elements might not be captured correctly.

b. How could the process be improved?

I could make the process more efficient by using the other formats available through GovInfo instead of relying on PDFs alone. Plain-text files would be easier to work with for text analysis, while the metadata already provides information such as the title, date, chamber, and document type. This information could be collected before opening or processing the documents and used to organize the dataset. I would also keep the search query and download log so that I could check which documents were collected and reproduce the process later.

c. What did the API provide that the search page and last week’s scraping did not?

The API allowed me to retrieve structured search results directly in R, which made it easier to filter, sort, and compare documents without manually processing a webpage. It also provided access to package metadata and download links, making it easier to collect information about multiple documents in a more consistent and reproducible way. It is also a more reliable and legal/ethical way of obtaining data. There is not many hurdles to get through after being authorized an API key, whereas for scraping we had to politely get the info.

5. Submit

Download log:

download_log <- read_csv(
  "data/govinfo_downloads/download_log.csv",
  show_col_types = FALSE
)

kable(
  download_log,
  caption = "GovInfo API Download Log"
)
GovInfo API Download Log
packageId title file status error
CHRG-119shrg63909 Arms Control and Transforming International Security Functions at the State Department data/govinfo_downloads/CHRG-119shrg63909.zip success NA
CHRG-119shrg63707 A Pathway to European Energy Security data/govinfo_downloads/CHRG-119shrg63707.zip success NA
CHRG-119shrg64059 Countering Terrorism in North Africa: Opportunities and Challenges data/govinfo_downloads/CHRG-119shrg64059.zip success NA
CHRG-119shrg61565 NATO Summit 2025: An Assessment of Transatlantic Security Cooperation data/govinfo_downloads/CHRG-119shrg61565.zip success NA
CHRG-119shrg60820 East Africa & the Horn: At a Turning Point or Breaking Point? data/govinfo_downloads/CHRG-119shrg60820.zip success NA
CHRG-119shrg60819 Shared Threats: Indo Pacific Alliances and Burden Sharing in Today’s Geopolitical Environment data/govinfo_downloads/CHRG-119shrg60819.zip success NA
CHRG-119shrg60060 PRC Influence and the Status of Taiwan’s Diplomatic Allies in the Western Hemisphere data/govinfo_downloads/CHRG-119shrg60060.zip success NA
CHRG-119shrg60032 Advancing American Interests in the Western Hemisphere data/govinfo_downloads/CHRG-119shrg60032.zip success NA
CHRG-119shrg61202 Interdicting Illicit Drug Trafficking: A View from the Front Lines data/govinfo_downloads/CHRG-119shrg61202.zip success NA
CHRG-119shrg59893 After Assad: Navigating Syria Policy data/govinfo_downloads/CHRG-119shrg59893.zip success NA