Initialize a client

The Cloud Client Libraries for Rust use client structs as the main interface to Google Cloud services, with methods corresponding to each RPC offered by the service. Before calling a service, you initialize its client.

This document shows you how to initialize a Secret Manager client with its default configuration and call an RPC. The same pattern applies to all other Google Cloud services.

Before you begin

Before running the code in this document, complete the following prerequisites:

Dependencies

Add the required crates to your Cargo.toml file:

cargo add google-cloud-secretmanager-v1 google-cloud-gax anyhow
cargo add tokio --features macros,rt-multi-thread

Initialize a client and make an RPC

To initialize a client, call builder on the client struct to obtain a ClientBuilder and then call build. Complete the following steps to initialize a client with default settings and call an RPC:

  1. Import the SecretManagerService client type:

    use google_cloud_secretmanager_v1::client::SecretManagerService;

  2. Build the client with its default configuration:

    let client = SecretManagerService::builder().build().await?;

  3. Use the initialized client to call list_locations, which lists the locations supported by Secret Manager for your project:

    use google_cloud_gax::paginator::Paginator as _;
    let mut items = client
        .list_locations()
        .set_name(format!("projects/{project_id}"))
        .by_page();
    while let Some(page) = items.next().await {
        let page = page?;
        for location in page.locations {
            println!("{}", location.name);
        }
    }

The output resembles the following:

projects/PROJECT_NUMBER/locations/europe-west8
projects/PROJECT_NUMBER/locations/europe-west9
projects/PROJECT_NUMBER/locations/us-east5

In this output, PROJECT_NUMBER is the numeric project number for your Google Cloud project.

Complete code

The following example combines client initialization and the list_locations call into a runnable program:

pub async fn initialize_client(project_id: &str) -> anyhow::Result<()> {
    use google_cloud_secretmanager_v1::client::SecretManagerService;

    // Initialize a client with the default configuration. This is an
    // asynchronous operation that may fail, as it requires acquiring an an
    // access token.
    let client = SecretManagerService::builder().build().await?;

    // Once initialized, use the client to make requests.
    use google_cloud_gax::paginator::Paginator as _;
    let mut items = client
        .list_locations()
        .set_name(format!("projects/{project_id}"))
        .by_page();
    while let Some(page) = items.next().await {
        let page = page?;
        for location in page.locations {
            println!("{}", location.name);
        }
    }

    Ok(())
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let project_id = std::env::args().nth(1).unwrap();

    initialize_client(&project_id).await
}