I'm trying to call a downstream API and return the results as a Json object. I'm using reqwest
which uses tokio
:
Cargo.toml
[dependencies]
rocket = { version = "0.5.0-rc.1", features = ["secrets", "tls", "json"] }
reqwest = { version = "0.11", features = ["blocking", "json"] }
tokio = { version = "1", features = ["full"] }
main.rs
#[post("/teams")]
fn teams() -> Json<Vec<Team>> {
let mut r = reqwest::blocking::get("https://example.com");
if r.is_ok() {
return Json(get_teams(r.unwrap().text().unwrap()));
} else {
return Json(Vec::new());
}
}
The error I get is:
thread 'rocket-worker-thread' panicked at 'Cannot drop a runtime in a context where blocking is not allowed. This happens when a runtime is dropped from within an asynchronous context.'
Is this because I'm using a blocking call? How can I make a blocking call and simply return the results. Any guidance would be appreciated.
Here's what did it for me:
#[post("/teams")]
async fn teams() -> Json<Vec<Team>> {
return Json(get_teams(reqwest::get("https://example.com").await.unwrap().text().await.unwrap()));
}
Cargo.toml
reqwest = { version = "0.11", features = ["blocking", "json"] }
tokio = { version = "1", features = ["full"] }