Sample code for 30+ languages & platforms
Rust

Download Photo to a File

See more Facebook Examples

Assuming we have the ID of a Photo, this example demonstrates how to download the photo image data to a file.

Chilkat Rust Downloads

Rust

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

// This example assumes a previously obtained an access token
let oauth2 = chilkat::OAuth2::new();
oauth2.set_access_token("FACEBOOK-ACCESS-TOKEN");

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

// Connect to Facebook...
if rest.connect("graph.facebook.com", 443, true, true).is_err() {
    println!("{}", rest.last_error_text());
    return;
}

// Provide the authentication credentials (i.e. the access key)
let _ = rest.set_auth_o_auth2(&oauth2);

// Assumes we've already obtained a Photo ID.
let photo_id = "10210199026347451".to_string();

let sb_path = chilkat::StringBuilder::new();
let _ = sb_path.append("/v2.7/");
let _ = sb_path.append(&photo_id);

// First we're going to get the photo informaton so we can get the URL of the image file data.
// Select the fields we want.
// See https://developers.facebook.com/docs/graph-api/reference/photo/
let _ = rest.add_query_param("fields", "id,album,images");

let Ok(response_json) = rest.full_request_no_body("GET", &sb_path.get_as_string().unwrap_or_default()) else {
    println!("{}", rest.last_error_text());
    return;
};

let json = chilkat::JsonObject::new();
json.set_emit_compact(false);
let _ = json.load(&response_json);

// Show the JSON in human-readable format.
println!("{}", json.emit().unwrap_or_default());

// Get the image URL.
let image_url = json.string_of("images[0].source").unwrap_or_default();
println!("Downloading from {}", image_url);

let sb_image_url = chilkat::StringBuilder::new();
let _ = sb_image_url.append(&image_url);

// Build the output local file path.
let sb_to_path = chilkat::StringBuilder::new();
let _ = sb_to_path.append("qa_output/fb");
let _ = sb_to_path.append(&json.string_of("id").unwrap_or_default());
let b_case_sensitive = false;
if sb_image_url.contains(".jpg", b_case_sensitive) {
    let _ = sb_to_path.append(".jpg");
} else {
    let _ = sb_to_path.append(".png");
}

println!("Downloading to {}", sb_to_path.get_as_string().unwrap_or_default());

// Download using Chilkat HTTP.
let http = chilkat::Http::new();
if http.download(&image_url, &sb_to_path.get_as_string().unwrap_or_default()).is_err() {
    println!("{}", http.last_error_text());
} else {
    println!("Downloaded.");
}