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.

Rust Data 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!()
}