Reqwest is a popular HTTP client library for Rust that allows you to send HTTP requests easily. To send a POST request with Reqwest, you would typically use its asynchronous API, which is built on top of tokio
and futures. Below is an example of how to send a POST request using Reqwest in Rust.
First, you need to add reqwest
and tokio
to your Cargo.toml
file:
[dependencies]
reqwest = "0.11"
tokio = { version = "1", features = ["full"] }
Then, you can write a function to send a POST request. Here's an example using Reqwest's asynchronous API:
use reqwest;
use tokio;
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
// The URL to which we'll send the POST request
let url = "http://example.com/api/data";
// The data to be sent with the POST request
let params = [("field1", "value1"), ("field2", "value2")];
// Send the POST request and await the response
let client = reqwest::Client::new();
let response = client.post(url)
.form(¶ms)
.send()
.await?;
// Check if the request was successful and print the response
if response.status().is_success() {
let response_text = response.text().await?;
println!("Response: {}", response_text);
} else {
eprintln!("Request failed with status: {}", response.status());
}
Ok(())
}
In the example above, we:
- Import
reqwest
andtokio
modules. - Define the
main
function as asynchronous with#[tokio::main]
. - Specify the URL and parameters for the POST request.
- Create a
reqwest::Client
instance. - Use the
post
method on the client, passing in the URL. - Use the
form
method to add the form parameters to the request. - Use the
send
method to send the request andawait
the response inside anasync
block. - Check the HTTP status code to see if the request was successful.
- If successful, get the response body as text and print it out.
Remember that this is an asynchronous example, and the tokio
runtime is required to execute the async code. If you are working in a synchronous context, Reqwest also provides a synchronous API which you can use without async
and await
. However, the asynchronous approach is recommended for performance reasons, especially when dealing with multiple network requests concurrently.