DEV Community

Cover image for Fetching data with Rust
artydev
artydev

Posted on

Fetching data with Rust

use serde::Deserialize;

#[derive(Deserialize)]
struct Product {
    id: u32,
    title: String,
    brand: Option<String>,
    price: f64,
    rating: f64,
    stock: u32,
    category: String,
}

#[derive(Deserialize)]
struct ApiResponse {
    products: Vec<Product>,
    total: u64,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let response = reqwest::get("https://dummyjson.com/products")
        .await?
        .json::<ApiResponse>()
        .await?;

    // Display the products in a formatted table
    println!("\n{:<5} {:<30} {:<15} {:<10} {:<8} {:<8} {:<10}",
             "ID", "Title", "Brand", "Price", "Rating", "Stock", "Category");
    println!("{}", "=".repeat(100));

    for product in response.products.iter().take(60) {
        let brand = product.brand.as_deref().unwrap_or("Unknown");

        println!("{:<5} {:<30} {:<15} ${:<9.2} {:<8.1} {:<8} {:<10}",
                 product.id,
                 truncate_string(&product.title, 30),
                 truncate_string(brand, 15),
                 product.price,
                 product.rating,
                 product.stock,
                 truncate_string(&product.category, 10));
    }

    println!("\nTotal products fetched: {}", response.total);
    println!("Showing first {} out of {} products", response.products.len().min(60), response.total);

    Ok(())
}

fn truncate_string(s: &str, max_len: usize) -> String {
    if s.chars().count() <= max_len {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max_len - 3).collect();
        format!("{}...", truncated)
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
leob profile image
leob

Did you ever check out Haskell? When I did that bit of "Rust learning", I couldn't help but see many big similarities between Rust and Haskell - I think that's what fascinated me most, because Rust isn't generally seen as an "FP" (functional programming) language ...

Collapse
 
artydev profile image
artydev

Hy Leob,

I know Haskell, but I have never used trying to learn it .
Not because I don't like it, just a question of time and paracticity.