Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Simple blocking HTTP POST request using Rust

The reqwest crate provides all the capabilities to send HTTP requests.

  • reqwest
  • HTTP
  • POST
  • form

In this example we are using the reqwest crate to send an HTTP POST request to https://httpbin.org/.

The curl command

This is the same command as executed using curl.

curl -X POST -d "text=Hello World!" http://httpbin.org/post

This is the result:

{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "text": "Hello World!"
  },
  "headers": {
    "Accept": "*/*",
    "Content-Length": "17",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "curl/8.2.1",
    "X-Amzn-Trace-Id": "Root=1-65b22590-3ba351816c46408426023f1b"
  },
  "json": null,
  "origin": "46.120.9.250",
  "url": "http://httpbin.org/post"
}

Dependencies

In order to be able to send a blocking request we need to add that feature, and in order to be able to parse the returned JSON data we had to add the json feature.

[package]
name = "simple-blocking-http-post-reqwest"
version = "0.1.0"
edition = "2021"

[dependencies]
reqwest = { version = "0.11.23", features = ["blocking", "json"] }
serde_json = "1.0.111"

The code

We can pass the parameters in the form method as a bunch of key-value pairs from a HashMap.

use reqwest::blocking::Client;
use std::collections::HashMap;

fn main() {
    let client = Client::new();
    let params = HashMap::from([
        ("text", "Hello World!"),
    ]);

    match client.post("http://httpbin.org/post").form(&params).send() {
        Ok(resp) => {
            let data:  serde_json::Value = resp.json().unwrap();
            println!("{:#?}", data);
        },
        Err(err) => eprintln!("{}", err),
    }
}

The result

This is the resulting data from the request.

#![allow(unused)]
fn main() {
Object {
    "args": Object {},
    "data": String(""),
    "files": Object {},
    "form": Object {
        "text": String("Hello World!"),
    },
    "headers": Object {
        "Accept": String("*/*"),
        "Content-Length": String("19"),
        "Content-Type": String("application/x-www-form-urlencoded"),
        "Host": String("httpbin.org"),
        "X-Amzn-Trace-Id": String("Root=1-65b225c3-1cfb5c6440c0d3014b818197"),
    },
    "json": Null,
    "origin": String("46.120.9.250"),
    "url": String("http://httpbin.org/post"),
}
}