Rust

reqwest GET + JSON Deserialize

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`reqwest` is the standard HTTP client. Combined with serde, you can fetch and parse a JSON API response into a typed struct in three lines.
Rust
Raw
// Cargo.toml:
// reqwest = { version = "0.12", features = ["json"] }
// serde   = { version = "1", features = ["derive"] }
// tokio   = { version = "1", features = ["full"] }

use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct User {
    login: String,
    name:  Option<String>,
    public_repos: u32,
}

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let user: User = reqwest::Client::new()
        .get("https://api.github.com/users/torvalds")
        .header("User-Agent", "myapp/1.0")     // required by GitHub API
        .send().await?
        .error_for_status()?                   // 4xx/5xx → Err
        .json().await?;

    println!("{user:#?}");
    Ok(())
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.