crates-io-api
crates-io-api copied to clipboard
Use HTTP Client Trait to allow different backends
Come up with a way of allowing different http client backends (eg attohttpc, etc).
I have the same need in one of my crates. This seems like a common enough need that it would justify some crate to define a common set of traits but I was surprised to find out that there is no such crate. It's probably hard to abstract away all networking into one single trait though...
Absolutely, this is much needed. API clients shouldn't force a specific http library on it's users.
Considering 95+ percent of all apis are "get url, parse json body" or "send json body, parse json body" it should be possible to come up with something that is sufficient for most use cases.
A problem is that traits don't support async
functions, so the futures always need to be boxed, but that's fine for this use case imo.
One could use the async_traits crate to make the code a little bit more readable though. I will probably tinker around with it anyway. If you're interested I can share my progress here.
I mean theoretically a get and post method should be enough for almost all use cases :thinking:
I just stumbled across this: https://docs.rs/http-types/2.4.0/http_types/
Looks like it's a really good crate that does have nice abstractions around the whole http world.
I think we can use the tower_service::Service
trait for this.
reqwest
already implements this trait for its own Request
and Response
type, so we can add new Request
and Response
trait and implements it for reqwest::{Request, Response}
and then take any Service
that implements these traits.