Scope

This vignette provides a guided walk-through of the “getting data out” functions of the RESTful API endpoints which list and view details.

ruODK users would mix and match parts of the demonstrated workflows to build their own data pipelines, e.g.:

  • to build a quick analysis from all data, freshly downloaded from a smaller project, or
  • to build an interactive ETL pipeline to selectively download only new submissions for further processing and upload into downstream data warehouses.

A typical and more stream-lined workflow is provided in the RMarkdown template “ODK Central via OData” which is supplied by ruODK.

Three ways to happiness

ODK Central offers no less than three different ways to access data:

  • viewing ODK Central data in MS PowerBI, MS Excel, Tableau, or ruODK through the OData service endpoints, or
  • downloading all submissions including attachments as one (possibly gigantic) zip archive either through the “Export Submissions” button in the ODK Central form submissions page or through ruODK, or
  • viewing ODK Central data through ruODK’s RESTful API functions.

While the vignette("odata", package="ruODK") (online here) illustrates the first option, this vignette demonstrates the remaining two.

Not implemented (yet) are the “managing ODK Central” functions which create, update, and delete projects, forms, users, roles, and permissions. We haven’t yet found a strong use case to automate those functions - ODK Central (driven by humans) does those jobs beautifully on an expected scale.

Setup ruODK

See vignette("Setup", package = "ruODK") for detailed options to configure ruODK.

Here, we’ll grab the OData service URL from the form used in this vignette, plus username and password of a web user of ODK Central with access to that form.

ruODK::ru_setup() will populate the default url, project ID, and form ID which are used by ruODK’s other functions (unless specified otherwise).

library(ruODK)
ruODK::ru_setup(
  svc = "https://sandbox.central.getodk.org/v1/projects/14/forms/build_Flora-Quadrat-0-4_1564384341.svc",
  un = Sys.getenv("ODKC_TEST_UN"),
  pw = Sys.getenv("ODKC_TEST_PW"),
  tz = "Australia/Perth",
  verbose = TRUE
)
#> <ruODK settings>
#>   Default ODK Central Project ID: 14 
#>   Default ODK Central Form ID: build_Flora-Quadrat-0-4_1564384341 
#>   Default ODK Central URL: https://sandbox.central.getodk.org 
#>   Default ODK Central Username: [email protected] 
#>   Default ODK Central Password: run ruODK::get_default_pw() to show 
#>   Default ODK Central Passphrase: run ruODK::get_default_pp() to show 
#>   Default Time Zone: Australia/Perth 
#>   Default ODK Central Version: 1.1 
#>   Default HTTP GET retries: 3 
#>   Verbose messages: TRUE 
#>   Test ODK Central Project ID: 14 
#>   Test ODK Central Form ID: build_Flora-Quadrat-0-2_1558575936 
#>   Test ODK Central Form ID (ZIP tests): build_Spotlighting-0-6_1558333698 
#>   Test ODK Central Form ID (Attachment tests): build_Flora-Quadrat-0-1_1558330379 
#>   Test ODK Central Form ID (Parsing tests): build_Turtle-Track-or-Nest-1-0_1569907666 
#>   Test ODK Central Form ID (WKT tests): build_Locations_1589344221 
#>   Test ODK Central URL: https://sandbox.central.getodk.org 
#>   Test ODK Central Username: [email protected] 
#>   Test ODK Central Password: run ruODK::get_test_pw() to show 
#>   Test ODK Central Passphrase: run ruODK::get_test_pp() to show 
#>   Test ODK Central Version: 1.1
t <- fs::dir_create("media")

Projects

List projects. We see the project ID, a name, the number of forms and app users, dates of last form submissions plus project management timestamps (created, updated).

The important bit here is the project ID.

