Rust Playbook

Course › Week 4 · Async and plugging into Laravel › Day 2 · lesson 23 of 42 · 30 min reading + 45–60 min practice

HTTP with reqwest

Call APIs with timeouts and status checks, many requests in flight with a limit.

reqwesttimeoutsbuffer_unordered

On this page
  1. Setup
  2. 1. GET into a struct
  3. 2. One Client, with a timeout
  4. 3. An error status is not an error
  5. 4. POST, and Laravel’s 422
  6. 5. What a timeout looks like
  7. 6. Retrying what can succeed on retry
  8. 7. Many requests, a few at a time
  9. Coming from PHP
  10. Practice
  11. Remember

reqwest is Rust’s Guzzle: the HTTP client almost every Rust program uses, built on tokio. Today’s examples call a Laravel-style API at http://127.0.0.1:8000, where php artisan serve listens: it wraps resources in data, returns 404 with a message, 422 with errors, and 429 with Retry-After, as Laravel does. Every output below is a real response.

The rule for the whole day: an HTTP call is three things that can go wrong, and each needs its own answer. The connection can fail, the server can answer with an error status, and the body can be something other than what you expected.

Setup

terminal
cargo add reqwest --features json
cargo add serde --features derive
cargo add tokio --features full

The json feature adds .json() for sending and decoding bodies with serde. reqwest 0.13 uses rustls for HTTPS, so there is no OpenSSL to install.

1. GET into a struct

Two awaits: send() waits for the response headers, .json() waits for the body and decodes it with serde. The resource wrapper becomes a generic struct, Envelope<T> (the traits lesson): one definition for every endpoint that wraps its payload in data.

src/main.rs
use std::error::Error;

use serde::Deserialize;

/// A Laravel API resource wraps its payload in "data".
#[derive(Deserialize)]
struct Envelope<T> {
    data: T,
}

#[derive(Debug, Deserialize)]
struct Booking {
    id: u64,
    guest: String,
    nights: u32,
    status: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let response = reqwest::get("http://127.0.0.1:8000/api/bookings/5521").await?;
    let booking: Envelope<Booking> = response.json().await?;

    println!("{:?}", booking.data);
    println!(
        "#{}: {} stays {} nights ({})",
        booking.data.id, booking.data.guest, booking.data.nights, booking.data.status
    );
    Ok(())
}
$ cargo run
Booking { id: 5521, guest: "Lina", nights: 3, status: "confirmed" }
#5521: Lina stays 3 nights (confirmed)

2. One Client, with a timeout

reqwest::get builds a new client on every call. A program that makes more than one request builds a Client once and reuses it: it keeps connections open between requests (a connection pool) and holds settings like the timeout.

Always set a timeout. reqwest has none by default, so a server that never answers would block your call forever.

src/main.rs
use std::error::Error;
use std::time::Duration;

use reqwest::Client;
use serde::Deserialize;

/// A Laravel API resource wraps its payload in "data".
#[derive(Deserialize)]
struct Envelope<T> {
    data: T,
}

#[derive(Debug, Deserialize)]
struct Booking {
    id: u64,
    guest: String,
    nights: u32,
    status: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = Client::builder()
        .timeout(Duration::from_secs(5))
        .user_agent("nordic-worker/1.0")
        .build()?;

    for id in [5521, 5522] {
        let url = format!("http://127.0.0.1:8000/api/bookings/{id}");
        let booking: Envelope<Booking> = client.get(&url).send().await?.json().await?;
        let b = booking.data;
        println!("#{}: {}, {} nights, {}", b.id, b.guest, b.nights, b.status);
    }
    Ok(())
}
$ cargo run
#5521: Lina, 3 nights, confirmed
#5522: Omar, 7 nights, confirmed

A Client is cheap to clone (the clones share one pool), so you can pass copies into tasks freely. That is the one .clone() in this course that never needs a second thought.

3. An error status is not an error

reqwest only returns Err when there is no response at all. A 404 or 500 is a successful HTTP exchange with a bad status, so send() gives Ok. Decoding that 404 body as a Booking fails with a confusing message:

src/main.rs
use std::error::Error;

use serde::Deserialize;

/// A Laravel API resource wraps its payload in "data".
#[derive(Deserialize)]
struct Envelope<T> {
    data: T,
}

