Rust HTTP Client

Introduction

The reqwest crate delivers a suitable, higher-level HTTP Client. It controls several of the things that record people just imagine an HTTP client to do for them. The reqwest::Client is asynchronous. The reqwest::blocking API can be more useful for applications desiring to only create a few HTTP requests. In this article, we will make an HTTP Client with Reqwest by using Rust.

Description

Rust is informal to make a production. It similarly has memory safety through compiling. It helps us to fix bugs and monitors our code. Rust is a generic type so it is good and more flexible for programming.

We need to install Rust if we haven’t. Find the below link for the rust installation page. https://www.rust-lang.org/tools/install . We may check this out: https://github.com/y6n/html-client-with-reqwest.git . Once we have rust,

  • Open up the app that we use for Rust.
  • Go to Cargo.toml and add the following dependencies.
reqwest = { version = “0.10.4”, features = [“cookies”,”json”]}.

tokio = { version = “0.2”, features = [“full”] }

Now, we can paste the below simple source code into our file.

use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::get("https://httpbin.org/ip")
.await?
.json::<HashMap<String, String>>()
.await?;
println!("{:#?}", resp);
Ok(())
}

Find below more instances for good learning and better understanding.

let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
.body("the exact body that is sent")
.send()
.await?;
let params = [("foo", "bar"), ("baz", "quux")];
let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
.form(&params)
.send()
.await?;

Creating a GET request

We can use the get shortcut method for a single request.

let body = reqwest::get("https://www.rust-lang.org")

    .await?

    .text()

    .await?;

println!("body = {:?}", body);

Setting request bodies

There are multiple ways we can set the body of a request. The simple one is by using the body () method of a RequestBuilder. This allows us to set the precise raw bytes of what the body should be. It receives many types, as well as String and Vec<u8>. We can use the reqwest::Body constructors if we wish to pass a custom type.

let client = reqwest::Client::new();

let res = client.post("http://httpbin.org/post")

    .body("the exact body that is sent")

    .send()

    .await?;

HTTP Client with Reqwest by using Rust

Cookies

The automatic storing and sending of session cookies may be allowed with the cookie_store method on ClientBuilder. A cookie store saves the local database. For instance, we use Facebook. We are essentially keeping our cookies in the cookie store of browsers or applications if we log in or sign up.

We require to permit the cookie store feature by putting this in our dependency. We maybe have by now.

reqwest = { version = “0.10.4”, features = [“cookies”]}.

Following is one way we can allow the cookie store.

let client = reqwest::Client::builder()
.cookie_store(true)
.build()?;
let res = client.get("https://google.com")
.send()
.await?;
let mut body = res.text().await?;

JSON

There is as well a JSON method helper on the RequestBuilder.That the whole thing is, in the same way, the form method. It may take any value that can be divided into JSON. The feature JSON is needed to allow us must put this into our dependency. Once more, we perhaps have by now.

reqwest = { version = “0.10.4”, features = [“json”]}.

The below code needs the JSON feature permitted.

let mut map = HashMap::new();
map.insert("lang", "rust");
let client = reqwest::blocking::Client::new();
let res = client.post("http://httpbin.org")
.json(&map)
.send()?;

Reqwest cares about the feature called .await and async.

use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut map = HashMap::new();
map.insert("lang", "rust");
map.insert("body", "json");
let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
.json(&map)
.send()
.await?;

Ok(())
}

Query Strings

let client = reqwest::Client::builder()
    .build()?;

let res = client
    .get("http://httpbin.org")
    .query(&[("foo", "bar")])
    .send()?;

POST-JSON Data

The json(..) method on the RequestBuilder takes any value that may be serialized into JSON for example a HashMap or
a Struct.

let mut map = HashMap::new();
map.insert("foo", "bar");
map.insert("buzz", "blah");

...
.json(&map)
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Debug, Serialize, Deserialize)]
struct Person {
    first_name: String,
    last_name: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct PersonResponse {
    data: String,
    method: String,
    headers: HashMap<String, String>
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let p = Person { 
        first_name: "Foo".into(),
        last_name: "Bar".into(),
    };

    let res = reqwest::Client::new()
        .post("https://httpbin.org/anything")
        .json(&p)
        .send()
        .await?;

    let js = res
        .json::<PersonResponse>()
        .await?;

    let person: Person = serde_json::from_str(&js.data)?;
    println!("{:#?}", person);

    println!("Headers: {:#?}", js.headers);
    Ok(())
}