fq_project_list <- ruODK::project_list()
fq_project_list %>% knitr::kable(.)
id name created_at updated_at forms app_users last_submission key_id archived
4 Fire Management and Plant Health 2020-11-06 11:12:16 2021-09-29 08:18:29 8 2 2021-09-30 12:19:54 NA FALSE
6 Kingston Spotlighting 2021-02-16 14:01:19 2021-02-16 14:40:31 3 3 2021-03-24 11:32:15 NA FALSE
2 ruODK package tests 2020-10-31 19:11:50 2020-11-23 13:25:03 12 1 2020-11-02 12:41:14 NA FALSE
3 ruODK package tests encrypted 2020-10-31 19:12:57 2020-11-02 15:23:17 1 1 2020-11-02 15:26:38 1 FALSE
5 Sandbox 2020-12-14 15:36:46 2021-08-05 19:07:08 3 2 2021-07-07 11:16:47 NA FALSE
1 Turtle Monitoring 2020-09-15 11:50:06 2021-09-09 10:50:11 13 14 2021-09-20 11:34:44 NA FALSE
7 An archived project 2021-05-04 17:13:32 2021-05-04 17:13:38 0 0 NA NA TRUE

Inspect a project using its ID. We receive a tibble with exactly one row, all the columns of ruODK::project_list plus a column verbs, which contains all available API actions for a project.

fq_project_detail <- ruODK::project_detail()
# Project details (without verbs)
fq_project_detail %>% dplyr::select(-"verbs") %>%  knitr::kable(.)
id name forms app_users last_submission created_at updated_at archived
2 ruODK package tests 12 1 2020-11-02T04:41:14.761Z 2020-10-31T11:11:50.035Z 2020-11-23T05:25:03.426Z FALSE

# Available verbs
fq_project_detail$verbs[[1]] %>% unlist(.)
#>  [1] "config.read"              "field_key.create"        
#>  [3] "field_key.delete"         "field_key.list"          
#>  [5] "form.create"              "form.delete"             
#>  [7] "form.list"                "form.read"               
#>  [9] "form.update"              "project.create"          
#> [11] "project.delete"           "project.read"            
#> [13] "project.update"           "session.end"             
#> [15] "submission.create"        "submission.read"         
#> [17] "submission.list"          "user.create"             
#> [19] "user.list"                "user.password.invalidate"
#> [21] "user.read"                "user.update"             
#> [23] "submission.update"        "role.create"             
#> [25] "role.update"              "role.delete"             
#> [27] "assignment.list"          "assignment.create"       
#> [29] "assignment.delete"        "user.delete"             
#> [31] "audit.read"               "public_link.create"      
#> [33] "public_link.list"         "public_link.read"        
#> [35] "public_link.update"       "public_link.delete"      
#> [37] "backup.run"               "config.set"              
#> [39] "analytics.read"

Nothing apart from the verbs is new compared to the data returned by ruODK::project_list.

To learn more about the functionality behind the verbs, refer to the interactive ODK Central API documentation.

To retrieve data from ODK Central, the functions shown below will suffice.

Forms

List forms for a project

To download form submissions, we need to know project ID and form ID.

There are several ways of retrieving the form ID:

  • Browsing forms in the ODK Central’s project overviews,
  • Stealing the form ID from the OData service endpoint URL as shown on ODK Central’s form submission page,
  • Listing form metadata for a given project ID with ruODK::form_list().
