make a http request with a custom body as json in rust

You can use the reqwest library in combination with serde_json to easily make a HTTP request with a custom JSON body.

First, add the following dependencies to your Cargo.toml file:

[dependencies]
reqwest = { version = "0.11.1", features = ["json"] }
serde_json = "1.0"
88 chars
4 lines

Then, you can use the following code snippet to make a POST request with a custom JSON body:

main.rs
use serde::{Serialize, Deserialize};

#[derive(Serialize)]
struct CustomBody {
    field1: String,
    field2: u32,
}

// create a new instance of the custom body struct
let custom_body = CustomBody { 
  field1: String::from("hello"), 
  field2: 42 
};

// send the post request with the custom body
let response = reqwest::Client::new()
    .post("https://example.com/api/endpoint")
    .json(&custom_body)
    .send()
    .await?;
433 chars
21 lines

In this example, we define a struct CustomBody using serde's Serialize trait to allow it to easily be converted to JSON. We then create a new instance of CustomBody and pass it to the json method on the POST request, which will automatically convert it to a JSON body. Finally, we send the request using await (in an async context).

Note that the URL used in the example is only for demonstration purposes and will not actually work.

related categories

gistlibby LogSnag