#[derive(Debug, Deserialize)]
struct Booking {
    id: u64,
    guest: String,
    nights: u32,
    status: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let response = reqwest::get("http://127.0.0.1:8000/api/bookings/9999").await?;
    println!("status: {}", response.status());

    let booking: Envelope<Booking> = response.json().await?;
    let b = booking.data;
    println!("#{}: {}, {} nights, {}", b.id, b.guest, b.nights, b.status);
    Ok(())
}
$ cargo run
status: 404 Not Found
Error: reqwest::Error { kind: Decode, url: "http://127.0.0.1:8000/api/bookings/9999", source: Error("missing field `data`", line: 1, column: 68) }
exit code 1

“missing field data” is true, and useless: the real story is that booking 9999 does not exist. Check the status before decoding.

Check the status first

A missing booking is a normal outcome, so the function returns Option: None for a 404. Any other bad status becomes an Err through error_for_status(), which turns a 4xx or 5xx response into a reqwest::Error.

src/main.rs
use std::time::Duration;

use reqwest::{Client, StatusCode};
use serde::Deserialize;

/// A Laravel API resource wraps its payload in "data".
#[derive(Deserialize)]
struct Envelope<T> {
    data: T,
}

#[derive(Debug, Deserialize)]
struct Booking {
    id: u64,
    guest: String,
    nights: u32,
    status: String,
}

async fn find_booking(client: &Client, id: u64) -> Result<Option<Booking>, reqwest::Error> {
    let url = format!("http://127.0.0.1:8000/api/bookings/{id}");
    let response = client.get(&url).send().await?;
    if response.status() == StatusCode::NOT_FOUND {
        return Ok(None);
    }
    let envelope: Envelope<Booking> = response.error_for_status()?.json().await?;
    Ok(Some(envelope.data))
}

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = Client::builder().timeout(Duration::from_secs(5)).build()?;

    for id in [5521, 9999] {
        match find_booking(&client, id).await? {
            Some(b) => println!("#{}: {}, {} nights, {}", b.id, b.guest, b.nights, b.status),
            None => println!("#{id}: no such booking"),
        }
    }
    Ok(())
}
$ cargo run
#5521: Lina, 3 nights, confirmed
#9999: no such booking

StatusCode::NOT_FOUND is a named constant for 404, so the code says what it means. Result<Option<Booking>, …> reads: the call can fail, and if it does not, there may be no booking.

4. POST, and Laravel’s 422

.json(&body) serialises any Serialize value as the request body and sets the Content-Type. When validation fails, Laravel answers 422 with a known shape: a message and an errors map from field to messages. That shape is a struct too:

src/main.rs
use std::collections::BTreeMap;
use std::error::Error;
use std::time::Duration;

use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};

#[derive(Serialize)]
struct NewReminder<'a> {
    channel: &'a str,
}

/// The body of a Laravel 422 response.
#[derive(Deserialize)]
struct ValidationErrors {
    message: String,
    errors: BTreeMap<String, Vec<String>>,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = Client::builder().timeout(Duration::from_secs(5)).build()?;
    let url = "http://127.0.0.1:8000/api/bookings/5521/reminders";

    for channel in ["email", "pigeon"] {
        let response = client
            .post(url)
            .json(&NewReminder { channel })
            .send()
            .await?;
        match response.status() {
            StatusCode::CREATED => println!("{channel}: reminder created"),
            StatusCode::UNPROCESSABLE_ENTITY => {
                let invalid: ValidationErrors = response.json().await?;
                println!("{channel}: rejected: {}", invalid.message);
                for (field, messages) in &invalid.errors {
                    println!("  {field}: {}", messages.join(" "));
                }
            }
            other => println!("{channel}: unexpected status {other}"),
        }
    }
    Ok(())
}
$ cargo run
email: reminder created
pigeon: rejected: The selected channel is invalid.
  channel: The selected channel is invalid.

NewReminder<'a> borrows its channel instead of copying it: a struct that only exists to be serialised can hold &str (the lifetimes lesson). match on the status covers the expected codes by name and everything else in one arm.

5. What a timeout looks like

/api/slow takes 3 seconds. With a 1-second timeout on the client:

src/main.rs
use std::time::Duration;

