编程 用 Rust 玩转 Google Sheets API

2024-11-19 02:36:20 +0800 CST views 1342

用 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 之前,你需要完成以下步骤:

  1. 访问 Google Cloud Console 并创建一个新项目。
  2. 在项目中启用 Google Sheets API
  3. 创建一个服务帐户,并下载 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 的强大功能。

复制全文 生成海报 编程 API Rust Google 数据管理

推荐文章

goctl 技术系列 - Go 模板入门
2024-11-19 04:12:13 +0800 CST
Go 并发利器 WaitGroup
2024-11-19 02:51:18 +0800 CST
解决 PHP 中的 HTTP 请求超时问题
2024-11-19 09:10:35 +0800 CST
Go 如何做好缓存
2024-11-18 13:33:37 +0800 CST
如何在Vue3中处理全局状态管理?
2024-11-18 19:25:59 +0800 CST
MySQL死锁 - 更新插入导致死锁
2024-11-19 05:53:50 +0800 CST
一键配置本地yum源
2024-11-18 14:45:15 +0800 CST
Vue3中如何进行异步组件的加载?
2024-11-17 04:29:53 +0800 CST
File 和 Blob 的区别
2024-11-18 23:11:46 +0800 CST
Web 端 Office 文件预览工具库
2024-11-18 22:19:16 +0800 CST
Vue中的样式绑定是如何实现的?
2024-11-18 10:52:14 +0800 CST
使用Rust进行跨平台GUI开发
2024-11-18 20:51:20 +0800 CST
Redis和Memcached有什么区别?
2024-11-18 17:57:13 +0800 CST
Go配置镜像源代理
2024-11-19 09:10:35 +0800 CST
四舍五入五成双
2024-11-17 05:01:29 +0800 CST
vue打包后如何进行调试错误
2024-11-17 18:20:37 +0800 CST
程序员茄子在线接单