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"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"reqwest",
|
"reqwest",
|
||||||
|
"serde",
|
||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
@ -664,6 +665,20 @@ name = "serde"
|
||||||
version = "1.0.163"
|
version = "1.0.163"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2113ab51b87a539ae008b5c6c02dc020ffa39afd2d83cffcb3f4eb2722cebec2"
|
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]]
|
[[package]]
|
||||||
name = "serde_json"
|
name = "serde_json"
|
||||||
|
|
|
@ -6,6 +6,7 @@ edition = "2018"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
reqwest = { version = "0.11", features = ["json"] }
|
reqwest = { version = "0.11", features = ["json"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
|
19
src/main.rs
19
src/main.rs
|
@ -1,9 +1,22 @@
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
let res = reqwest::get("https://api.thecatapi.com/v1/images/search")
|
let res = reqwest::get("https://api.thecatapi.com/v1/images/search")
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
println!("Status: {}", res.status());
|
if !res.status().is_success() {
|
||||||
let body = res.text().await.unwrap();
|
panic!("Request failed with HTTP {}", res.status());
|
||||||
println!("Body: {}", body);
|
}
|
||||||
|
|
||||||
|
#[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