I have a data structure similar to this that I want to post to firestore database via REST API:
I manually created the House1 document, then Floor1 and Ground.
Ground contains the data:
Now, I am trying to use the firestore REST API in R to create the same thing.
library(httr)
library(jsonlite)
# POST function
post_data_to_firestore <- function(path, data, auth_token) {
r <- httr::POST(
url = sprintf("https://firestore.googleapis.com/v1beta1/%s", path),
config = httr::add_headers(
"Content-Type" = "application/json",
"Authorization" = paste("Bearer", auth_token)
),
body = data
)
return(r)
}
PROJECT_NAME <- "firebase-project"
COLLECTION <- "Block"
accessTokenu <- "access-token"
endpoint <- paste0("projects/", PROJECT_NAME, "/databases/(default)/documents/", COLLECTION)
data_list <- toJSON(
list(
fields = list(
Name = list("stringValue" = "Ground")
)
), auto_unbox = TRUE
)
post_data_to_firestore(
path = paste0(endpoint, "/House2/Floor1", "?documentId=", "Ground"),
data = data_list,
auth_token = accessTokenu
)
This creates House2 which is a non-existent document according to firestore. I understand that all I have created here is only Ground that contains Name:
How do I change my POST request to ensure that I properly create documents so that I can query them?
When you manually added House1 using the Firebase Console, you would have clicked the "Add Document" button for House1, then you clicked "Start Collection" for Floor1, then you clicked "Add Document" for Ground and again for Top.
So manually (via Firebase Console) you created 3 documents:
Block/House1Block/House1/Floor1/GroundBlock/House1/Floor1/TopBut your REST API is creating a single document:
Block/House2/Floor1/Ground