diff --git a/examples/json_dynamic.rs b/examples/json_dynamic.rs new file mode 100644 index 0000000..48676b9 --- /dev/null +++ b/examples/json_dynamic.rs @@ -0,0 +1,40 @@ +//! This example illustrates the way to send and receive arbitrary JSON. +//! +//! This is useful for some ad-hoc experiments and situations when you don't +//! really care about the structure of the JSON and just need to display it or +//! process it at runtime. +extern crate reqwest; +#[macro_use] extern crate serde_json; + +fn main() -> Result<(), reqwest::Error> { + let echo_json: serde_json::Value = reqwest::Client::new() + .post("https://jsonplaceholder.typicode.com/posts") + .json( + &json!({ + "title": "Reqwest.rs", + "body": "https://docs.rs/reqwest", + "userId": 1 + }) + ) + .send()? + .json()?; + + println!("{:#?}", echo_json); + // Object( + // { + // "body": String( + // "https://docs.rs/reqwest" + // ), + // "id": Number( + // 101 + // ), + // "title": String( + // "Reqwest.rs" + // ), + // "userId": Number( + // 1 + // ) + // } + // ) + Ok(()) +} diff --git a/examples/json_typed.rs b/examples/json_typed.rs new file mode 100644 index 0000000..cefb1cf --- /dev/null +++ b/examples/json_typed.rs @@ -0,0 +1,42 @@ +//! This example illustrates the way to send and receive statically typed JSON. +//! +//! In contrast to the arbitrary JSON example, this brings up the full power of +//! Rust compile-time type system guaranties though it requires a little bit +//! more code. +extern crate reqwest; +#[macro_use] extern crate serde_derive; +extern crate serde_json; + +#[derive(Debug, Serialize, Deserialize)] +struct Post { + id: Option, + title: String, + body: String, + #[serde(rename = "userId")] + user_id: i32, +} + +fn main() -> Result<(), reqwest::Error> { + let new_post = Post { + id: None, + title: "Reqwest.rs".into(), + body: "https://docs.rs/reqwest".into(), + user_id: 1 + }; + let new_post: Post = reqwest::Client::new() + .post("https://jsonplaceholder.typicode.com/posts") + .json(&new_post) + .send()? + .json()?; + + println!("{:#?}", new_post); + // Post { + // id: Some( + // 101 + // ), + // title: "Reqwest.rs", + // body: "https://docs.rs/reqwest", + // user_id: 1 + // } + Ok(()) +}