Sample code for 30+ languages & platforms
Rust

Download Text File to a String Variable

See more Google Drive Examples

This example demonstrates how to download the content of a text file from Google Drive into a string variable.

Chilkat Rust Downloads

Rust

let _ = true;

// It requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

// This example uses a previously obtained access token having permission for the 
// Google Drive scope.

let g_auth = chilkat::AuthGoogle::new();
g_auth.set_access_token("GOOGLE-DRIVE-ACCESS-TOKEN");

let rest = chilkat::Rest::new();

// Connect using TLS.
// A single REST object, once connected, can be used for many Google Drive REST API calls.
// The auto-reconnect indicates that if the already-established HTTPS connection is closed,
// then it will be automatically re-established as needed.
let b_auto_reconnect = true;
let _ = rest.connect("www.googleapis.com", 443, true, b_auto_reconnect).is_ok();

// Provide the authentication credentials (i.e. the access token)
let _ = rest.set_auth_google(&g_auth);

// ------------------------------------------------------------------------------
// To download a file, we must know the file ID.
// In a previous example (see Build Local Metadata Cache
// we built a local cache to make it easy to lookup file IDs given a file path.
// Let's say we want to download "testFolder/abc/123/pigs.json".
// First we lookup the fileId in the cache.  With the fileId, we can download the file.
let gd_cache = chilkat::Cache::new();
gd_cache.set_level(0);
gd_cache.add_root("C:/ckCache/googleDrive");

let Ok(file_id) = gd_cache.fetch_text("testFolder/abc/123/pigs.json") else {
    println!("Filepath not found in cache.");
    return;
};

// We need to send a GET request like this:
// GET https://www.googleapis.com/drive/v3/files/fileId?alt=media
// The fileId is part of the path.
let sb_path = chilkat::StringBuilder::new();
let _ = sb_path.append("/drive/v3/files/");
let _ = sb_path.append(&file_id);
let _ = rest.add_query_param("alt", "media");

// The FullRequestNoBody returns the file content in the response body.
let Ok(file_content) = rest.full_request_no_body("GET", &sb_path.get_as_string().unwrap_or_default()) else {
    println!("{}", rest.last_error_text());
    return;
};

// A successful response will have a status code equal to 200.
if rest.response_status_code() != 200 {
    println!("response status code = {}", rest.response_status_code());
    println!("response status text = {}", rest.response_status_text());
    println!("response header: {}", rest.response_header());
    return;
}

println!("{}", file_content);

println!("File downloaded.");