Override the default endpoint

The Google Cloud client libraries for Swift automatically configure the endpoint for each service. Some applications might need to override the default endpoint, either because their network has specific requirements or because they need to use regional versions of a service. This document shows you how to override the default endpoint.

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 list secrets, such as the Secret Manager Viewer Identity and Access Management (IAM) role (roles/secretmanager.viewer).

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

Configure a regional endpoint

In this example, you configure the client library to use Secret Manager regional endpoints. You can use the same override to configure the endpoint with one of the private access options, or for locational endpoints in the services that support them.

To configure a regional endpoint, follow these steps:

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

    import Foundation
    import GoogleGax
    import GoogleCloudSecretManagerV1

  2. Write a function that receives the project ID and region as parameters:

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

  3. Initialize a client and override the endpoint to use a regional endpoint:

    let client = try SecretManagerServiceClient(
      ClientOptions().with {
        $0.endpoint = "https://secretmanager.\(region).rep.googleapis.com"
      })

  4. Use the client to retrieve the list of secrets in a region and iterate over the results:

    let secrets = client.listSecretsByItems(
      request: ListSecretsRequest().with { $0.parent = "projects/\(projectId)/locations/\(region)" })
    for try await item in secrets {
      print("  \(item)")
    }

After configuring the endpoint, running your application returns secrets stored in the specified region. You can also enable debug logging to verify that requests target the overridden host.

Complete code

The following example shows the complete code for this document:

import Foundation
import GoogleGax
import GoogleCloudSecretManagerV1

func sample(projectId: String, region: String) async throws {
  let client = try SecretManagerServiceClient(
    ClientOptions().with {
      $0.endpoint = "https://secretmanager.\(region).rep.googleapis.com"
    })
  let secrets = client.listSecretsByItems(
    request: ListSecretsRequest().with { $0.parent = "projects/\(projectId)/locations/\(region)" })
  for try await item in secrets {
    print("  \(item)")
  }
}

What's next