编程 用 Rust 玩转 Google Sheets API

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

用 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 数据管理

推荐文章

MySQL 1364 错误解决办法
2024-11-19 05:07:59 +0800 CST
Nginx 状态监控与日志分析
2024-11-19 09:36:18 +0800 CST
PHP 微信红包算法
2024-11-17 22:45:34 +0800 CST
Vue3中如何处理权限控制?
2024-11-18 05:36:30 +0800 CST
Linux查看系统配置常用命令
2024-11-17 18:20:42 +0800 CST
如何在 Linux 系统上安装字体
2025-02-27 09:23:03 +0800 CST
淘宝npm镜像使用方法
2024-11-18 23:50:48 +0800 CST
FastAPI 入门指南
2024-11-19 08:51:54 +0800 CST
Mysql允许外网访问详细流程
2024-11-17 05:03:26 +0800 CST
Nginx 反向代理 Redis 服务
2024-11-19 09:41:21 +0800 CST
企业官网案例-芊诺网络科技官网
2024-11-18 11:30:20 +0800 CST
在 Vue 3 中如何创建和使用插件?
2024-11-18 13:42:12 +0800 CST
Python 微软邮箱 OAuth2 认证 Demo
2024-11-20 15:42:09 +0800 CST
介绍 Vue 3 中的新的 `emits` 选项
2024-11-17 04:45:50 +0800 CST
html5在客户端存储数据
2024-11-17 05:02:17 +0800 CST
MySQL 主从同步一致性详解
2024-11-19 02:49:19 +0800 CST
程序员茄子在线接单