HTTP Post and Get Request no Response

So I run main but neither the post nor get functions return me anything despite println!, what did I do wrong?

extern crate reqwest;

fn main()
{
    post();
    get();
}

async fn post()
{
    let client = reqwest::Client::new();
    let res = client.post("http://localhost:8088")
    .body("the exact body that is sent")
    .send()
    .await;
    
    println!("{:?}", res)
}

async fn get()
{
    let body = reqwest::get("http://localhost:8088")
    .await;

    println!("body = {:?}", body);
}

Since post and get are asynchronous functions, you have to await them. What you currently do in main is just creating Futures, but not executing them. You need an executor like tokio or async-std to run your futures, e.g.:

#[tokio::main]
async fn main() {
    post().await;
    get().await;
}

and include tokio in your Cargo.toml:

[dependencies]
tokio = { version = "0.2", features = ["full"] }

(you might want to include less than full features for tokio to save compilation time and binary size, but I'm not totally sure what the minimum feature set for your case would be).

Edit: the Rust compiler also warns you about the fact that your Futures are unused:

warning: unused implementer of `std::future::Future` that must be used
 --> src/main.rs:5:5
  |
5 |     post();
  |     ^^^^^^^
  |
  = note: `#[warn(unused_must_use)]` on by default
  = note: futures do nothing unless you `.await` or poll them
1 Like

I see thank you very much.

1 Like

Just a quick question when I run post and ask it to print out res, it doesn't seem to print out the body and only prints out the headers. How can I include the body?

You call a method such as text or bytes on the response.

1 Like

Hi alice, when I try to add on .text() onto res in post it says that the method is not found, do I need to add something to my dependencies? Could you maybe include a code snippet example? Thank you.

Let me guess, the function isn't found on Result<Response, SomeError>?
you need to handle the error by e.g. an unwrap

Yes that was it, but now it's not letting me print res - saying impl std:future:Future doesn't implement std:fmt:Debug.

Ahh I just needed to use await again - thxs for your help Alice.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.