To perform an HTTP POST request in Rust, one of the most popular libraries you can use is reqwest. This library provides an easy and powerful way to make HTTP requests. Below is a simple example of how to perform a POST request using reqwest. This example assumes you want to post JSON data to a server.
First, you need to add reqwest and tokio to your Cargo.toml since reqwest is an asynchronous library and relies on tokio as the runtime. You might also want to add serde for JSON serialization and deserialization.
[dependencies]
reqwest = "0.11"
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Here is a simple example of making a POST request with JSON body:
use serde_json::json;
use reqwest::Error;
#[tokio::main]
async fn main() -> Result<(), Error> {
// Your JSON data
let data = json!({
"key": "value"
});
// The URL to which the request is made
let url = "http://httpbin.org/post";
// Creating a client instance
let client = reqwest::Client::new();
// Making the POST request
let res = client.post(url)
.json(&data)
.send()
.await?;
// Print the response status and text
println!("Status: {}", res.status());
println!("Headers:\n{:#?}", res.headers());
let body = res.text().await?;
println!("Body:\n{}", body);
Ok(())
}
In this example:
- We define a JSON object with
json! macro from the serde_json crate.
- We use
reqwest::Client to make a POST request to http://httpbin.org/post, which is a simple HTTP request & response service.
- We set the JSON body with
.json(&data) where data is the JSON payload.
- We asynchronously send the request with
.send().await? and print the response status, headers, and body.
Remember to run this code within an asynchronous context, as we did by using #[tokio::main] macro. This example will not work in a synchronous context without modifications.