make a http get request in rust

To make an HTTP GET request in Rust, you can use the reqwest library. Add reqwest to your Cargo.toml file:

[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }
79 chars
3 lines

Here's an example code to make a GET request to a URL:

main.rs
use reqwest::blocking::get;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let response = get("https://www.example.com")?.text()?;
    println!("{}", response);

    Ok(())
}
187 chars
9 lines

In the above code, we first import the get function from the reqwest::blocking module.

We then call the get function with the URL we want to GET. The get function returns a Result<Response, reqwest::Error>.

To get the response body as text, we call the text method on the response object. The text method returns a Result<String, reqwest::Error>.

We then print the response body to the console.

Note: the ? operator is used to propagate any errors that may occur when calling get or text.

related categories

gistlibby LogSnag