R code for creating a new form in Central from xls/xlsx using API

The following is my latest code to upload xlsx file into ODK Central:

centralupload <- function(){
  library(glue)

  ## Assign values to variables  
  server <- 'myServerURL'
  pid <- 'myProjectId'
  url <- glue('{server}/v1/projects/{pid}/forms?ignoreWarnings=true')

  username <- 'myusername'
  password <- 'mypassword'

  ## File location, you might want to give absolute link to the file
  xlsxfile <- 'test.xlsx'

  ## POST form in xlsx format to Central
  ## Construct the body 
  mybody <- httr::upload_file(xlsxfile, type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  
  ## Upload the file
  ## Note that  header "X-XlsForm-FormId-Fallback"  must be included, 
  ## but if you have form ID in the excel file the argument you are sending 
  ## with this header will be ignored.
  r <- httr::POST(url,
                  httr::add_headers('X-XlsForm-FormId-Fallback' = 'test_survey'),
                  httr::authenticate(username, password),
                  body = mybody
  )
  
  httr::http_status(r) -> publish.status
  httr::content(r, "parsed")  -> publish.data

}

This will upload form into ODK Central as draft, and one more step is needed to publish it:

publishdraft <- function(){
  library(glue)

  ## Assign values to variables
  server <- 'myServerURL'
  pid <- 'myProjectId'
  formid <- 'myformid'
  version <- '1' # you might want to increase it when uploading a new versions

  username <- 'myusername'
  password <- 'mypassword'

  url <- glue("{server}/v1/projects/{pid}/forms/{formid}/draft/publish?version={version}")
  
  ## Publish draft form in  Central server
  r <- httr::POST(url, httr::authenticate(username, password))
  
  httr::http_status(r) -> publish.status
  httr::content(r, "parsed")  -> publish.data
}

Hope this helps.

2 Likes