DEV Community

Rohan Rajpal
Rohan Rajpal

Posted on

Rust + Google Sheets API Quickstart

Google sheets API is a very useful tool. For MVPs and prototypes it works amazing, no need for SQL setup and you have a very powerful database frontend (google sheets) to interact with.

Recently I've been learning Rust and wanted to work with Sheets API using Rust.

Sadly, the sheets documentation has no quickstart of Rust mentioned.

So this post, you'll learn how to use Sheets API with Rust.

cargo new sheets_api_rust
Enter fullscreen mode Exit fullscreen mode

Your Cargo.toml should look like:

[package]
name = "sheets_api_rust"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[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",
] }
Enter fullscreen mode Exit fullscreen mode

and obtain your api keys from google.

your credentials.json should look like

{
  "installed": {
    "client_id": "384278056379-tr5pbot1mil66749n639jo54i4840u77.apps.googleusercontent.com",
    "project_id": "sanguine-rhythm-105020",
    "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": "QeQUnhzsiO4t--ZGmj9muUAu",
    "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"]
  }
}
Enter fullscreen mode Exit fullscreen mode

and finally your main.rs

// This is a modified version of the example at:
// https://github.com/Byron/google-apis-rs/tree/main/gen/sheets4

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() {
    // Get an ApplicationSecret instance by some means. It contains the `client_id` and
    // `client_secret`, among other things.
    let secret = yup_oauth2::read_application_secret("clientsecret.json")
        .await
        .expect("client secret could not be read");

    // Instantiate the authenticator. It will choose a suitable authentication flow for you,
    // unless you replace  `None` with the desired Flow.
    // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
    // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
    // retrieve them from storage.
    let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
        secret,
        yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
    )
    .persist_tokens_to_disk("tokencache.json")
    .build()
    .await
    .unwrap();

    let hub = Sheets::new(
        hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()),
        auth,
    );

    let result = hub
        .spreadsheets()
        .get("1TWUpZdjXiquf-LsfbqXEIBVWgZ12XeaZtzrNp3uaHX8") // your spreadsheet id enters here
        .doit()
        .await;

    // println!("{:?}",result);
    match result {
        Err(e) => match e {
            // The Error enum provides details about what exactly happened.
            // You can also just use its `Debug`, `Display` or `Error` traits
            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!("Success: {:?}", res),
    }
}
Enter fullscreen mode Exit fullscreen mode

and boom, now you can explore the sheets4 docs to see what more you can do!

References

  1. https://github.com/Byron/google-apis-rs/tree/main/gen/sheets4
  2. https://github.com/dermesser/yup-oauth2/tree/master/examples/drive_example

Discussion (1)