fq_form_list <- ruODK::form_list()
fq_form_list %>% knitr::kable(.)
name fid version state submissions created_at created_by_id created_by updated_at published_at last_submission hash
Flora Quadrat 0.4 Flora-Quadrat-04 open 1 2020-11-02 10:56:21 5 Florian Mayer 2020-11-23 13:25:03 2020-11-02 10:56:25 2020-11-02 12:19:45 434ff9e1e33fc8bb35148c0cc6979708
Flora Quadrat 0.4 (gap) Flora-Quadrat-04-gap open 2 2020-11-02 11:15:29 5 Florian Mayer 2020-11-23 13:25:03 2020-11-02 11:15:32 2020-11-02 12:36:09 241c4759564ea039b4404b6892025500
Flora Quadrat 0.4 (one att) Flora-Quadrat-04-att open 1 2020-11-02 11:13:13 5 Florian Mayer 2020-11-23 13:25:03 2020-11-02 11:13:16 2020-11-02 12:36:10 2cb6a4b3d7f05ab055f3da89d0958b14
I8n label and choices I8n_label_choices open 2 2020-11-02 11:29:48 5 Florian Mayer 2020-11-23 13:25:03 2020-11-02 11:29:50 2020-11-02 12:41:14 bc4dff584ab2e0b0dd2c50eb1c2c7aa4
I8n label lang I8n_label_lng open 1 2020-11-02 11:38:37 5 Florian Mayer 2020-11-23 13:25:03 2020-11-02 11:38:40 2020-11-02 12:39:58 7e912580b246796c8477cfcd4c5dceab
I8n label lang with choice filter I8n_lang_choicefilter open 0 2020-11-23 13:23:36 5 Florian Mayer 2020-11-23 13:25:03 2020-11-23 13:23:41 NA 369a921eb94672dabbd395a035819d65
I8n label no lang with choice filter I8n_no_lang_choicefilter open 0 2020-11-23 13:23:56 5 Florian Mayer 2020-11-23 13:25:03 2020-11-23 13:24:00 NA 0c574c7254ba06435ae560b0506fef68
I8n no lang I8n_no_lang open 1 2020-11-02 11:29:27 5 Florian Mayer 2020-11-23 13:25:03 2020-11-02 11:29:29 2020-11-02 12:39:27 44a38dfee1e7c7b6622a489e379e479f
Locations Locations open 1 2020-11-02 10:54:24 5 Florian Mayer 2020-11-23 13:25:03 2020-11-02 10:54:27 2020-11-02 12:36:11 7365cf1fdad8d6c0ae7351bc05ecc2f2
Locations (draft) Locations_draft open 0 2020-11-02 14:26:01 5 Florian Mayer 2020-11-23 13:25:03 NA NA d1701aad460c192c2fc97eb10241e350
Locations (no submissions) Locations_no_submissions open 0 2020-11-02 10:55:11 5 Florian Mayer 2020-11-23 13:25:03 2020-11-02 10:55:15 NA eb7caf4e3994b953999165ddfdb6eb3b
Spotlighting 0.6 Spotlighting-06 open 1 2020-11-02 10:57:46 5 Florian Mayer 2020-11-23 13:25:03 2020-11-02 10:57:49 2020-11-02 12:36:11 1e14bff57968a3684849bb4370f5d88b

Further to the metadata shown here, a column xml contains the entire XForms definition (originally XML) as nested list.

If the original XML is needed rather than the R equivalent (nested list), we can use ruODK::form_xml with parameter parse=FALSE:

fq_form_xml <- ruODK::form_xml(parse=FALSE)
if (require(listviewer)){
  listviewer::jsonedit(fq_form_xml)
} else {
 ru_msg_warn("Install package listviewer to browse the form XML.")  
}
#> Loading required package: listviewer

Inspect form schema

The form_schema represents all form fields of the XForms definition.

See the ODK Central API docs and the examples of ??ruODK::form_schema() for more detail.

