2

I'd like to to pass a https string with an api key to Rust and print out the results of the GET request.

#[macro_use]
extern crate serde_json;
extern crate reqwest;

use reqwest::Error;
use std::future::Future;

#[derive(Debug)]
fn main() -> Result<(), Error> {
 
  //Testing out pretty print JSON
  let obj = json!({"data":{"updated_at":"2021-09-17T17:41:05.677631986Z","items":[{"signed_at":"2015-07-30T03:26:13Z","height":0}],"pagination":null},"error":false,"error_message":null,"error_code":null});
  
  //Pretty print the above JSON
  //This works
  println!("{}", serde_json::to_string_pretty(&obj).unwrap());

  //Issue API GET request
  //Colon at the end of my_private_key is to bypass the password
  let request_url = format!("https://api.xyz.com/v1/1/ -u my_private_key:");

  let response = reqwest::get(&request_url);

  println!("{:?}", response);

  Ok(())

}

I receive the following output from the compiler.

--> src/main.rs:19:22
 |
19 |     println!("{:?}", response);
 |                      ^^^^^^^^ `impl Future` cannot be formatted using `{:?}` because it doesn't implement `Debug`
 |
 = help: the trait `Debug` is not implemented for `impl Future`
 = note: required by `std::fmt::Debug::fmt`
 = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
Herohtar
  • 5,347
  • 4
  • 31
  • 41
marrowgari
  • 417
  • 3
  • 15
  • await the future – Brady Dean Sep 17 '21 at 18:37
  • 4
    Or, if you are only doing a few requests, better use `reqwest::blocking::get` to avoid dealing with `async` at all. – Ivan C Sep 17 '21 at 18:40
  • 1
    You want to use the [`blocking`](https://docs.rs/reqwest/0.11.4/reqwest/blocking/index.html) API (ie. replace `reqwest::get` with `reqwest::blocking::get`). – Jmb Sep 17 '21 at 18:49
  • This works. Thank you. How would you pass in additional query string parameters to the reqwest, e.g., an API key? – marrowgari Sep 17 '21 at 20:17
  • @marrowgari you'd have to use RequestBuilder api https://docs.rs/reqwest/0.11.4/reqwest/struct.RequestBuilder.html#method.query – Ivan C Sep 17 '21 at 20:22

1 Answers1

4

reqwest::get() is an async function and it returns a future. A future represents a task that will be completed in the future. If you're inside an async function, you can use await to continue once the future is done and get the result. Such as:

let response = reqwest::get("https://example.com").await;

main can't be async by default, but you can use the tokio crate and annotate main with #[tokio::main].

CoderCharmander
  • 1,862
  • 10
  • 18