use reqwest::Client;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = Client::builder().timeout(Duration::from_secs(1)).build()?;

    match client.get("http://127.0.0.1:8000/api/slow").send().await {
        Ok(response) => println!("answered: {}", response.status()),
        Err(error) if error.is_timeout() => eprintln!("gave up after 1 s: {error}"),
        Err(error) if error.is_connect() => eprintln!("cannot connect: {error}"),
        Err(error) => eprintln!("request failed: {error}"),
    }
    Ok(())
}
$ cargo run
gave up after 1 s: error sending request for url (http://127.0.0.1:8000/api/slow)

is_timeout() and is_connect() tell the failures apart, which matters for the next section: a timeout or a refused connection is worth retrying, a malformed URL is not.

6. Retrying what can succeed on retry

/api/unstable answers 503 twice, then 200. /api/limited answers 429 once with Retry-After: 1, then 200. A retry loop that waits longer each time (backoff) and honours Retry-After handles both. A 404 or 422 is never retried: asking again cannot change the answer.

src/main.rs
use std::time::Duration;

use reqwest::{Client, Response, StatusCode};
use tokio::time::sleep;

/// GET with up to three attempts. Retries timeouts, connection failures, 429 and 5xx; nothing else.
async fn get_with_retry(client: &Client, url: &str) -> Result<Response, reqwest::Error> {
    let mut delay = Duration::from_millis(200);
    let mut attempt: u32 = 1;
    loop {
        let result = client.get(url).send().await;
        let retry_after = match &result {
            Ok(r) if r.status() == StatusCode::TOO_MANY_REQUESTS => {
                Some(retry_after(r).unwrap_or(delay))
            }
            Ok(r) if r.status().is_server_error() => Some(delay),
            Ok(_) => None,
            Err(e) if e.is_timeout() || e.is_connect() => Some(delay),
            Err(_) => None,
        };
        match retry_after {
            Some(wait) if attempt < 3 => {
                eprintln!(
                    "attempt {attempt} failed, retrying in {} ms",
                    wait.as_millis()
                );
                sleep(wait).await;
                attempt += 1;
                delay *= 2;
            }
            _ => return result?.error_for_status(),
        }
    }
}

/// The server's Retry-After header, in seconds, if it sent one.
fn retry_after(response: &Response) -> Option<Duration> {
    let value = response.headers().get("retry-after")?.to_str().ok()?;
    let seconds: u64 = value.parse().ok()?;
    Some(Duration::from_secs(seconds))
}

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = Client::builder().timeout(Duration::from_secs(5)).build()?;

    for path in [
        "unstable?key=docs-unstable",
        "limited?key=docs-limited",
        "bookings/9999",
    ] {
        let url = format!("http://127.0.0.1:8000/api/{path}");
        match get_with_retry(&client, &url).await {
            Ok(response) => println!("{path}: {}", response.status()),
            Err(error) => println!("{path}: gave up: {error}"),
        }
    }
    Ok(())
}
$ cargo run
unstable?key=docs-unstable: 200 OK
limited?key=docs-limited: 200 OK
bookings/9999: gave up: HTTP status client error (404 Not Found) for url (http://127.0.0.1:8000/api/bookings/9999)
attempt 1 failed, retrying in 200 ms
attempt 2 failed, retrying in 400 ms
attempt 1 failed, retrying in 1000 ms

The 503s were retried at 200 and 400 ms; the 429 waited the 1 second the server asked for; the 404 failed at once. After the last attempt, error_for_status() turns whatever came back into the final result, so the caller sees the real status in the error.

This is Http::retry(3, 200) with the rules written out. Writing them out is the point: the retry policy is part of how your program treats someone else’s server.

7. Many requests, a few at a time

Spawning one task per request (the async lesson) fires them all at once, which a rate-limited API will punish. buffer_unordered(n) from the futures crate keeps at most n requests in flight: as one finishes, the next starts. Here 5 requests, each made slow with ?delay=300, 2 at a time:

src/main.rs
use std::time::{Duration, Instant};

use futures::stream::{self, StreamExt};
use reqwest::{Client, StatusCode};

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = Client::builder().timeout(Duration::from_secs(5)).build()?;
    let ids: Vec<u64> = vec![5521, 5522, 5523, 5524, 9999];
    let start = Instant::now();

    let mut results: Vec<(u64, Result<StatusCode, reqwest::Error>)> = stream::iter(ids)
        .map(|id| {
            let client = client.clone();
            async move {
                let url = format!("http://127.0.0.1:8000/api/bookings/{id}?delay=300");
                let status = client.get(&url).send().await.map(|r| r.status());
                (id, status)
            }
        })
        .buffer_unordered(2)
        .collect()
        .await;

    results.sort_by_key(|(id, _)| *id);
    for (id, status) in &results {
        match status {
            Ok(status) => println!("#{id}: {status}"),
            Err(error) => println!("#{id}: failed: {error}"),
        }
    }
    println!(
        "5 requests, 2 at a time: about {} ms",
        start.elapsed().as_millis() / 100 * 100
    );
    Ok(())
}
$ cargo run
#5521: 200 OK
#5522: 200 OK
#5523: 200 OK
#5524: 200 OK
#9999: 404 Not Found
5 requests, 2 at a time: about 900 ms