fq_form_schema <- ruODK::form_schema()
fq_form_schema %>% knitr::kable(.)
path name type binary ruodk_name
/meta meta structure NA meta
/meta/instanceID instanceID string NA meta_instance_id
/encounter_start_datetime encounter_start_datetime dateTime NA encounter_start_datetime
/reporter reporter string NA reporter
/device_id device_id string NA device_id
/location location structure NA location
/location/area_name area_name string NA location_area_name
/location/quadrat_photo quadrat_photo binary TRUE location_quadrat_photo
/location/corner1 corner1 geopoint NA location_corner1
/habitat habitat structure NA habitat
/habitat/morphological_type morphological_type select1 NA habitat_morphological_type
/habitat/morphological_type_photo morphological_type_photo binary TRUE habitat_morphological_type_photo
/vegetation_stratum vegetation_stratum repeat NA vegetation_stratum
/vegetation_stratum/nvis_level3_broad_floristic_group nvis_level3_broad_floristic_group select1 NA vegetation_stratum_nvis_level3_broad_floristic_group
/vegetation_stratum/max_height_m max_height_m decimal NA vegetation_stratum_max_height_m
/vegetation_stratum/foliage_cover foliage_cover select1 NA vegetation_stratum_foliage_cover
/vegetation_stratum/dominant_species_1 dominant_species_1 string NA vegetation_stratum_dominant_species_1
/vegetation_stratum/dominant_species_2 dominant_species_2 string NA vegetation_stratum_dominant_species_2
/vegetation_stratum/dominant_species_3 dominant_species_3 string NA vegetation_stratum_dominant_species_3
/vegetation_stratum/dominant_species_4 dominant_species_4 string NA vegetation_stratum_dominant_species_4
/perimeter perimeter structure NA perimeter
/perimeter/corner2 corner2 geopoint NA perimeter_corner2
/perimeter/corner3 corner3 geopoint NA perimeter_corner3
/perimeter/corner4 corner4 geopoint NA perimeter_corner4
/perimeter/mudmap_photo mudmap_photo binary TRUE perimeter_mudmap_photo
/taxon_encounter taxon_encounter repeat NA taxon_encounter
/taxon_encounter/field_name field_name string NA taxon_encounter_field_name
/taxon_encounter/photo_in_situ photo_in_situ binary TRUE taxon_encounter_photo_in_situ
/taxon_encounter/taxon_encounter_location taxon_encounter_location geopoint NA taxon_encounter_taxon_encounter_location
/taxon_encounter/life_form life_form select1 NA taxon_encounter_life_form
/taxon_encounter/voucher_specimen_barcode voucher_specimen_barcode barcode NA taxon_encounter_voucher_specimen_barcode
/taxon_encounter/voucher_specimen_label voucher_specimen_label string NA taxon_encounter_voucher_specimen_label
/encounter_end_datetime encounter_end_datetime dateTime NA encounter_end_datetime

Show details of one form

The details of a form are exactly the same as the output of ruODK::form_list().

fq_form_detail <- ruODK::form_detail()
fq_form_detail %>% knitr::kable(.)
name fid version state submissions created_at created_by_id created_by updated_at published_at last_submission hash
Flora Quadrat 0.4 Flora-Quadrat-04 open 1 2020-11-02T02:56:21.085Z 5 Florian Mayer 2020-11-23T05:25:03.426Z 2020-11-02T02:56:25.092Z 2020-11-02T04:19:45.451Z 434ff9e1e33fc8bb35148c0cc6979708

Submissions

We are getting closer to the actual data! This section shows two of the options for data access: dump all submissions, or extract a subset.

Get all submissions for one form

Smaller datasets lend themselves to be exported in one go. ODK Central offers one giant zip file containing all submissions, any repeating groups, and any attachments both on the form submission page, and as API endpoint which is provided as ruODK::submission_export().

The default behaviour of ruODK::submission_export() is to write the zip file to the project root (here::here()), and to overwrite existing previous downloads. See ?ruODK::submission_export() for alternative download and retention options.

In the following chuck, we illustrate common tasks:

  • Download the zip file.
  • Unpack the zip file.
  • Join repeating form group data data_taxon to main data data_quadrat to annotate data_taxon with data from data_quadrat.
  • Sanitise the column names.
  • Prepend all attachment filenames (e.g. data_quadrat$location_quadrat_photo, data_taxon$photo_in_situ) with media/.
# Predict filenames (with knowledge of form)
fid <- ruODK::get_test_fid()
fid_csv <- fs::path(t, glue::glue("{fid}.csv"))
fid_csv_veg <- fs::path(t, glue::glue("{fid}-vegetation_stratum.csv"))
fid_csv_tae <- fs::path(t, glue::glue("{fid}-taxon_encounter.csv"))

