typestar

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

  1. json::<T>() needs T to implement Deserialize.
  2. The type annotation is what picks the model.
  3. A shape mismatch surfaces as a reqwest error.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 5 in Requests with reqwest, step 8 of 12 in CLI tools & HTTP clients.

← Previous Next →