library(jsonlite)
library(httr)
library(purrr)
I added purrr to the list of libraries because it's really great for working with lists like the one that the NHTSA API returns.
Here is our "list" of VINS
vins <- rep("4JGCB5HE1CA138466", 3)
It took some trial and error, but from looking at the examples the NHTSA provided in other languages, such as JavaScript, I was able to piece together that the body of the message should be a JSON object with entries for format = "json" and data to hold the VINs concatenated into a single string separated by ;. Note that httr will automatically convert lists to JSON for us.
The final detail was realizing that the NHTSA API wanted the POST body encoded as a form, requiring the encode = "form".
I also added verbose() so that httr prints information about the request. It can be helpful during debugging.
r <- httr::POST(
url = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
body = list(
format = "json",
data = paste(vins, collapse = ";")
),
encode = "form",
verbose()
)
results <- httr::content(r)
httr automatically converts the returned JSON into an R list. Here we can see that the NHTSA API returns a JSON object with four top-level entries.
str(results, max.level = 1)
#> List of 4
#> $ Count : int 3
#> $ Message : chr "Results returned successfully. NOTE: Any missing decoded values should be interpreted as NHTSA does not have da"| __truncated__
#> $ SearchCriteria: chr ""
#> $ Results :List of 3
The individual VIN results are returned in .$Results, and here I show just the first 10 entries with text of the first result...
results$Results[[1]] %>%
purrr::keep(~ . != "") %>%
.[1:10] %>%
str()
#> List of 10
#> $ AirBagLocFront : chr "1st Row (Driver & Passenger)"
#> $ AirBagLocSide : chr "1st & 2nd & 3rd Rows"
#> $ BodyClass : chr "Sport Utility Vehicle (SUV)/Multi Purpose Vehicle (MPV)"
#> $ DisplacementCC : chr "3500.0"
#> $ DisplacementCI : chr "213.58310433156"
#> $ DisplacementL : chr "3.5"
#> $ Doors : chr "4"
#> $ DriveType : chr "AWD/All Wheel Drive"
#> $ EngineConfiguration : chr "V-Shaped"
#> $ EngineCylinders : chr "6"