Rust is a systems programming language focused on performance, reliability, and efficiency. As more developers adopt Rust for building applications, there is a need for robust HTTP client libraries like Python's ubiquitous requests package.
The most popular HTTP client library for Rust is reqwest. In many ways,
Getting Started with reqwest
To start using
[dependencies]
reqwest = "0.11"
Then import the crate in your Rust code:
use reqwest;
Making a Basic GET Request
Here is an example of making a simple GET request with
let resp = reqwest::get("https://www.rust-lang.org")
.await?
.text()
.await?;
println!("Response: {}", resp);
This makes a GET request to the Rust language homepage, awaits the response, reads the response body as text, and prints it out.
The
POST Requests and Request Options
Here is an example of a POST request with some request options like headers:
let client = reqwest::Client::new();
let resp = client.post("https://httpbin.org/post")
.header("User-Agent", "My Rust App")
.json(&map!{
"lang" => "Rust",
"package" => "reqwest"
})
.send()
.await?
.text()
.await?;
This demonstrates creating a
Handling Errors
let resp = reqwest::get("https://mysite.com").await;
match resp {
Ok(resp) => println!("Success!"),
Err(err) => println!("Error: {}", err),
}
This matches on the
Timeouts, Redirects, and Other Configuration
The
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.redirect(reqwest::redirect::Policy::none())
.build()?;
So
Conclusion
In summary,
To learn more, check out the official reqwest documentation. The examples provide more detail on advanced usage like multipart file uploads, websockets, and custom response handling. Rust's strong typing also ensures your HTTP logic stays safe and correct.
So give