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.

RustData Fetching

Code

snippet
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::Client and serde::Deserialize — not built-in, must be present in the project.
  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

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

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.