A stream is the async cousin of an iterator: stream::iter turns the list into one, map turns each id into a future (not yet started), buffer_unordered(2) runs two at a time, and collect gathers the results. Three rounds of 300 ms: about 900 ms, where one at a time would be 1,500 and all at once 300.

Results arrive in the order they finish, so the code sorts them. Each request’s own failure stays in its own Result: one bad id does not cancel the others.

Coming from PHP

Laravel’s HTTP client puts these decisions in method calls:

app/Services/BookingApi.php (part)
<?php

use Illuminate\Support\Facades\Http;

$response = Http::timeout(5)
    ->retry(3, 200, throw: false)          // retries any failure, by default
    ->get("http://127.0.0.1:8000/api/bookings/{$id}");

if ($response->notFound()) {
    return null;
}

return $response->throw()->json('data');   // an array: nothing checks its shape

The pieces map one to one: timeout, retry, notFound(), throw() is error_for_status(). Two differences. Laravel’s retry retries every failure unless you pass a when callback, including a 422 that will never succeed; the Rust loop above only retries what can. And ->json('data') gives an untyped array, while Envelope<Booking> rejects a response that does not match.

PracticeThe reqwest docs, and paging through an API

Skim the reqwest docs front page and the Client, RequestBuilder and Response types.

Exercise: every page

GET /api/bookings?page=N returns {"data": […], "current_page": N, "last_page": 3, "total": 5}, like a Laravel paginator. Write async fn all_bookings(client: &Client) -> Result<Vec<Booking>, reqwest::Error> that fetches page 1, then keeps fetching until current_page == last_page, and returns every booking. Print the guests.

Show the solution
src/main.rs
use std::time::Duration;

use reqwest::Client;
use serde::Deserialize;

#[derive(Deserialize)]
struct Booking {
    guest: String,
}

#[derive(Deserialize)]
struct Page {
    data: Vec<Booking>,
    current_page: u32,
    last_page: u32,
}

async fn all_bookings(client: &Client) -> Result<Vec<Booking>, reqwest::Error> {
    let mut bookings: Vec<Booking> = Vec::new();
    let mut page: u32 = 1;
    loop {
        let url = format!("http://127.0.0.1:8000/api/bookings?page={page}");
        let body: Page = client
            .get(&url)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?;
        bookings.extend(body.data);
        if body.current_page >= body.last_page {
            return Ok(bookings);
        }
        page += 1;
    }
}

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = Client::builder().timeout(Duration::from_secs(5)).build()?;
    let bookings = all_bookings(&client).await?;
    let guests: Vec<&str> = bookings.iter().map(|b| b.guest.as_str()).collect();
    println!("{} bookings: {}", bookings.len(), guests.join(", "));
    Ok(())
}
$ cargo run
5 bookings: Lina, Omar, Sara, Youssef, Mona

>= rather than ==: if the server ever reports a current_page past the last one, the loop still ends instead of asking forever.

Remember

  • One Client with a timeout, reused; check the status before decoding the body.
  • Retry only timeouts, connection failures, 429 and 5xx, with backoff; limit concurrency with buffer_unordered.

Tomorrow: sqlx, so the worker can read the same Postgres database your Laravel app writes.