Deserialize JSON response.
This commit is contained in:
parent
eb887d009d
commit
a9d5459cb4
15
Cargo.lock
generated
15
Cargo.lock
generated
|
@ -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"
|
||||
|
|
|
@ -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]
|
||||
|
|
19
src/main.rs
19
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<CatImage> = 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);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue