Skip to main content

wi_api/
lib.rs

1//! Official Rust SDK for the [wi-api](https://wi.api.br) WhatsApp platform.
2//!
3//! # Quick start
4//!
5//! ```rust,no_run
6//! use wi_api::{Wi, types::SendTextParams};
7//!
8//! #[tokio::main]
9//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
10//!     let wi = Wi::new("YOUR_API_KEY");
11//!     let session = wi.session("my-instance");
12//!
13//!     let msg = session.send_text(SendTextParams {
14//!         to: "5511999999999".into(),
15//!         text: "Hello from wi-api".into(),
16//!         ..Default::default()
17//!     }).await?;
18//!
19//!     println!("sent: {}", msg.message_id);
20//!     Ok(())
21//! }
22//! ```
23
24pub mod error;
25pub mod session;
26pub mod types;
27pub mod webhook;
28
29pub use error::WiError;
30pub use session::Session;
31
32use std::sync::Arc;
33use std::time::Duration;
34
35const DEFAULT_BASE_URL: &str = "https://endpoint.wi.api.br";
36
37/// The wi-api client. Create with [`Wi::new`] or [`Wi::builder`].
38#[derive(Clone)]
39pub struct Wi {
40    http: Arc<reqwest::Client>,
41    base_url: Arc<String>,
42    api_key: Arc<String>,
43}
44
45impl Wi {
46    /// Create a client with the given API key and default settings.
47    pub fn new(api_key: impl Into<String>) -> Self {
48        Self::builder(api_key).build()
49    }
50
51    /// Create a [`WiBuilder`] for custom configuration.
52    pub fn builder(api_key: impl Into<String>) -> WiBuilder {
53        WiBuilder {
54            api_key: api_key.into(),
55            base_url: DEFAULT_BASE_URL.to_string(),
56            timeout: Duration::from_secs(30),
57        }
58    }
59
60    /// Return a [`Session`] scoped to the given session ID.
61    pub fn session(&self, id: impl Into<String>) -> Session {
62        Session {
63            id: id.into(),
64            http: self.http.clone(),
65            base_url: self.base_url.clone(),
66            api_key: self.api_key.clone(),
67        }
68    }
69}
70
71/// Builder for [`Wi`].
72pub struct WiBuilder {
73    api_key: String,
74    base_url: String,
75    timeout: Duration,
76}
77
78impl WiBuilder {
79    /// Override the API base URL. Default: `https://endpoint.wi.api.br`.
80    pub fn base_url(mut self, url: impl Into<String>) -> Self {
81        self.base_url = url.into().trim_end_matches('/').to_string();
82        self
83    }
84
85    /// Set the per-request timeout. Default: 30s.
86    pub fn timeout(mut self, d: Duration) -> Self {
87        self.timeout = d;
88        self
89    }
90
91    pub fn build(self) -> Wi {
92        let http = reqwest::Client::builder()
93            .timeout(self.timeout)
94            .build()
95            .expect("failed to build HTTP client");
96
97        Wi {
98            http: Arc::new(http),
99            base_url: Arc::new(self.base_url),
100            api_key: Arc::new(self.api_key),
101        }
102    }
103}