Created
February 19, 2024 20:02
-
-
Save fancellu/055af6e1b575b67e42f6931c555cba5e to your computer and use it in GitHub Desktop.
Rust reqwest http client async json demo with serde
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use serde::Deserialize; | |
use std::time::Duration; | |
#[derive(Deserialize, Debug)] | |
struct Product { | |
id: i32, | |
title: String, | |
description: String, | |
price: f64, | |
#[serde(rename = "discountPercentage")] | |
discount_percentage: f64, | |
rating: f64, | |
stock: i32, | |
brand: String, | |
category: String, | |
thumbnail: String, | |
images: Vec<String>, | |
} | |
async fn getText(url: &str) -> Result<String, Box<dyn std::error::Error>> { | |
let body = reqwest::get(url).await?.text().await?; | |
Ok(body) | |
} | |
#[tokio::main] | |
async fn main() -> Result<(), Box<dyn std::error::Error>> { | |
let body2Result = getText("https://dummyjson.com/products/2").await; | |
let product: Product = serde_json::from_str(&body2Result?)?; | |
println!("product = {:?}", product); | |
tokio::time::sleep(Duration::from_secs(1)).await; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
product = Product { id: 2, title: "iPhone X", description: "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...", price: 899.0, discount
_percentage: 17.94, rating: 4.44, stock: 34, brand: "Apple", category: "smartphones", thumbnail: "https://cdn.dummyjson.com/product-images/2/thumbnail.jpg", images: ["https://cdn.dummyjs
on.com/product-images/2/1.jpg", "https://cdn.dummyjson.com/product-images/2/2.jpg", "https://cdn.dummyjson.com/product-images/2/3.jpg", "https://cdn.dummyjson.com/product-images/2/thumbnail.jpg"] }