Documentation >

Reading from the STAC API with R

This quickstart introduces STAC for R users. To use the Planetary Computer’s STAC API from Python, see here.

We’ll use the rstac library to make requests to the STAC API.

[1]:
library(rstac)
library(magrittr)
library(terra)

s_obj <- stac("https://planetarycomputer.microsoft.com/api/stac/v1/")
terra 1.5.12


Attaching package: ‘terra’


The following objects are masked from ‘package:magrittr’:

    extract, inset


We can search for items using s_obj and the stac_search function:

[2]:
it_obj <- s_obj %>%
    stac_search(collections = "landsat-c2-l2",
                bbox = c(-47.02148, -17.35063, -42.53906, -12.98314)) %>%
    get_request()

print(it_obj)
###STACItemCollection
- features (250 item(s)):
  - LC09_L2SP_217072_20220515_02_T1
  - LC09_L2SP_217071_20220515_02_T2
  - LC09_L2SP_219071_20220513_02_T1
  - LC09_L2SP_221071_20220511_02_T1
  - LC09_L2SP_221070_20220511_02_T1
  - LC09_L2SP_221069_20220511_02_T1
  - LC08_L2SP_217072_20220507_02_T2
  - LC08_L2SP_217071_20220507_02_T1
  - LC09_L2SP_218072_20220506_02_T1
  - LC09_L2SP_218071_20220506_02_T1
  - ... with 240 more feature(s).
- assets:
qa, ang, red, blue, drad, emis, emsd, trad, urad, atran, cdist, green, nir08, lwir11, swir16, swir22, coastal, mtl.txt, mtl.xml, mtl.json, qa_pixel, qa_radsat, qa_aerosol, tilejson, rendered_preview
- other field(s): type, features, links

As detailed in Using tokens for data access, accessing data from the Planetary Computer typically requires signing the item. rstac has built-in support for signing.

[3]:
it_obj <- s_obj %>%
    stac_search(collections = "landsat-c2-l2",
                bbox = c(-47.02148, -17.35063, -42.53906, -12.98314)) %>%
    get_request() %>%
    items_sign(sign_fn = sign_planetary_computer())
Warning message:
“Items matched not provided.”
[4]:
url <- paste0("/vsicurl/", it_obj$features[[1]]$assets$blue$href)

data <- rast(url)
plot(data)

Learn more

For more about the Planetary Computer’s STAC API, see Using tokens for data access and the STAC API reference. For more about rstac, see its documentation.