expression
Encode a JSON request body
The json feature prepares a serialized body and JSON content type. Use a typed value or a JSON tree and handle possible serialization errors before sending. External crate example; constructs requests or synthetic responses in memory; no request is sent. Expected stdout (not executed): application/json {"qty":2} Common mistake: Setting a JSON content type but composing an invalid body by hand.
Formal Syntax & Structure
rust syntaxrust
builder.json(&serializable).build()Working Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() { let c = reqwest::Client::builder().no_proxy().build().unwrap(); let r = c.post("https://example.com/books").json(&serde_json::json!({"qty":2})).build().unwrap(); println!("{}", r.headers()["content-type"].to_str().unwrap()); println!("{}", std::str::from_utf8(r.body().unwrap().as_bytes().unwrap()).unwrap());}