Skip to main content

zero_bounce/api/
mod.rs

1pub mod bulk;
2pub mod inbox_placement;
3pub mod priority3;
4pub mod validation;
5
6use std::collections::HashMap;
7
8use chrono::{NaiveDate, Utc};
9
10pub use crate::ZeroBounce;
11use crate::utility::http_error::{parse_json_body_with_status, UNEXPECTED_JSON_SHAPE_MESSAGE};
12use crate::utility::structures::generic::{
13    FindEmailResponse, FindEmailResponseV2, DomainSearchResponseV2, DOMAIN_SEARCH_V2_FIELD_NAMES,
14};
15use crate::utility::{ZBError, ZBResult, ENDPOINT_EMAIL_FINDER};
16use crate::utility::structures::{ActivityData, ApiUsage};
17use crate::utility::structures::generic::ScoreEmailResponse;
18use crate::utility::{ENDPOINT_ACTIVITY_DATA, ENDPOINT_API_USAGE, ENDPOINT_CREDITS, ENDPOINT_SCORING};
19
20/// Builder for the `find_email_v2` API call.
21/// 
22/// # Example
23/// ```no_run
24/// use zero_bounce::ZeroBounce;
25/// use zero_bounce::utility::ZBResult;
26/// 
27/// # fn main() -> ZBResult<()> {
28/// let zb = ZeroBounce::new("your_api_key");
29/// let result = zb.find_email_v2()
30///     .first_name("John")
31///     .domain("example.com")
32///     .last_name("Doe")
33///     .call()?;
34/// # Ok(())
35/// # }
36/// ```
37pub struct FindEmailV2Builder<'a> {
38    client: &'a ZeroBounce,
39    first_name: Option<&'a str>,
40    domain: Option<&'a str>,
41    company_name: Option<&'a str>,
42    middle_name: Option<&'a str>,
43    last_name: Option<&'a str>,
44}
45
46/// Builder for the `domain_search_v2` API call.
47/// 
48/// # Example
49/// ```no_run
50/// use zero_bounce::ZeroBounce;
51/// use zero_bounce::utility::ZBResult;
52/// 
53/// # fn main() -> ZBResult<()> {
54/// let zb = ZeroBounce::new("your_api_key");
55/// let result = zb.domain_search_v2()
56///     .domain("example.com")
57///     .call()?;
58/// # Ok(())
59/// # }
60/// ```
61pub struct DomainSearchV2Builder<'a> {
62    client: &'a ZeroBounce,
63    domain: Option<&'a str>,
64    company_name: Option<&'a str>,
65}
66
67impl ZeroBounce {
68
69    /// The status and body of a 2xx answer to a GET, checked like
70    /// `generic_get_request`. When `message_only_is_failure` is set, a
71    /// message-only or empty object is an error. The response status is kept
72    /// so that a body of the wrong shape is reported with it.
73    pub(crate) fn get_request_with_status<'a>(
74        &'a self,
75        url: String,
76        mut query_args: HashMap<&'a str, &'a str>,
77        message_only_is_failure: bool,
78    ) -> ZBResult<(u16, String)> {
79        self.require_key()?;
80        query_args.insert("api_key", self.api_key.as_str());
81        let response = self
82            .client
83            .get(crate::parse_request_url(&url)?)
84            .query(&query_args)
85            .send()?;
86        self.read_api_response_with_status(response, message_only_is_failure)
87    }
88
89    /// `get_request_with_status` for a form POST.
90    pub(crate) fn form_post_request_with_status<'a>(
91        &'a self,
92        url: String,
93        mut form_args: HashMap<&'a str, &'a str>,
94    ) -> ZBResult<(u16, String)> {
95        self.require_key()?;
96        form_args.insert("api_key", self.api_key.as_str());
97        let response = self
98            .client
99            .post(crate::parse_request_url(&url)?)
100            .form(&form_args)
101            .send()?;
102        self.read_api_response_with_status(response, false)
103    }
104
105    /// `read_api_response` that also returns the status.
106    pub(crate) fn read_api_response_with_status(
107        &self,
108        response: reqwest::blocking::Response,
109        message_only_is_failure: bool,
110    ) -> ZBResult<(u16, String)> {
111        let (status, content_type, content) = Self::read_api_body(response)?;
112        crate::utility::http_error::ensure_json_api_body(status, &content_type, &content)
113            .map_err(|error| self.redact_error(error))?;
114        if message_only_is_failure {
115            crate::utility::http_error::reject_message_only_body(status, &content_type, &content)
116                .map_err(|error| self.redact_error(error))?;
117        }
118        Ok((status, content))
119    }
120
121    /// The `Credits` value of a 2xx body: an integer sent as a JSON string
122    /// (`"-1"`, `"12345"`, as the live API sends it) or as a JSON integer
123    /// (`{"Credits":2375323}`, zerobounce.net's own example). Anything else
124    /// (missing, `null`, `5.5`, `5.0`, `"abc"`, another JSON type, out of
125    /// `i64` range) is JSON of the wrong shape: a [`ZBError::ApiError`] with
126    /// the response status, like on every other call.
127    fn get_credits_from_body(status: u16, string_value: &str) -> ZBResult<i64> {
128        let body = parse_json_body_with_status::<serde_json::Value>(status, string_value)?;
129        match body.get("Credits") {
130            Some(serde_json::Value::String(credits)) => credits.parse::<i64>().ok(),
131            Some(serde_json::Value::Number(credits)) => credits.as_i64(),
132            _ => None,
133        }
134        .ok_or_else(|| ZBError::api(status, UNEXPECTED_JSON_SHAPE_MESSAGE))
135    }
136
137    #[cfg(test)]
138    fn get_credits_from_string(string_value: String) -> ZBResult<i64> {
139        Self::get_credits_from_body(200, &string_value)
140    }
141
142    pub fn get_credits(&self) -> ZBResult<i64> {
143        let query_args = HashMap::new();
144
145        let (status, response_content) = self.get_request_with_status(
146            self.url_provider.url_of(ENDPOINT_CREDITS), query_args, false
147        )?;
148
149        Self::get_credits_from_body(status, &response_content)
150    }
151
152    pub fn get_api_usage(&self, start_date: NaiveDate, end_date: NaiveDate) -> ZBResult<ApiUsage> {
153        let start_date_str = start_date.format("%F").to_string();
154        let end_date_str = end_date.format("%F").to_string();
155        let query_args = HashMap::from([
156            ("start_date", start_date_str.as_str()),
157            ("end_date", end_date_str.as_str()),
158        ]);
159
160        let (status, response_content) = self.get_request_with_status(
161            self.url_provider.url_of(ENDPOINT_API_USAGE), query_args, false
162        )?;
163
164        let api_usage = parse_json_body_with_status::<ApiUsage>(status, &response_content)?;
165        Ok(api_usage)
166    }
167
168    pub fn get_api_usage_overall(&self) -> ZBResult<ApiUsage> {
169        let start_date = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
170        let end_date = Utc::now().naive_local().date();
171        self.get_api_usage(start_date, end_date)
172    }
173
174    pub fn get_activity_data(&self, email: &str) -> ZBResult<ActivityData> {
175        let query_args = HashMap::from([
176            ("email", email),
177        ]);
178
179        let (status, response_content) = self.get_request_with_status(
180            self.url_provider.url_of(ENDPOINT_ACTIVITY_DATA), query_args, false
181        )?;
182
183        let activity_data = crate::utility::http_error::parse_unless_message_beside_nulls::<ActivityData>(
184            status, &response_content, &["found", "active_in_days"],
185        )?;
186        Ok(activity_data)
187    }
188
189    pub fn score_email(&self, email: &str) -> ZBResult<ScoreEmailResponse> {
190        let query_args = HashMap::from([("email", email)]);
191
192        let (status, response_content) = self.get_request_with_status(
193            self.url_provider.url_of(ENDPOINT_SCORING),
194            query_args,
195            false,
196        )?;
197
198        let score = crate::utility::http_error::parse_unless_message_beside_nulls::<ScoreEmailResponse>(
199            status, &response_content, &["email", "score"],
200        )?;
201        Ok(score)
202    }
203
204    pub fn score_email_post(&self, email: &str) -> ZBResult<ScoreEmailResponse> {
205        let form_args = HashMap::from([("email", email)]);
206
207        let (status, response_content) = self.form_post_request_with_status(
208            self.url_provider.url_of(ENDPOINT_SCORING),
209            form_args,
210        )?;
211
212        let score = crate::utility::http_error::parse_unless_message_beside_nulls::<ScoreEmailResponse>(
213            status, &response_content, &["email", "score"],
214        )?;
215        Ok(score)
216    }
217
218    /// Deprecated: Use `find_email_v2` instead.
219    /// 
220    /// This function is kept for backward compatibility but will be removed in a future version.
221    #[deprecated(
222        since = "1.2.0",
223        note = "Use `find_email_v2` instead. The new version supports both domain and company_name parameters."
224    )]
225    pub fn find_email(&self, domain: &str, first_name: &str, middle_name: &str, last_name: &str) -> ZBResult<FindEmailResponse> {
226        let mut query_args = HashMap::from([
227            ("domain", domain),
228        ]);
229        if !first_name.is_empty() {
230            query_args.insert("first_name", first_name);
231        }
232        if !middle_name.is_empty() {
233            query_args.insert("middle_name", middle_name);
234        }
235        if !last_name.is_empty() {
236            query_args.insert("last_name", last_name);
237        }
238
239        let (status, response_content) = self.get_request_with_status(
240            self.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args, true
241        )?;
242
243        let activity_data = parse_json_body_with_status::<FindEmailResponse>(status, &response_content)?;
244        Ok(activity_data)
245    }
246
247    /// Find an email address using either a domain or company name.
248    /// 
249    /// Returns a builder that allows you to set parameters using method chaining.
250    /// 
251    /// # Requirements
252    /// - Exactly one of `domain` or `company_name` must be provided (XOR requirement)
253    /// - `first_name` is optional; without it the API answers with the domain's
254    ///   address formats, the same as `domain_search_v2`
255    /// 
256    /// # Example
257    /// ```no_run
258    /// use zero_bounce::ZeroBounce;
259    /// use zero_bounce::utility::ZBResult;
260    /// 
261    /// # fn main() -> ZBResult<()> {
262    /// let zb = ZeroBounce::new("your_api_key");
263    /// // Using domain
264    /// let result = zb.find_email_v2()
265    ///     .first_name("John")
266    ///     .domain("example.com")
267    ///     .last_name("Doe")
268    ///     .call()?;
269    /// // Or using company name
270    /// let result = zb.find_email_v2()
271    ///     .first_name("John")
272    ///     .company_name("Example Inc")
273    ///     .last_name("Doe")
274    ///     .call()?;
275    /// # Ok(())
276    /// # }
277    /// ```
278    pub fn find_email_v2(&self) -> FindEmailV2Builder<'_> {
279        FindEmailV2Builder {
280            client: self,
281            first_name: None,
282            domain: None,
283            company_name: None,
284            middle_name: None,
285            last_name: None,
286        }
287    }
288
289    /// Deprecated: Use `domain_search_v2` instead.
290    /// 
291    /// This function is kept for backward compatibility but will be removed in a future version.
292    #[deprecated(
293        since = "1.2.0",
294        note = "Use `domain_search_v2` instead. The new version supports both domain and company_name parameters."
295    )]
296    #[allow(deprecated)] // This method uses deprecated find_email, which is expected
297    pub fn domain_search(&self, domain: &str) -> ZBResult<FindEmailResponse> {
298        self.find_email(domain, "", "", "")
299    }
300
301    /// Search for email formats using either a domain or company name.
302    /// 
303    /// Returns a builder that allows you to set parameters using method chaining.
304    /// 
305    /// # Requirements
306    /// Exactly one of `domain` or `company_name` must be provided (XOR requirement).
307    /// 
308    /// # Example
309    /// ```no_run
310    /// use zero_bounce::ZeroBounce;
311    /// use zero_bounce::utility::ZBResult;
312    /// 
313    /// # fn main() -> ZBResult<()> {
314    /// let zb = ZeroBounce::new("your_api_key");
315    /// // Using domain
316    /// let result = zb.domain_search_v2()
317    ///     .domain("example.com")
318    ///     .call()?;
319    /// // Or using company name
320    /// let result = zb.domain_search_v2()
321    ///     .company_name("Example Inc")
322    ///     .call()?;
323    /// # Ok(())
324    /// # }
325    /// ```
326    pub fn domain_search_v2(&self) -> DomainSearchV2Builder<'_> {
327        DomainSearchV2Builder {
328            client: self,
329            domain: None,
330            company_name: None,
331        }
332    }
333
334}
335
336impl<'a> FindEmailV2Builder<'a> {
337    /// Set the first name (optional).
338    pub fn first_name(mut self, name: &'a str) -> Self {
339        self.first_name = Some(name);
340        self
341    }
342
343    /// Set the domain name (exactly one of domain or company_name must be provided).
344    pub fn domain(mut self, domain: &'a str) -> Self {
345        self.domain = Some(domain);
346        self
347    }
348
349    /// Set the company name (exactly one of domain or company_name must be provided).
350    pub fn company_name(mut self, company: &'a str) -> Self {
351        self.company_name = Some(company);
352        self
353    }
354
355    /// Set the middle name (optional).
356    pub fn middle_name(mut self, name: &'a str) -> Self {
357        self.middle_name = Some(name);
358        self
359    }
360
361    /// Set the last name (optional).
362    pub fn last_name(mut self, name: &'a str) -> Self {
363        self.last_name = Some(name);
364        self
365    }
366
367    /// Execute the API call and return the result.
368    pub fn call(self) -> ZBResult<FindEmailResponseV2> {
369        // first_name is optional: /guessformat answers with the domain's formats
370        // when no name is given. Setting it to an empty string is still a mistake.
371        if let Some("") = self.first_name {
372            return Err(ZBError::explicit("first_name cannot be empty"));
373        }
374
375        // Validate XOR requirement: exactly one of domain or company_name must be provided
376        match (self.domain, self.company_name) {
377            (Some(d), None) => {
378                if d.is_empty() {
379                    return Err(ZBError::explicit("domain cannot be empty"));
380                }
381            }
382            (None, Some(c)) => {
383                if c.is_empty() {
384                    return Err(ZBError::explicit("company_name cannot be empty"));
385                }
386            }
387            (Some(_), Some(_)) => {
388                return Err(ZBError::explicit("exactly one of domain or company_name must be provided, not both"));
389            }
390            (None, None) => {
391                return Err(ZBError::explicit("either domain or company_name must be provided"));
392            }
393        }
394
395        let mut query_args = HashMap::new();
396
397        if let Some(first) = self.first_name {
398            query_args.insert("first_name", first);
399        }
400
401        if let Some(d) = self.domain {
402            query_args.insert("domain", d);
403        }
404
405        if let Some(c) = self.company_name {
406            query_args.insert("company_name", c);
407        }
408
409        if let Some(middle) = self.middle_name {
410            if !middle.is_empty() {
411                query_args.insert("middle_name", middle);
412            }
413        }
414
415        if let Some(last) = self.last_name {
416            if !last.is_empty() {
417                query_args.insert("last_name", last);
418            }
419        }
420
421        let (status, response_content) = self.client.get_request_with_status(
422            self.client.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args, true
423        )?;
424
425        // A message beside fields that are all missing or null (`{"detail":"x","email":null}`)
426        // is not a found address. `{"email":null}` with no message stays a result.
427        let body = parse_json_body_with_status::<serde_json::Value>(status, &response_content)?;
428        if let Some(object) = body.as_object() {
429            const NAMES: [&str; 6] = [
430                "email",
431                "domain",
432                "email_confidence",
433                "company_name",
434                "did_you_mean",
435                "failure_reason",
436            ];
437            if crate::utility::http_error::object_has_message_key(object)
438                && !crate::utility::http_error::object_has_non_null_named_field(object, &NAMES)
439            {
440                return Err(ZBError::api(status, UNEXPECTED_JSON_SHAPE_MESSAGE));
441            }
442        }
443        let find_email_response =
444            parse_json_body_with_status::<FindEmailResponseV2>(status, &response_content)?;
445        Ok(find_email_response)
446    }
447}
448
449impl<'a> DomainSearchV2Builder<'a> {
450    /// Set the domain name (exactly one of domain or company_name must be provided).
451    pub fn domain(mut self, domain: &'a str) -> Self {
452        self.domain = Some(domain);
453        self
454    }
455
456    /// Set the company name (exactly one of domain or company_name must be provided).
457    pub fn company_name(mut self, company: &'a str) -> Self {
458        self.company_name = Some(company);
459        self
460    }
461
462    /// Execute the API call and return the result.
463    pub fn call(self) -> ZBResult<DomainSearchResponseV2> {
464        // Validate XOR requirement: exactly one of domain or company_name must be provided
465        match (self.domain, self.company_name) {
466            (Some(d), None) => {
467                if d.is_empty() {
468                    return Err(ZBError::explicit("domain cannot be empty"));
469                }
470            }
471            (None, Some(c)) => {
472                if c.is_empty() {
473                    return Err(ZBError::explicit("company_name cannot be empty"));
474                }
475            }
476            (Some(_), Some(_)) => {
477                return Err(ZBError::explicit("exactly one of domain or company_name must be provided, not both"));
478            }
479            (None, None) => {
480                return Err(ZBError::explicit("either domain or company_name must be provided"));
481            }
482        }
483
484        let mut query_args = HashMap::new();
485
486        if let Some(d) = self.domain {
487            query_args.insert("domain", d);
488        }
489
490        if let Some(c) = self.company_name {
491            query_args.insert("company_name", c);
492        }
493
494        let (status, response_content) = self.client.get_request_with_status(
495            self.client.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args, true
496        )?;
497
498        // Every field of the result defaults, because the live API leaves out
499        // the ones that do not apply, so serde takes any object, `{}` and
500        // `{"message":"m","file_id":null}` included. An object that carries none
501        // of the struct's field names is not a domain search answer.
502        let body = parse_json_body_with_status::<serde_json::Value>(status, &response_content)?;
503        let object = body.as_object();
504        let named = object.is_some_and(|object| {
505            DOMAIN_SEARCH_V2_FIELD_NAMES
506                .iter()
507                .any(|name| object.contains_key(*name))
508        });
509        let real = object.is_some_and(|object| {
510            crate::utility::http_error::object_has_non_null_named_field(
511                object,
512                &DOMAIN_SEARCH_V2_FIELD_NAMES,
513            )
514        });
515        let message = object.is_some_and(crate::utility::http_error::object_has_message_key);
516        // `{"domain":null}` is a result. A message beside only null fields is not.
517        if !named || (message && !real) {
518            return Err(ZBError::api(status, UNEXPECTED_JSON_SHAPE_MESSAGE));
519        }
520        let domain_search_response =
521            parse_json_body_with_status::<DomainSearchResponseV2>(status, &response_content)?;
522        Ok(domain_search_response)
523    }
524}
525
526#[cfg(test)]
527mod tests {
528    use crate::utility::mock_constants::CREDITS_RESPONSE_OK;
529    use crate::utility::mock_constants::CREDITS_RESPONSE_NEGATIVE;
530
531    use super::*;
532
533    #[test]
534    fn test_credits_negative() {
535        let credits = ZeroBounce::get_credits_from_string(CREDITS_RESPONSE_NEGATIVE.to_string());
536        assert!(credits.is_ok());
537
538        let amount = credits.unwrap();
539        assert_eq!(amount, -1);
540    }
541
542    #[test]
543    fn test_credits_ok() {
544        let credits = ZeroBounce::get_credits_from_string(CREDITS_RESPONSE_OK.to_string());
545        assert!(credits.is_ok());
546
547        let amount = credits.unwrap();
548        assert_eq!(amount, 123456);
549    }
550
551}