Skip to content

Instantly share code, notes, and snippets.

@Hevanafa
Last active February 3, 2023 07:08
Show Gist options
  • Save Hevanafa/100c62b75d489fb7e7fa8dc02926da53 to your computer and use it in GitHub Desktop.
Save Hevanafa/100c62b75d489fb7e7fa8dc02926da53 to your computer and use it in GitHub Desktop.
Rust Bored API (reqwest + serde) Example
[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"] }
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);
}
}
}
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