Making Requests

Make a HTTP GET request

reqwest-badge cat-net-badge

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.

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 example, 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-badge serde-badge url-badge cat-net-badge

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.

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(())
}