Rust HTTP Client with Reqwest
Make HTTP requests in Rust using reqwest with async/await, retry logic, JSON deserialization with serde, timeout handling, and connection pooling for.
Code
use reqwest::Client;
use serde::Deserialize;
#[derive(Deserialize)]
struct User { id: i32, name: String }
async fn fetch_user(id: i32) -> Result<User, Box<dyn std::error::Error>> {
let client = Client::builder().timeout(std::time::Duration::from_secs(5)).build()?;
for attempt in 0..3 {
let res = client.get(format!("https://api.example.com/users/{id}")).send().await;
match res {
Ok(r) => return Ok(r.json().await?),
Err(e) if attempt == 2 => return Err(e.into()),
Err(_) => tokio::time::sleep(std::time::Duration::from_secs(2u64.pow(attempt))).await,
}
}
unreachable!()
}How it works
The working surface is the function fetch_user — everything else is wiring.
Repetition is confined to for attempt in 0..3 — the rest of the file is straight-line. Result is the error channel: the caller receives the failure as a value instead of an exception. match here is the control flow: arms enumerate the value’s shapes exhaustively.
Points of care
- Dependency check:
reqwest::Clientandserde::Deserialize— not built-in, must be present in the project. Resultis the only error channel — remove a?while adapting and that site needs an explicitmatch.
Using it
Signature: fn fetch_user(id: i32) -> Result<User, Box<dyn std::error::Error>>
fetch_user is what another module would consume; nothing else here is load-bearing for callers.
Key statements
let client = Client::builder().timeout(std::time::Duration::from_secs(5)).build()?;
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- Does the snippet panic on failure?
- As data, not exceptions: `Result` makes the caller handle both arms.
- Which packages must be installed first?
- Yes. The imports resolve to `reqwest::Client` and `serde::Deserialize`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.