I’ve been playing around with Rust a lot the past couple weeks. It’s a neat little language with some cool ideas (I particularly like its memory-safety features, though they take some getting used to), but sadly the ecosystem has some catching up to do.
In particular, making HTTP requests in Rust is a bit of a mess right now. The closest Rust has to a working requests library at the moment is rust-http, which is not being maintained while its creator works on its forthcoming replacement, Teepee. Unfortunately, rust-http’s API is not the clearest to use and its documentation is rather sparse.
The fun part, though, is that this means I’ve had to figure out a lot of its quirks myself.
I’ve been working on writing a client for a JSON API and I needed to use rust-http to make lots of JSON requests and then parse their responses as JSON, with as convenient an interface as possible. Here’s what I came up with.
(Disclaimer: I have no idea whether what follows is idiomatic Rust – I’ve been using Rust for less than a month – but it works for me.)
Individual requests are encapsulated in a Request struct (method is a Method and headers is an instance of HeaderCollection):
The json_request method takes a Request struct and tries to make a JSON request with it, returning Ok(Some(response: Json)) if the response is valid JSON, Ok(None) if the response is not valid JSON, or Err(error) if the request failed in some way or did not receive a 200 OK response:
Here’s an example of how this method can be used:
And yeah, that’s about it. It’s still nowhere near as nice as, say, Python’s requests library, but it certainly beats working directly with rust-http’s low-level interface.
Comments
blog comments powered by Disqus