Search code examples
androidresthttpurlconnectiongoogle-cloud-firestoregoogle-apis-explorer

Firestore add Field to Document with POST request and HttpsURLConnection


Even after playing with Google's APIs Explorer for many hours I can't figure it out. I want to add a single field using HTTPS requests provided the document path.

Example of my PATCH function (this one works)

private void PATCHRequest(String document_path, String theData) throws IOException, JSONException {

    // Build URL
    String FirestoreURL = REST_HEADER + "projects/" + PROJECT_ID + "/databases/(default)/documents/" + document_path;

    // Create URL
    URL cloudFirestoreEndPoint = new URL(FirestoreURL);

    // Create connection
    myHttpsConnection = (HttpsURLConnection) cloudFirestoreEndPoint.openConnection();

    // Set Writable
    myHttpsConnection.setDoOutput(true);

    // Set Request Method
    myHttpsConnection.setRequestMethod("PATCH");

    // Set Https Connection properties
    myHttpsConnection.setRequestProperty("Content-Type", "application/json");

    // Generate JSON from the data
    JSONObject myJSON = getJSONfromString(theData);

    if(myJSON != null){

        // Create output stream linked to our https connection
        OutputStreamWriter streamWriter = new OutputStreamWriter(myHttpsConnection.getOutputStream());

        // Write to buffer
        streamWriter.write(myJSON.toString());

        // Send out the buffer
        streamWriter.flush();

        // Close the stream
        streamWriter.close();
    }
}

Other Example my DELETE function,

private void DELETERequest(String document_path) throws IOException {

    // Build URL
    String FirestoreURL = REST_HEADER + "projects/" + PROJECT_ID + "/databases/(default)/documents/" + document_path;

    // Create URL
    URL cloudFirestoreEndPoint = new URL(FirestoreURL);

    // Create connection
    myHttpsConnection = (HttpsURLConnection) cloudFirestoreEndPoint.openConnection();

    // Set Writable
    myHttpsConnection.setDoOutput(true);

    // Set Request Method
    myHttpsConnection.setRequestMethod("DELETE");

    // Send the command
    myHttpsConnection.connect();

    // Result
    myResult_ = "deleted";
}

Based on this format does anybody know how to add a single field with a value?


Solution

  • I needed to use the updateMask field,

            if(fieldMasks_ != null) {
                for (int i = 0; i < fieldMasks_.size(); ++i) {
                    URL_str.append("updateMask.fieldPaths=").append(fieldMasks_.get(i).getName()).append("&");
                }
            }