Last active
February 3, 2023 07:08
-
-
Save Hevanafa/100c62b75d489fb7e7fa8dc02926da53 to your computer and use it in GitHub Desktop.
Rust Bored API (reqwest + serde) Example
This file contains 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
[package] | |
name = "bored_api_rs" | |
version = "0.1.0" | |
edition = "2021" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
reqwest = { version = "0.11.14", features = ["json"] } | |
serde = { version = "1.0.152", features = ["derive"] } | |
tokio = { version = "1.25.0", features = ["full"] } |
This file contains 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; | |
// Ref: | |
// https://www.boredapi.com/documentation | |
#[derive(Deserialize)] | |
struct Activity { | |
activity: String, | |
#[serde(rename = "type")] | |
_type: String, | |
participants: u32, | |
price: f32, | |
link: Option<String>, | |
key: String, | |
accessibility: f32, | |
} | |
#[tokio::main] | |
async fn main() { | |
let res = reqwest::get("https://www.boredapi.com/api/activity/").await; | |
println!("Get a random activity!"); | |
match res { | |
Ok(res) => { | |
let res = res.json::<Activity>().await; | |
match res { | |
Ok(activity) => { | |
println!("Activity key: {}\n", activity.key); | |
println!("{}!", activity.activity); | |
println!("This activity needs {} participant(s).", activity.participants); | |
println!("Price: {}", | |
if activity.price > 0.0 { | |
activity.price.to_string() | |
} else { | |
"Free".to_owned() | |
}); | |
if let Some(link) = activity.link { | |
if link.len() > 0 { | |
println!("Link: {}", link); | |
} | |
} | |
}, | |
Err(e) => { | |
eprintln!("{:?}", e); | |
} | |
} | |
}, | |
Err(e) => { | |
eprintln!("{:?}", e); | |
} | |
} | |
} |
This file contains 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
Get a random activity! | |
Activity key: 2790297 | |
Learn how to whistle with your fingers! | |
This activity needs 1 participant(s). | |
Price: Free |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment