How to Call HTTP APIs in Rust with reqwest
Table of Contents
Updated November 2026: Updated for reqwest 0.13 and tokio 1.54 on Rust 2024: client reuse, POST with JSON, auth, timeouts and error_for_status; all samples run against httpbin.org.
Whenever one of my Rust CLIs has to talk to an HTTP API, I reach for reqwest . It’s built on top of hyper and tokio, has a pleasant builder API and handles JSON, TLS, compression and proxies for me. This post shows the parts I use all the time: one reusable client, JSON in and out, headers and auth, timeouts and proper error handling.
All samples use httpbin.org , a public echo API, so you can run them as they are.
Add reqwest, tokio and serde
reqwest is async, so you need an async runtime. Add reqwest with the json and query features, tokio and serde to your Cargo.toml:
[dependencies]
reqwest = { version = "0.13", features = ["json", "query"] }
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
Or let cargo do it:
cargo add reqwest --features json,query
cargo add serde --features derive
cargo add tokio --features full
Since reqwest 0.13, query (and form) are opt-in features, and the default TLS backend is rustls, so you no longer need OpenSSL on your build machine.
A quick GET request
For a one-off request, the reqwest::get shortcut is all you need:
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let body = reqwest::get("https://httpbin.org/get")
.await?
.text()
.await?;
println!("{body}");
Ok(())
}
Every call to reqwest::get creates a new Client under the hood. That’s fine once, but wasteful as soon as you send more requests.
Create one Client and reuse it
A Client holds a connection pool. When you reuse it, subsequent requests to the same host skip the TCP and TLS handshakes and go over an already open connection. Client uses an Arc internally, so cloning it is cheap and every clone shares the same pool. Create it once at startup and pass it (or clones of it) around.
I configure everything that applies to all requests on the ClientBuilder:
use std::time::Duration;
use reqwest::header::{ACCEPT, HeaderMap, HeaderValue};
fn build_client() -> reqwest::Result<reqwest::Client> {
let mut headers = HeaderMap::new();
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
reqwest::Client::builder()
.user_agent(concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")))
.default_headers(headers)
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(10))
.build()
}
Some APIs (GitHub, for example) reject requests without a User-Agent, and reqwest doesn’t send one by default. That’s why I always set it.
Deserialize a JSON response with serde
Model the parts of the response you care about as a struct deriving Deserialize, and let json() do the rest. Fields you don’t declare are ignored:
use std::collections::HashMap;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct HttpBinGet {
url: String,
headers: HashMap<String, String>,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = build_client()?;
let res: HttpBinGet = client
.get("https://httpbin.org/get")
.query(&[("page", "2"), ("per_page", "10")])
.send()
.await?
.error_for_status()?
.json()
.await?;
println!("{} sent by {:?}", res.url, res.headers.get("User-Agent"));
Ok(())
}
query URL-encodes the pairs and appends them, so the program prints https://httpbin.org/get?page=2&per_page=10. Instead of annotating the variable, you can also use the turbofish: .json::<HttpBinGet>(). If the API uses camelCase field names, add #[serde(rename_all = "camelCase")] to the struct instead of giving up on Rust naming.
Send JSON with a POST request
Sending JSON works the other way around. Derive Serialize and pass a reference to json(). reqwest serializes the value and sets Content-Type: application/json:
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Todo {
title: String,
done: bool,
}
// httpbin echoes the request body in the `json` field
#[derive(Debug, Deserialize)]
struct Echo {
json: Todo,
}
async fn create_todo(client: &reqwest::Client, todo: &Todo) -> reqwest::Result<Todo> {
let echo: Echo = client
.post("https://httpbin.org/post")
.json(todo)
.send()
.await?
.error_for_status()?
.json()
.await?;
Ok(echo.json)
}
put, patch and delete work the same way. For anything else, use client.request(Method::OPTIONS, url).
Add headers and authentication
Headers that only apply to a single request go on the RequestBuilder. For the two common auth schemes, reqwest has dedicated helpers:
let token = std::env::var("API_TOKEN")?;
let res = client
.get("https://httpbin.org/bearer")
.bearer_auth(&token)
.header("X-Request-Id", "42")
.send()
.await?;
let res = client
.get("https://httpbin.org/basic-auth/thorsten/s3cret")
.basic_auth("thorsten", Some("s3cret"))
.send()
.await?;
Both helpers mark the Authorization header as sensitive, so its value doesn’t show up when you debug-print the request. Read tokens from the environment or a secret store, never hard-code them.
Set timeouts
By default, reqwest doesn’t time out at all. A slow API can hang your program forever, so set timeouts on the client, as shown above:
connect_timeoutlimits how long establishing the connection may take.timeoutlimits the whole request, from connecting until the response body is read.
You can override the total timeout per request, for a slow endpoint for example:
let res = client
.get("https://httpbin.org/delay/5")
.timeout(Duration::from_secs(2))
.send()
.await;
if let Err(e) = &res
&& e.is_timeout()
{
eprintln!("request timed out: {e}");
}
Handle errors with error_for_status
Here’s the part that surprises most people: reqwest does not treat 404 or 500 as an error. send() only fails if the request couldn’t be sent or no response came back. A response with any status code is a success from reqwest’s point of view.
That’s why I call error_for_status() on every response before reading the body. It turns 4xx and 5xx responses into a reqwest::Error, which carries the status code:
match client
.get("https://httpbin.org/status/404")
.send()
.await?
.error_for_status()
{
Ok(res) => println!("got {}", res.status()),
Err(e) if e.status() == Some(reqwest::StatusCode::NOT_FOUND) => {
eprintln!("not found: {e}");
}
Err(e) => return Err(e.into()),
}
This prints not found: HTTP status client error (404 Not Found) for url (https://httpbin.org/status/404). Without error_for_status(), the next call to json() would fail with a confusing decode error, because the error page is not the JSON you expected.
If you need the error body (many APIs explain what went wrong in it), check res.status() yourself and read res.text() before giving up. reqwest::Error also has is_connect(), is_timeout(), is_decode() and friends, so you can decide what is worth a retry.
Compression and proxies
Enable the gzip, brotli, deflate or zstd feature and reqwest sends the matching Accept-Encoding header and decompresses response bodies transparently. No further code needed.
reqwest picks up the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables (and the system proxy settings on macOS and Windows) by default. To set a proxy explicitly, or to ignore all of them:
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::https("http://my-proxy.local:8080")?)
.build()?;
let client = reqwest::Client::builder()
.no_proxy()
.build()?;
A note on the blocking client
For small scripts that don’t need async, enable the blocking feature and use reqwest::blocking. The API mirrors the async one, minus the .await:
fn main() -> Result<(), reqwest::Error> {
let body = reqwest::blocking::get("https://httpbin.org/get")?.text()?;
println!("{body}");
Ok(())
}
It starts its own tokio runtime internally, so don’t use it inside an async function: it panics there.
Conclusion
Five years after I first wrote this post, reqwest is still my default HTTP client in Rust. Create one Client, set a user agent and timeouts on it, and call error_for_status() before reading a body. That covers most of what can go wrong when talking to HTTP APIs.