Typed JSON responses in Rust
Ask for JSON and reqwest deserializes straight into your type.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Health {
status: String,
#[serde(default)]
version: String,
}
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let health: Health = reqwest::get("https://typestar.io/api/health")
.await?
.json()
.await?;
println!("{} {}", health.status, health.version);
Ok(())
}
How it works
json::<T>()needsTto implementDeserialize.- The type annotation is what picks the model.
- A shape mismatch surfaces as a reqwest error.
Keywords and builtins used here
HealthOkResultStringasyncawaitfnletmainstructuse
The run, in numbers
- Lines
- 19
- Characters to type
- 340
- Tokens
- 87
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 47 seconds.
Step 2 of 5 in Requests with reqwest, step 8 of 12 in CLI tools & HTTP clients.