base-sensible-wrapper

Crates.iobase-sensible-wrapper
lib.rsbase-sensible-wrapper
version0.1.0
created_at2025-04-02 17:25:10.199126+00
updated_at2025-04-02 17:25:10.199126+00
descriptionA simple api wrapper with sane defaults
homepagehttps://github.com/MatrixSenpai/base-sensible-wrapper
repositoryhttps://github.com/MatrixSenpai/base-sensible-wrapper.git
max_upload_size
id1616854
size55,040
(MatrixSenpai)

documentation

README

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
    }
}
Commit count: 0

cargo fmt