Directory Image
This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Privacy Policy.

Rust HTTP Client

Author: Mansoor Ahmed
by Mansoor Ahmed
Posted: Oct 23, 2021

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 { let resp = reqwest::get("https://httpbin.org/ip").await?.json::().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(¶ms).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. 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?;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 { 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 Stringslet 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 #[derive(Debug, Serialize, Deserialize)] struct #[tokio::main] async fn main() -> ; let res = reqwest::Client::new().post("https://httpbin.org/anything").json(&p).send().await?; let js = res.json::().await?; let person: Person = serde_json::from_str(&js.data)?; println!("{:#?}", person); println!("Headers: {:#?}", js.headers); Ok(()) }For more details visit:https://www.technologiesinindustry4.com/2021/10/rust-http-client.html

About the Author

Mansoor Ahmed Chemical Engineer,Web developer

Rate this Article
Leave a Comment
Author Thumbnail
I Agree:
Comment 
Pictures
Author: Mansoor Ahmed

Mansoor Ahmed

Member since: Oct 10, 2020
Published articles: 124

Related Articles