Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Simple blocking http client with reqwest sending a GET request

Create a new crate

cargo new demo
cd demo

Add the reqwest crate as a dependency with the blocking feature:

cargo add reqwest --features blocking

Cargo.toml

Or manually edit the Cargo.toml file to add it as a dependency.

[package]
name = "simple-http-client"
version = "0.1.0"
edition = "2024"

[dependencies]
reqwest = { version = "0.12.23", features = ["blocking"] }

Code

fn main() {
    let url = get_url("get");

    let res = match reqwest::blocking::get(url) {
        Ok(res) => res,
        Err(err) => {
            println!("Error {}", err);
            std::process::exit(1);
        }
    };
    println!("{:?}", res.status());
    println!("{:?}", res);
}

fn get_url(path: &str) -> String {
    let host = std::env::args().nth(1).unwrap_or("httpbin.org".into());
    let url = if host == "localhost" {
        format!("http://localhost/{path}")
    } else {
        format!("https://{host}/{path}")
    };

    url
}

Run the code

cargo run

If everything works fine then you'll get back something like this:

200
Response {
   url: "https://httpbin.org/get",
   status: 200,
   headers: {
     "date": "Wed, 24 Sep 2025 18:09:11 GMT",
     "content-type": "application/json",
     "content-length": "219",
     "connection": "keep-alive",
     "server": "gunicorn/19.9.0",
     "access-control-allow-origin": "*",
     "access-control-allow-credentials": "true"
  }
}

If the service does not work we'll see an error message:

Error error sending request for url (https://httpbin.org/get)

or you might get this output:

503
Response {
    url: "https://httpbin.org/get",
    status: 503,
    headers: {
        "server": "awselb/2.0",
        "date": "Wed, 24 Sep 2025 18:30:49 GMT",
        "content-type": "text/html",
        "content-length": "162",
        "connection": "keep-alive"
    }
}

Run httpbin locally

In that case we can also run the httpbin service locally using Docker.

Start as:

docker run --rm -p 80:80 --name httpbin kennethreitz/httpbin

Then run the code:

cargo run localhost

To stop the Docker container open another terminal and execute

docker container stop -t0 httpbin

  • reqwest
  • blocking
  • get
  • status