make a http request with a custom body as json and return a json response in rust

To make an HTTP request with a custom body as JSON and return a JSON response in Rust, we can use the reqwest crate along with serde and serde-json.

First, add the reqwest, serde, and serde_json dependencies to your Cargo.toml file:

[dependencies]
reqwest = { version = "0.11", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
137 chars
5 lines

Then, in your Rust code, you can use the following example code as a starting point:

main.rs
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::error::Error;

#[derive(Serialize)]
struct CustomBody {
    message: String,
}

#[derive(Deserialize)]
struct ResponseBody {
    result: Value,
}

async fn make_request() -> Result<String, Box<dyn Error>> {
    // Create the custom request body
    let custom_body = CustomBody {
        message: String::from("Hello, world!"),
    };
    let body_json = serde_json::to_string(&custom_body)?;

    // Send the HTTP POST request with the custom body
    let client = reqwest::Client::new();
    let response = client
        .post("https://example.com/api")
        .header("Content-Type", "application/json")
        .body(body_json)
        .send()
        .await?;

    // Parse the JSON response
    let response_body: ResponseBody = response.json().await?;
    let result = serde_json::to_string(&response_body.result)?;

    Ok(result)
}

fn main() {
    match tokio::runtime::Runtime::new().unwrap().block_on(make_request()) {
        Ok(result) => println!("Result: {}", result),
        Err(e) => println!("Error: {}", e),
    }
}
1116 chars
44 lines

This code defines two structs, CustomBody and ResponseBody, that correspond to the request and response JSON payloads, respectively. The make_request function creates an instance of CustomBody, converts it to a JSON string, and sends an HTTP POST request with the custom body. The response body is then deserialized into an instance of ResponseBody, and the result field is converted back to a JSON string and returned.

In the main function, we use the tokio runtime to execute the make_request function asynchronously and print the result or any encountered errors.

gistlibby LogSnag