2023-05-13 15:38:07 -04:00
|
|
|
use serde::Deserialize;
|
|
|
|
|
2023-05-13 14:54:41 -04:00
|
|
|
#[tokio::main]
|
|
|
|
async fn main() {
|
2023-05-13 16:24:05 -04:00
|
|
|
let url = get_cat_image_url().await.unwrap();
|
|
|
|
println!("The image is at {}", url);
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn get_cat_image_url() -> color_eyre::Result<String> {
|
|
|
|
let api_url = "https://api.thecatapi.com/v1/images/search";
|
|
|
|
let res = reqwest::get(api_url).await?;
|
2023-05-13 15:38:07 -04:00
|
|
|
if !res.status().is_success() {
|
2023-05-13 16:24:05 -04:00
|
|
|
return Err(color_eyre::eyre::eyre!(
|
|
|
|
"The Cat API returned HTTP {}",
|
|
|
|
res.status()
|
|
|
|
));
|
2023-05-13 15:38:07 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct CatImage {
|
|
|
|
url: String,
|
|
|
|
}
|
|
|
|
|
2023-05-13 16:24:05 -04:00
|
|
|
let mut images: Vec<CatImage> = res.json().await?;
|
|
|
|
if let Some(image) = images.pop() {
|
|
|
|
Ok(image.url)
|
|
|
|
} else {
|
|
|
|
Err(color_eyre::eyre::eyre!("The Cat API returned no images"))
|
|
|
|
}
|
2023-05-13 14:54:41 -04:00
|
|
|
}
|