How do I pass parameters in a Reqwest GET request?

In Rust, reqwest is a popular HTTP client library that allows you to make network requests. When you want to perform a GET request with query parameters using reqwest, you need to construct the URL with the query string or use the provided API to add parameters to the request.

Here's an example of how to pass parameters in a reqwest GET request:

use reqwest;
use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    // Create a client instance
    let client = reqwest::Client::new();

    // Create a URL without query parameters
    let url = "https://httpbin.org/get";

    // Create a map for the query parameters
    let mut params = HashMap::new();
    params.insert("param1", "value1");
    params.insert("param2", "value2");

    // Use the `query` method to add parameters to the request
    let res = client.get(url)
        .query(&params)
        .send()
        .await?;

    // Get the response text
    let body = res.text().await?;

    // Print the response text
    println!("Response: {}", body);

    Ok(())
}

In this example:

  • We import the necessary modules and declare the main function as asynchronous because reqwest is an async library.
  • We create an instance of a reqwest client.
  • We define the base URL we will be sending our GET request to.
  • We create a HashMap to hold our query parameters.
  • We use the .query() method of the reqwest::Client to add the parameters to our GET request.
  • We send the request and await the response.
  • Finally, we print out the response body.

Make sure to add reqwest and tokio to your Cargo.toml file dependencies to use the above code:

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

Remember that the tokio::main attribute macro is used to mark the async main function and set up the asynchronous runtime environment provided by Tokio.

Also, keep in mind that network-related operations can fail, and proper error handling should be considered for production code. The Result<(), reqwest::Error> return type in the example above is a simple way to handle errors by propagating them to the caller. In a real-world application, you may want to have more sophisticated error handling.

Related Questions

Get Started Now

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