New way to get a list of species by country from IUCN

Update to use IUCN API v4

Getting a list of species per country according to the ICUN Red List, as I did in one of my previous posts, is not possible anymore since the IUCN API has been upgraded to v4. Because of this, the rl_sp_country() function from the rredlist R package has also been deprecated, as it relied in the v3 of the API (see changelog).

So, how can we get the number of species in the country according to the IUCN Red List with the new IUCN API v4? Here’s how I did it.

Creating a function that uses IUCN API v4

The function queries the IUCN Red List v4 endpoint (and thus requires a valid IUCN API token, api_key) to retrieve the number of species associated with one or more ISO country codes (country_codes). It then returns a tibble with one row per country code and a numeric n_species column. If a country is not found or the request fails, n_species will be NA.

getNspeciesPerCountry <- function(api_key, country_codes, verbose=FALSE) {
  
  # Define the base URL for the IUCN Red List API
  base_url <- "https://api.iucnredlist.org/api/v4"
  endpoint <- str_glue("/countries")
  
  # Authorization token
  headers <- add_headers(Authorization = paste("Bearer", api_key))
  
  results <- tibble(country_code = character(),
                    n_species = integer())
  
  for (country_code in country_codes) {
    if(verbose == TRUE){
      cat("Fetching data for:", country_code, "\n")  
    }
    
    api_url <- str_glue('{base_url}{endpoint}/{country_code}?latest=true&scope_code=1')
    response <- HEAD(api_url, headers)
    
    if (status_code(response) == 200) {
      n_species <- response$headers$`total-count`
    } else {
      print("Country not found.")
      n_species <- NA
    }
    
    results_i <- tibble(country_code = country_code,
                        n_species = as.numeric(n_species))
    if (!is.null(results_i)) {
      results <- bind_rows(results, results_i)
    }
  }
  return(results)
}

Using it

Let’s do a quick example with Argentina (AR), Brazil (BR), and Uruguay (UY), and an invented country code XX, to test the function.

library(knitr)
library(countrycode)
library(httr)
library(jsonlite)
library(tidyverse)

# Your IUCN Red List API key
IUCN_REDLIST_KEY <- Sys.getenv("IUCN_REDLIST_KEY")
getNspeciesPerCountry(api_key = IUCN_REDLIST_KEY, 
                      country_codes= c('AR', 'BR', 'UY', 'XX'),
                      verbose = TRUE)
Fetching data for: AR 
Fetching data for: BR 
Fetching data for: UY 
Fetching data for: XX 
[1] "Country not found."

# A tibble: 4 × 2
  country_code n_species
  <chr>            <dbl>
1 AR                4807
2 BR               19891
3 UY                2001
4 XX                  NA

Same example as previous post

Now that we know it works, let’s test it on the same example as my previous post.

LatinAmerica <- tibble(country= c('Mexico', 'Brazil', 'Costa Rica', 'Colombia', 'Peru', 'Argentina', 'Ecuador', 'Panama', 'Chile', 'Venezuela', 'Belize', 'Honduras', 'Bolivia', 'Guatemala', 'Cuba', 'Nicaragua', 'Paraguay', 'Bahamas', 'Jamaica', 'Trinidad and Tobago', 'Guyana', 'Dominican Republic', 'El Salvador', 'Suriname', 'Uruguay', 'Haiti')) %>%
  mutate(country_code=countrycode(country, 'country.name', 'iso2c'))

LatinAmericaNspecies <- getNspeciesPerCountry(api_key = IUCN_REDLIST_KEY, 
                                              country_codes = LatinAmerica$country_code)

LatinAmerica <- left_join(LatinAmerica, LatinAmericaNspecies)
LatinAmerica %>% kable()
countrycountry_coden_species
MexicoMX12904
BrazilBR19891
Costa RicaCR7633
ColombiaCO16119
PeruPE11275
ArgentinaAR4807
EcuadorEC12169
PanamaPA7839
ChileCL2412
VenezuelaVE11219
BelizeBZ3934
HondurasHN5862
BoliviaBO7440
GuatemalaGT6141
CubaCU4064
NicaraguaNI5652
ParaguayPY2636
BahamasBS2559
JamaicaJM2828
Trinidad and TobagoTT3202
GuyanaGY5893
Dominican RepublicDO3037
El SalvadorSV3134
SurinameSR4811
UruguayUY2001
HaitiHT3042

And, that’s all!

Florencia Grattarola
Florencia Grattarola
Postdoc Researcher

Uruguayan biologist doing research in macroecology and biodiversity informatics.