# Download the zip file
se <- ruODK::submission_export(local_dir = t, overwrite = FALSE, verbose = TRUE)

# Unpack the zip file
f <- unzip(se, exdir = t)
fs::dir_ls(t)

# Prepend attachments with media/ to turn into relative file paths
fq_zip_data <- fid_csv %>% 
  readr::read_csv(na = c("", "NA", "na")) %>% # form uses "na" for NA
  janitor::clean_names(.) %>% 
  dplyr::mutate(id = meta_instance_id) %>% 
  ruODK::handle_ru_datetimes(fq_form_schema) %>% 
  ruODK::handle_ru_geopoints(fq_form_schema) %>% 
  ruODK::attachment_link(fq_form_schema)

fq_zip_strata <- fid_csv_veg %>% 
  readr::read_csv(na = c("", "NA", "na")) %>%
  janitor::clean_names(.) %>% 
  dplyr::mutate(id = parent_key) %>% 
  # ruODK::handle_ru_datetimes(fq_form_schema) parent_key%>% # no dates
  # ruODK::handle_ru_geopoints(fq_form_schema) %>%  # no geopoints
  # ruODK::ruODK::attachment_link(fq_form_schema) %>% # no att.
  dplyr::left_join(fq_zip_data, by = c("parent_key" = "meta_instance_id"))

fq_zip_taxa <- fid_csv_tae %>%
  readr::read_csv(na = c("", "NA", "na")) %>%
  janitor::clean_names(.) %>% 
  dplyr::mutate(id = parent_key) %>% 
  # ruODK::handle_ru_datetimes(fq_form_schema) %>% 
  # ruODK::handle_ru_geopoints(fq_form_schema) %>% 
  # ruODK::ruODK::attachment_link(fq_form_schema) %>%
  dplyr::left_join(fq_zip_data, by = c("parent_key" = "meta_instance_id"))
head(fq_zip_data)
#> # A tibble: 1 × 37
#>   submission_date     meta_instance_id    encounter_start_da… reporter device_id
#>   <dttm>              <chr>               <dttm>              <lgl>    <chr>    
#> 1 2020-11-02 04:19:45 uuid:469f71d3-d7aa… 2020-11-02 12:06:19 NA       5afb51f3…
#> # … with 32 more variables: location_area_name <chr>,
#> #   location_quadrat_photo <chr>, location_corner1_latitude <dbl>,
#> #   location_corner1_longitude <dbl>, location_corner1_altitude <dbl>,
#> #   location_corner1_accuracy <dbl>, habitat_morphological_type <chr>,
#> #   habitat_morphological_type_photo <chr>, perimeter_corner2_latitude <dbl>,
#> #   perimeter_corner2_longitude <dbl>, perimeter_corner2_altitude <dbl>,
#> #   perimeter_corner2_accuracy <dbl>, perimeter_corner3_latitude <dbl>, …
head(fq_zip_strata)
#> # A tibble: 3 × 46
#>   nvis_level3_broa… max_height_m foliage_cover dominant_specie… dominant_specie…
#>   <chr>                    <dbl> <chr>         <chr>            <chr>           
#> 1 c1.0_surface_cru…          0.1 5-0           Lichen sp 1      Lichen sp 2     
#> 2 w3.0_shrub                 0.5 30-10         Shrub sp 1       Shrub sp 2      
#> 3 w2.1_mallee                2   5-0           Mallee sp 1      Mallee sp 2     
#> # … with 41 more variables: dominant_species_3 <chr>, dominant_species_4 <chr>,
#> #   parent_key <chr>, key.x <chr>, id.x <chr>, submission_date <dttm>,
#> #   encounter_start_datetime <dttm>, reporter <lgl>, device_id <chr>,
#> #   location_area_name <chr>, location_quadrat_photo <chr>,
#> #   location_corner1_latitude <dbl>, location_corner1_longitude <dbl>,
#> #   location_corner1_altitude <dbl>, location_corner1_accuracy <dbl>,
#> #   habitat_morphological_type <chr>, habitat_morphological_type_photo <chr>, …
head(fq_zip_taxa)
#> # A tibble: 2 × 48
#>   field_name photo_in_situ     taxon_encounter… taxon_encounter… taxon_encounter…
#>   <chr>      <chr>                        <dbl>            <dbl>            <dbl>
#> 1 Mallee 1   1604290400891.jpg            -32.0             116.            -16.5
#> 2 Shrub 1    1604290499008.jpg            -32.0             116.            -16.8
#> # … with 43 more variables: taxon_encounter_location_accuracy <dbl>,
#> #   life_form <chr>, voucher_specimen_barcode <chr>,
#> #   voucher_specimen_label <chr>, parent_key <chr>, key.x <chr>, id.x <chr>,
#> #   submission_date <dttm>, encounter_start_datetime <dttm>, reporter <lgl>,
#> #   device_id <chr>, location_area_name <chr>, location_quadrat_photo <chr>,
#> #   location_corner1_latitude <dbl>, location_corner1_longitude <dbl>,
#> #   location_corner1_altitude <dbl>, location_corner1_accuracy <dbl>, …
# Further: create map with popups, see vignette "odata"

