Deserialize JSON response.
This commit is contained in:
parent
eb887d009d
commit
a9d5459cb4
3 changed files with 32 additions and 3 deletions
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…
Add table
Add a link
Reference in a new issue