1 //! This example illustrates the way to send and receive statically typed JSON.
2 //!
3 //! In contrast to the arbitrary JSON example, this brings up the full power of
4 //! Rust compile-time type system guaranties though it requires a little bit
5 //! more code.
6
7 // These require the `serde` dependency.
8 use serde::{Deserialize, Serialize};
9
10 #[derive(Debug, Serialize, Deserialize)]
11 struct Post {
12 id: Option<i32>,
13 title: String,
14 body: String,
15 #[serde(rename = "userId")]
16 user_id: i32,
17 }
18
19 // This is using the `tokio` runtime. You'll need the following dependency:
20 //
21 // `tokio = { version = "1", features = ["full"] }`
22 #[tokio::main]
main() -> Result<(), reqwest::Error>23 async fn main() -> Result<(), reqwest::Error> {
24 let new_post = Post {
25 id: None,
26 title: "Reqwest.rs".into(),
27 body: "https://docs.rs/reqwest".into(),
28 user_id: 1,
29 };
30 let new_post: Post = reqwest::Client::new()
31 .post("https://jsonplaceholder.typicode.com/posts")
32 .json(&new_post)
33 .send()
34 .await?
35 .json()
36 .await?;
37
38 println!("{:#?}", new_post);
39 // Post {
40 // id: Some(
41 // 101
42 // ),
43 // title: "Reqwest.rs",
44 // body: "https://docs.rs/reqwest",
45 // user_id: 1
46 // }
47 Ok(())
48 }
49