From a9d5459cb4afaf6947518c66bcf548b33fc74e24 Mon Sep 17 00:00:00 2001 From: Lyle Mantooth Date: Sat, 13 May 2023 15:38:07 -0400 Subject: [PATCH] Deserialize JSON response. --- Cargo.lock | 15 +++++++++++++++ Cargo.toml | 1 + src/main.rs | 19 ++++++++++++++++--- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1544d99..bf5ee17 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -37,6 +37,7 @@ name = "catscii" version = "0.1.0" dependencies = [ "reqwest", + "serde", "tokio", ] @@ -664,6 +665,20 @@ name = "serde" version = "1.0.163" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2113ab51b87a539ae008b5c6c02dc020ffa39afd2d83cffcb3f4eb2722cebec2" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.163" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c805777e3930c8883389c602315a24224bcc738b63905ef87cd1420353ea93e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "serde_json" diff --git a/Cargo.toml b/Cargo.toml index 163c742..40fe825 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2018" [dependencies] reqwest = { version = "0.11", features = ["json"] } +serde = { version = "1", features = ["derive"] } tokio = { version = "1", features = ["full"] } [dev-dependencies] diff --git a/src/main.rs b/src/main.rs index d3c6cab..e89d007 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,22 @@ +use serde::Deserialize; + #[tokio::main] async fn main() { let res = reqwest::get("https://api.thecatapi.com/v1/images/search") .await .unwrap(); - println!("Status: {}", res.status()); - let body = res.text().await.unwrap(); - println!("Body: {}", body); + if !res.status().is_success() { + panic!("Request failed with HTTP {}", res.status()); + } + + #[derive(Deserialize)] + struct CatImage { + url: String, + } + + let images: Vec = res.json().await.unwrap(); + let image = images + .first() + .expect("the cat API should return at least one image"); + println!("The image is at {}", image.url); }