How do you make a GET request in Rust?

17,859

Solution 1

Take a look at Hyper.

Sending a GET request is as simple as this.

let client = Client::new();

let res = client.get("http://example.domain").send().unwrap();
assert_eq!(res.status, hyper::Ok);

You can find more examples in the documentation.

Edit: It seems that Hyper got a bit more complicated since they started to use Tokio. Here is updated version.

extern crate futures;
extern crate hyper;
extern crate tokio_core;

use std::io::{self, Write};
use futures::{Future, Stream};
use hyper::Client;
use tokio_core::reactor::Core;


fn main() {
    let mut core = Core::new().unwrap();
    let client = Client::new(&core.handle());

    let uri = "http://httpbin.org/ip".parse().unwrap();
    let work =
        client.get(uri).and_then(|res| {
            println!("Response: {}", res.status());

            res.body().for_each(|chunk| {
                io::stdout()
                    .write_all(&chunk)
                    .map_err(From::from)
            })
        });
    core.run(work).unwrap();
}

And here are the required dependencies.

[dependencies]
futures = "0.1"
hyper = "0.11"
tokio-core = "0.1"

Solution 2

The current best practice for this particular problem is to use the reqwest crate, as specified in the Rust Cookbook. This code is slightly adapted from the cookbook to run standalone:

extern crate reqwest; // 0.9.18

use std::io::Read;

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let mut res = reqwest::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(())
}

As the cookbook mentions, this code will be executed synchronously.

See also:

Solution 3

Try to go for reqwest:

extern crate reqwest;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut res = reqwest::get("https://httpbin.org/headers")?;

    // copy the response body directly to stdout
    std::io::copy(&mut res, &mut std::io::stdout())?;

    Ok(())
}
Share:
17,859

Related videos on Youtube

Josh Weinstein
Author by

Josh Weinstein

Artist, Coder, and Poet I love SIMD, AVX, SSE, NEON, anything assembly and parallel. I'm on a mission to write the fastest software in the world.

Updated on June 04, 2022

Comments

  • Josh Weinstein
    Josh Weinstein almost 2 years

    I noticed that Rust doesn't have a builtin library to deal with HTTP, it only has a net module that deals with raw IP and TCP protocols.

    I need to take a &str of the URL, make a HTTP GET request, and if successful return either a String or &str that corresponds to the HTML or JSON or other response in string form.

    It would look something like:

    use somelib::http;
    
    let response = http::get(&"http://stackoverflow.com");
    match response {
        Some(suc) => suc,
        None => panic!
    }
    
    • Matthieu M.
      Matthieu M. about 7 years
      This kind of question is off-topic on Stack Overflow, so it likely will be closed. If you haven't found your answer by then, I invite you to check the Rust tag wiki Getting Help section which details other venues for open-ended questions.
  • marmistrz
    marmistrz over 6 years
    This no longer works, since hyper::Client::new takes some handle argument.
  • Erik Berkun-Drevnig
    Erik Berkun-Drevnig about 6 years
    Unfortunately reqwest requires OpenSSL so not good if you are doing cross compiling
  • Shepmaster
    Shepmaster over 4 years
    An answer that suggests reqwest already exists. Please be very clear about what benefit this new answer provides compared to the existing one.
  • Luis San Martin
    Luis San Martin over 4 years
    previous answer doesn't compile this onr does :)
  • Shepmaster
    Shepmaster over 4 years
    That's why we have the capability of making edits to existing answers. It's been edited.
  • Luis San Martin
    Luis San Martin over 4 years
    great! but since Im a new user I cannot comment on previous answer neither edit it..
  • jwh20
    jwh20 over 2 years
    Unfortunately this answer no longer compiles. Please update it or delete it.