编程 用 Rust 玩转 Google Sheets API

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

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

推荐文章

Vue3中如何实现插件?
2024-11-18 04:27:04 +0800 CST
html一份退出酒场的告知书
2024-11-18 18:14:45 +0800 CST
php内置函数除法取整和取余数
2024-11-19 10:11:51 +0800 CST
记录一次服务器的优化对比
2024-11-19 09:18:23 +0800 CST
mysql 计算附近的人
2024-11-18 13:51:11 +0800 CST
liunx服务器监控workerman进程守护
2024-11-18 13:28:44 +0800 CST
pycm:一个强大的混淆矩阵库
2024-11-18 16:17:54 +0800 CST
js一键生成随机颜色:randomColor
2024-11-18 10:13:44 +0800 CST
纯CSS绘制iPhoneX的外观
2024-11-19 06:39:43 +0800 CST
2024年微信小程序开发价格概览
2024-11-19 06:40:52 +0800 CST
Vue3中的自定义指令有哪些变化?
2024-11-18 07:48:06 +0800 CST
利用Python构建语音助手
2024-11-19 04:24:50 +0800 CST
ElasticSearch 结构
2024-11-18 10:05:24 +0800 CST
Go 如何做好缓存
2024-11-18 13:33:37 +0800 CST
goctl 技术系列 - Go 模板入门
2024-11-19 04:12:13 +0800 CST
ElasticSearch简介与安装指南
2024-11-19 02:17:38 +0800 CST
MySQL数据库的36条军规
2024-11-18 16:46:25 +0800 CST
内网穿透技术详解与工具对比
2025-04-01 22:12:02 +0800 CST
2025年,小程序开发到底多少钱?
2025-01-20 10:59:05 +0800 CST
php常用的正则表达式
2024-11-19 03:48:35 +0800 CST
Linux 常用进程命令介绍
2024-11-19 05:06:44 +0800 CST
Rust开发笔记 | Rust的交互式Shell
2024-11-18 19:55:44 +0800 CST
PHP设计模式:单例模式
2024-11-18 18:31:43 +0800 CST
程序员茄子在线接单