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

Making Requests

Make a HTTP GET request

reqwest Net

Parses the supplied URL and makes a synchronous HTTP GET request with reqwest::blocking::get. Prints obtained reqwest::blocking::Response status and headers. Reads HTTP response body into an allocated String using read_to_string.

This recipe requires the blocking feature flag of reqwest and the macros and rt-multi-thread feature flags of tokio to be enabled in Cargo.toml.

use anyhow::Result;
use std::io::Read;

fn main() -> Result<()> {
    let mut res = reqwest::blocking::get("http://httpbin.org/get")?;
    let mut body = String::new();
    res.read_to_string(&mut body)?;

    println!("Status: {}", res.status());
    println!("Headers:\n{:#?}", res.headers());
    println!("Body:\n{}", body);

    Ok(())
}

Async

A similar approach can be used by including the tokio executor to make the main function asynchronous, retrieving the same information.

In this recipe, tokio::main handles all the heavy executor setup and allows sequential code implemented without blocking until .await.

Uses the asynchronous versions of reqwest, both reqwest::get and reqwest::Response.

use anyhow::Result;

#[tokio::main]
async fn main() -> Result<()> {
    let res = reqwest::get("http://httpbin.org/get").await?;
    println!("Status: {}", res.status());
    println!("Headers:\n{:#?}", res.headers());

    let body = res.text().await?;
    println!("Body:\n{}", body);
    Ok(())
}

Set custom headers and URL parameters for a REST request

reqwest serde url Net

Sets both standard and custom HTTP headers as well as URL parameters for a HTTP GET request.

Builds a complex URL with Url::parse_with_params. Sets standard headers header::USER_AGENT and header::AUTHORIZATION, plus a custom X-Powered-By header using RequestBuilder::header, then makes the request with RequestBuilder::send.

The request target http://httpbin.org/headers responds with a JSON dict containing all request headers for easy verification.

This recipe requires the blocking and json feature flags of reqwest and the derive feature flag of serde to be enabled in Cargo.toml.

use anyhow::Result;
use reqwest::Url;
use reqwest::blocking::Client;
use reqwest::header::{AUTHORIZATION, USER_AGENT};
use serde::Deserialize;
use std::collections::HashMap;

#[derive(Deserialize, Debug)]
pub struct HeadersEcho {
    pub headers: HashMap<String, String>,
}

fn main() -> Result<()> {
    let url = Url::parse_with_params(
        "http://httpbin.org/headers",
        &[("lang", "rust"), ("browser", "servo")],
    )?;

    let response = Client::new()
        .get(url)
        .header(USER_AGENT, "Rust-test-agent")
        .header(AUTHORIZATION, "Bearer my-token")
        .header("X-Powered-By", "Rust")
        .send()?;

    assert_eq!(
        response.url().as_str(),
        "http://httpbin.org/headers?lang=rust&browser=servo"
    );

    let out: HeadersEcho = response.json()?;
    assert_eq!(out.headers["User-Agent"], "Rust-test-agent");
    assert_eq!(out.headers["Authorization"], "Bearer my-token");
    assert_eq!(out.headers["X-Powered-By"], "Rust");

    Ok(())
}