用 Rust 玩转 Google Sheets API
在构建最小化可行产品 (MVP) 或原型时,Google Sheets API 是一个非常强大的工具。它不仅免去了数据库的繁琐设置,还提供了 Google Sheets 的强大前端界面,方便管理数据。本文将带你一步步使用 Rust 语言,解锁 Google Sheets API 的强大功能。
项目搭建
1. 创建 Rust 项目
首先,使用以下命令创建一个新的 Rust 项目:
cargo new sheets_api_rust
2. 添加依赖
在项目的 Cargo.toml
文件中,添加 Google Sheets API 所需的依赖:
[package]
name = "sheets_api_rust"
version = "0.1.0"
edition = "2018"
[dependencies]
google-sheets4 = "*"
hyper = "^0.14"
hyper-rustls = "^0.22"
serde = "^1.0"
serde_json = "^1.0"
yup-oauth2 = "^5.0"
tokio = { version = "~1.2", features = ["macros", "io-util", "rt", "rt-multi-thread", "fs"] }
API 密钥和凭据
1. 获取 Google Cloud 项目的 API 密钥
在使用 Google Sheets API 之前,你需要完成以下步骤:
- 访问 Google Cloud Console 并创建一个新项目。
- 在项目中启用 Google Sheets API。
- 创建一个服务帐户,并下载 JSON 格式的凭据文件。
将下载的凭据文件重命名为 credentials.json
并放置在项目的根目录下。该文件的内容类似如下:
{
"installed": {
"client_id": "YOUR_CLIENT_ID.apps.googleusercontent.com",
"project_id": "YOUR_PROJECT_ID",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "YOUR_CLIENT_SECRET",
"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"]
}
}
Rust 代码实现
接下来,打开 src/main.rs
文件,并粘贴以下代码:
extern crate google_sheets4 as sheets4;
extern crate hyper;
extern crate hyper_rustls;
extern crate yup_oauth2 as oauth2;
use sheets4::Error;
use sheets4::Sheets;
#[tokio::main]
async fn main() {
// 读取应用密钥
let secret = yup_oauth2::read_application_secret("credentials.json")
.await
.expect("无法读取应用密钥");
// 实例化身份验证器
let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
secret,
yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
)
.persist_tokens_to_disk("tokencache.json")
.build()
.await
.unwrap();
// 创建 Sheets 服务客户端
let hub = Sheets::new(
hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()),
auth,
);
// 获取指定电子表格的信息
let result = hub
.spreadsheets()
.get("YOUR_SPREADSHEET_ID") // 替换为你的电子表格 ID
.doit()
.await;
// 处理结果
match result {
Err(e) => match e {
Error::HttpError(_)
| Error::Io(_)
| Error::MissingAPIKey
| Error::MissingToken(_)
| Error::Cancelled
| Error::UploadSizeLimitExceeded(_, _)
| Error::Failure(_)
| Error::BadRequest(_)
| Error::FieldClash(_)
| Error::JsonDecodeError(_, _) => println!("{}", e),
},
Ok(res) => println!("操作成功: {:?}", res),
}
}
请将代码中的 YOUR_SPREADSHEET_ID
替换为你的 Google Sheets 电子表格 ID。你可以在 Google Sheets 的 URL 中找到它,格式类似于:
https://docs.google.com/spreadsheets/d/YOUR_SPREADSHEET_ID/edit#gid=0
运行程序
完成以上步骤后,使用以下命令运行程序:
cargo run
程序将尝试获取指定 Google 电子表格的信息,并在控制台输出结果。
探索更多功能
你已经成功使用 Rust 连接到 Google Sheets API。接下来可以探索更多 sheets4
crate 提供的功能,如读取、写入、更新和删除电子表格数据。
Sheets API
文档:https://docs.rs/google-sheets4/latest/google_sheets4/
通过学习和使用 Google Sheets API,你可以更高效地构建数据驱动的应用程序,并充分利用 Google Sheets 的强大功能。