List submissions for one form

Not always is it appropriate to download all submissions and all attachments at once.

If forms feed into downstream data warehouses, the typical ETL workflow is to

  • List all submissions from ODK Central
  • Select the subset of new submissions to download, e.g.
    • Submissions younger than the oldest submission date in the data warehouse.
    • Submissions whose instance_id is not already present in the data warehouse.
  • Download only the selected submissions.
  • Download attachments of only the selected submissions.
fq_submission_list <- ruODK::submission_list()
fq_submission_list %>% knitr::kable(.)
instance_id submitter_id device_id created_at submitter_id_2 submitter_type submitter_display_name submitter_created_at
uuid:469f71d3-d7aa-4c74-8aaa-af5f667a2f28 53 android_id:5afb51f35ba0c572 2020-11-02 12:19:45 53 field_key ruODK 2020-11-02 10:04:58

The list of submissions critically contains each submission’s unique ID in instance_id. If the submissions shall be downloaded and uploaded into another data warehouse, the instance_id can be used to determine whether a record already exists in the downstream warehouse or not. This workflow is preferable where the majority of submissions is already imported into another downstream data warehouse, and we only want to add new submissions, as in submissions which are not already imported into the data warehouse.

Furthermore, the instance_ids can now be used to retrieve the actual submissions.

Get submission data

In order to import each submission, we need to retrieve the data by instance_id.

# One submission
fq_one_submission <- ruODK::get_one_submission(fq_submission_list$instance_id[[1]])

# Multiple submissions
fq_submissions <- ruODK::submission_get(fq_submission_list$instance_id)

Parse submissions

The data in sub is one row of the bulk downloaded submissions in data_quadrat. The data in submissions represents all (or let’s pretend, the selected) submissions in data_quadrat. The field xml contains the actual submission data including repeating groups.

The structure is different to the output of ruODK::odata_submission_get, therefore ruODK::odata_submission_rectangle does not work for those, as here we might have repeating groups included in a submission.

This structure could be used for upload into data warehouses accepting nested data as e.g. JSON.

if (requireNamespace("listviewer")) {
  listviewer::jsonedit(fq_submissions, mode = "code")
} else {
  ru_msg_info("Please install package listviewer!")
}

Outlook

The approach shown here yields nested and stand-alone records, which is useful if the subsequent use requires records in nested JSON or XML format. Complex forms with repeating sub-groups will result in highly nested lists, whose structure heavily depends on the completeness of the submissions.

The other approach shown in vignette("odata-api", package="ruODK") yields rectangled data in several normalised tables, which is useful for analysis and visualisation.