How do I make a GET request using Reqwest?

Reqwest is a popular HTTP client library for Rust. It provides a simple and ergonomic interface to make HTTP requests, including GET requests. Below is an example of how you can make a GET request using Reqwest.

First, you need to add Reqwest as a dependency in your Cargo.toml file:

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

The "json" feature is included here in case you want to send or receive JSON. The tokio crate with the "full" feature is included because Reqwest is an asynchronous library that depends on tokio as the runtime for executing asynchronous code.

Here is an example of how to use Reqwest to make a simple GET request:

// Import the necessary modules.
use reqwest;
use tokio;

// This is the main function where our application starts.
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    // Perform the GET request.
    let response = reqwest::get("https://httpbin.org/get")
        .await?;

    // Check if the request was successful.
    if response.status().is_success() {
        // Parse the response body as text.
        let body = response.text().await?;

        // Print the response body.
        println!("Response Text: {}", body);
    } else {
        // If the request failed, print the status code.
        println!("Request failed with status: {}", response.status());
    }

    Ok(())
}

In this example, we define an asynchronous main function by using the #[tokio::main] attribute. This allows us to run asynchronous code inside the main function. We then use reqwest::get() to send a GET request to https://httpbin.org/get, which is a simple HTTP request and response service. We await the response and check the status code to see if the request was successful. If it was, we print the response body; if not, we print the status code.

Remember that all I/O-bound operations in Rust's async world, including HTTP requests, should be awaited. Reqwest takes care of building and sending the HTTP request, handling the response, and providing you with a simple API to handle the result.

To run this Rust code, make sure you're in the directory with the Cargo.toml file and execute cargo run in your console. This will compile and run your Rust application.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon