make a http post request in rust

To make an HTTP POST request in Rust, we will use the reqwest crate. Here's a basic example of how to make an HTTP POST request:

main.rs
use reqwest::blocking::Client;
use reqwest::Error;

fn make_post_request() -> Result<(), Error> {
    let client = Client::new();
    let res = client.post("https://www.example.com/api/create/user")
        .json(&json!({
            "username": "johndoe",
            "email": "johndoe@example.com",
            "password": "password123"
        }))
        .send()?;

    println!("Response status: {}", res.status());

    Ok(())
}
435 chars
18 lines

Here we are creating a new Client object and then using its post method to create a new RequestBuilder object. We set the URL to which we want to send the request using the post method. We then chain the json method which sets the request body to a JSON object. Finally, we send the request using the send method and handle any errors that may occur.

In this example, we are making a POST request to https://www.example.com/api/create/user with a JSON payload containing the user's username, email, and password. The response status is then printed to the console.

Note that this example uses the blocking API of reqwest, which means that the program will block until the request completes. If you need to make asynchronous requests, you can use the tokio runtime with the asynchronous API of reqwest.

related categories

gistlibby LogSnag