Connect to the Server using crate “reqwest” | RUST Programming

Reading Time: 3 minutes

Hi everyone I hope you all are good and learning every day. So what we are going to discuss today?? Embedded? Microcontroller? No! None of them. Today we are going to talk about the HTTP request in RUST Programming.

In the previous blog, we talked about a Valuable Package LSM303DLHC using which we were able to access two of the sensor of the f3 board. Today we are going to learn something different but relatable.

HTTP REQUEST USE IN SOCIETY


What is an HTTP request?

An HTTP request is made by a client, to a named host, which is located on a server. The request aims to access a resource on the server. Now to access this server-client uses a URL(Uniform Resource Locator)

A correctly composed HTTP request contains the following elements:

  1. A request line.
  2. A series of HTTP headers, or header fields.
  3. A message body, if needed.

Crate reqwest in RUST!

The `reqwest crate provides a convenient, higher-level HTTP client. It handles many of the things that most people just expect an HTTP client to do for them.

The applications which make only a few requests can use reqwest::blocking whereas the reqwest::Client is asynchronous. This helps in making an HTTP request in Rust.

Dependencies to include in Cargo.toml & The Body!

For the Client, as an asynchronous request, we use Tokio.

[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }

The body which uses tokio and work in an asynchronous form.

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(())
}

For Blocking Client we use :

[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }

The body we provide here:

use std::collections::HashMap;

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

Make some Request

Making a GET request

For a single request we can use “get” which is a shortcut method.

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

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

Making POST requests

The body:

let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
    .body("the exact body that is sent")
    .send()
    .await?;

Not only this we can post our data on the server in many different formats. Let’s see a few of them here.

Data which is Serialize into a form data.

// This will POST a body of `hi=ROHAN&bye=AKASH`
let params = [("hi", "ROHAN"), ("bye", "AKASH")];
let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
    .form(&params)
    .send()
    .await?;

The JSON Form

// This will POST a body of `{"database":"user","body":"json"}`
let mut map = HashMap::new();
map.insert("database", "user");
map.insert("body", "json");

let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
    .json(&map)
    .send()
    .await?;

Test your “get” and “post” Request

Here are some online servers available on which you can test your get, post, and many more requests.

Return get Data:

https://httpbin.org/get

Return your post Data:

https://httpbin.org/post

Return your HTTP status code:

https://httpbin.org/status/:code

Here is the link to my repository in which I have done the post and get requests using Client as asynchronous. You can use it to get an idea if you face any problem.

This is all in today’s blog. I hope you liked the reading. Thanks!!!


If you want to read more content like this?  Subscribe to Rust Times Newsletter and receive insights and latest updates, bi-weekly, straight into your inbox. Subscribe to Rust Times Newsletter: https://bit.ly/2Vdlld7.

rust times

Written by 

Nitin is a Software Consultant, with experience of more than 7 months. He works on Rust Programming Language and Embedded Development using Rust. He is also fond of Java Programming & Artificial Intelligence. Apart from that, his hobbies are Watching Netflix, Reading, Singing & Writing.