Update a resource using a field mask

This document shows you how to update a resource using a field mask in the Google Cloud client libraries for Swift to control which fields on the resource you modify. The examples use a secret from Secret Manager as a sample resource. The same concepts apply across Google Cloud services that follow the AIP-134 update specification and AIP-161 field mask specification on google.aip.dev.

Before you begin

This document uses the Secret Manager API. To enable this API, follow the Secret Manager quickstart. Verify that your principal has permissions to create and update secrets, such as the Secret Manager Admin Identity and Access Management (IAM) role (roles/secretmanager.admin).

For complete setup instructions for the Swift client libraries, see Quickstart: Get started with Swift.

Optional: Install well-known types for dynamic masks

The swift-google-wkt package (GoogleWKT module) provides Protocol Buffer well-known types for Google Cloud APIs, including WKTFieldMask. If your app constructs dynamic field masks using WKTFieldMask(paths:), follow these steps to add swift-google-wkt as a dependency:

  1. Add the swift-google-wkt package to your Package.swift dependencies:

    swift package add-dependency \
        https://github.com/googleapis/swift-google-wkt.git --from 0.6.0
    
  2. Add the GoogleWKT module as a dependency of your target:

    swift package add-target-dependency \
        GoogleWKT TARGET_NAME \
        --package swift-google-wkt
    

    Replace TARGET_NAME with the name of your target.

The WKTFieldMask type

A WKTFieldMask instance represents a set of symbolic field paths, such as paths: ["annotations", "labels"] or paths: ["user.display_name", "photo"]. You use field masks to specify which fields a read operation returns or which fields an update operation modifies.

In an update operation, the API modifies only the fields listed in the field mask and leaves all other fields unchanged. If you provide a resource with additional modified fields, the API ignores any fields not covered by the mask. For services that support full resource replacement, you can pass the wildcard mask ["*"] to update all fields.

WKTFieldMask conforms to ExpressibleByArrayLiteral, which lets you specify field masks in two ways:

  • Array literals: use array literals such as updateMask: ["annotations", "labels"] when you know the fields to update at compile time. This style is concise and doesn't require importing GoogleWKT.
  • Explicit initializers: use WKTFieldMask(paths: myPaths) when your app computes the list of fields dynamically at runtime from a [String] collection. This style requires importing GoogleWKT and adding the swift-google-wkt package on GitHub as a dependency.

Field paths use the lowercase, underscore-separated field names from the protobuf definition relative to the updated resource—for example, "version_aliases" rather than the Swift property name versionAliases.

To reset a field to its default value, include the field path in the mask and leave that field set to its default value on the provided resource.

Update fields on a resource

To update specific fields on a secret resource, follow these steps:

  1. Add the imports required to use the Secret Manager client library:

    import Foundation
    import GoogleCloudSecretManagerV1

  2. Define a function that receives the project ID and secret ID as parameters:

    func sample(projectId: String, secretId: String) async throws {

  3. Initialize a Secret Manager client and create a secret. When you create the secret, both the labels and annotations dictionaries are empty:

    let client = try SecretManagerServiceClient()
    
    let secret = try await client.createSecret(
      parent: "projects/\(projectId)",
      secretId: secretId,
      secret: Secret().with {
        $0.replication = Replication().with { replication in
          replication.replication = .automatic(Replication.Automatic())
        }
      }
    )
    print("CREATE = \(secret)")

  4. Construct a Secret object containing the updated labels and annotations, along with the resource name and etag field. Setting etag prevents overwriting concurrent updates:

    var labels = secret.labels
    labels["updated"] = "your-label"
    var annotations = secret.annotations
    annotations["updated"] = "your-annotations"
    
    let updatedSecret = Secret().with {
      $0.name = secret.name
      $0.etag = secret.etag
      $0.labels = labels
      $0.annotations = annotations
    }

  5. Call updateSecret(secret:updateMask:), passing an array literal with the annotations and labels field paths to update only those fields:

    let update = try await client.updateSecret(
      secret: updatedSecret,
      updateMask: ["annotations", "labels"]
    )
    print("UPDATE = \(update)")

When updateSecret(secret:updateMask:) succeeds, it returns the updated Secret resource with the new labels and annotations. You can verify the updated fields by running gcloud secrets describe:

gcloud secrets describe SECRET_ID

Replace SECRET_ID with your secret ID.

Clean up

To avoid incurring charges on your Google Cloud account for the resources used in this document, see Secret Manager pricing and delete the secret you created:

gcloud secrets delete SECRET_ID

Complete code

The following example shows the complete code for this document:

import Foundation
import GoogleCloudSecretManagerV1

func sample(projectId: String, secretId: String) async throws {
  let client = try SecretManagerServiceClient()

  let secret = try await client.createSecret(
    parent: "projects/\(projectId)",
    secretId: secretId,
    secret: Secret().with {
      $0.replication = Replication().with { replication in
        replication.replication = .automatic(Replication.Automatic())
      }
    }
  )
  print("CREATE = \(secret)")

  var labels = secret.labels
  labels["updated"] = "your-label"
  var annotations = secret.annotations
  annotations["updated"] = "your-annotations"

  let updatedSecret = Secret().with {
    $0.name = secret.name
    $0.etag = secret.etag
    $0.labels = labels
    $0.annotations = annotations
  }

  let update = try await client.updateSecret(
    secret: updatedSecret,
    updateMask: ["annotations", "labels"]
  )
  print("UPDATE = \(update)")
}

What's next