How to initialize a client

The Google Cloud Client Libraries for Rust use "clients" as the main abstraction to interface with specific services. Clients are implemented as Rust structs, with methods corresponding to each RPC offered by the service. In other words, to use a Google Cloud service using the Rust client libraries you need to first initialize a client.

Prerequisites

In this guide we will initialize a client and then use the client to make a simple RPC. To make this guide concrete, we will use the Secret Manager API. The same structure applies to any other service in Google Cloud.

We recommend you follow one of the "Getting Started" guides for Secret Manager before attempting to use the client library, such as how to Create a secret. These guides cover service specific concepts in more detail, and provide detailed instructions with respect to project prerequisites than we can fit in this guide.

We also recommend you follow the instructions in the Authenticate for using client libraries guide. This guide will show you how to login to configure the Application Default Credentials used in this guide.

Dependencies

As it is usual with Rust, you must declare the dependency in your Cargo.toml file. We use:

google-cloud-secretmanager-v1 = { version = "0.2", path = "../../src/generated/cloud/secretmanager/v1" }

The default initialization is designed to meet the requirements for most cases. You create a default client using new():

let client = SecretManagerService::new().await?;

Once successfully initialized, you can use this client to make RPCs:

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

Full program

Putting all this code together into a full program looks as follows:

pub type Result = std::result::Result<(), Box<dyn std::error::Error>>; pub async fn initialize_client(project_id: &str) -> 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::new().await?; // Once initialized, use the client to make requests. let mut items = client .list_locations(format!("projects/{project_id}")) .paginator() .await; while let Some(page) = items.next().await { let page = page?; for location in page.locations { println!("{}", location.name); } } Ok(()) }