1 unstable release
Uses new Rust 2024
new 0.1.0 | Apr 2, 2025 |
---|
#14 in #base
83 downloads per month
16KB
198 lines
API Wrapper
cargo add base-sensible-wrapper
A simple api interface and client for integrating reqwest with helper methods.
Allows for creating simple and reusable automatic api interfaces.
How to use
Create a very simple struct that is capable of containing any auth info required. Create an impl that includes creating
the http client you wish to use. This package uses reqwuest-with-middleware
, but this is optional and does not require
any middleware being added. Additionally, conform this struct to ApiInterface
pub struct AuthenticationInfo {
username: String,
password: String,
}
pub struct MyApiInterface {
auth_info: AuthenticationInfo
}
impl MyApiInterface {
pub fn new(username: String, password: String) -> Self {
let auth_info = AuthenticationInfo { username, password };
Self { auth_info }
}
}
impl ApiInterface for MyApiInterface {
fn get_base_url(&self) -> String { "https://example.com".to_string() }
fn get_auth_info(&self, request: RequestBuilder) -> RequestBuilder {
request.basic_auth(self.username.clone(), Some(self.password.clone())
}
}
Then, create a type
that aliases ApiClient
with your interface in use. Additionally, create a new()
fn to
create the http client and initialize any part of your interface.
pub type MyApiClient = ApiClient<MyApiInterface>;
impl MyApiClient {
pub fn new(username: String, password: String) -> Self {
let interface = MyApiInterface::new(username, password);
let http_client = ClientWithMiddleware::new(Client::new());
Self { interface, http_client }
}
}
Then, use it...
impl MyApiClient {
pub async fn get_home(&self) -> Result<MyModel> {
self.simple_get("/home").await
}
}
Dependencies
~4–16MB
~201K SLoC