Rust

reqwest POST JSON

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Send a JSON body by calling `.json(&value)` — serde handles serialization. Read the response body or status code afterwards.
Rust
Raw
use serde::{Deserialize, Serialize};

#[derive(Serialize)]
struct NewUser<'a> { name: &'a str, email: &'a str }

#[derive(Deserialize, Debug)]
struct CreatedUser { id: u64, name: String, email: String }

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();

    let resp = client.post("https://api.example.com/users")
        .bearer_auth(std::env::var("API_TOKEN")?)
        .json(&NewUser { name: "Alice", email: "a@x.com" })
        .send().await?;

    println!("status: {}", resp.status());
    let created: CreatedUser = resp.error_for_status()?.json().await?;
    println!("{created:#?}");
    Ok(())
}
Tags

Save your own code snippets

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