19 More crates and async Rust
This chapter covers
- Another external crate: reqwest
- Feature flags - compiling just part of a crate
- Async Rust - code that doesn't block
In this chapter, we will finally get around to using the reqwest crate. As you read through this chapter you'll soon see why we didn't learn it until now: it's because the reqwest crate is the first one we have encountered that involves async Rust! Well, sort of. Read on to find out.
While we're at it we'll also learn about feature flags, which are used to let you bring in just part of an external crate and thereby help to keep compilation time down.
19.1 The reqwest crate
Back in Chapter 17 that we had a code sample that included a Client[1] from the reqwest crate in one of our structs. We didn't use it at the time because (among other reasons) the Rust Playground doesn't allow you to make http requests. The code looked like this:
use reqwest::Client;
struct Logger {
logs: Vec<Log>,
url: String,
client: Client,
}
Let's simplify this even more by removing the Logger struct and just creating a Client. The code couldn't be easier:
use reqwest::Client;
fn main() {
let client = Client::default();
}
That was easy. So how do we use it? We can use our client to .post() data, .get() it, .delete(), and so on. The easiest method to use is .get(). With this we can just ask a server to give you the html for a website, or a response in a form like JSON from an API. The .get() method is pretty simple: