namegender 0.4.0

Client for the NameGender API: gender from names, email addresses and usernames, with the probability and sample size behind each answer.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
//! Client for the [NameGender](https://namegender.com) API.
//!
//! ```no_run
//! use namegender::{NameGender, Options};
//!
//! # async fn run() -> Result<(), namegender::Error> {
//! let client = NameGender::new(std::env::var("NAMEGENDER_API_KEY").unwrap());
//! let result = client
//!     .name("Andrea", &Options { country: Some("IT".into()), ..Default::default() })
//!     .await?;
//! println!("{:?} {} {}", result.gender, result.probability, result.sample_size);
//! # Ok(())
//! # }
//! ```
//!
//! Every lookup costs one credit, unknown results included. Success is the
//! HTTP status; any other response is returned as [`Error::Api`] carrying the
//! API's reason code.

use serde::{Deserialize, Serialize};
use std::fmt;

const DEFAULT_BASE_URL: &str = "https://namegender.com/api/v1";

/// Options shared by the name, email, username and bulk lookups.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Options {
    /// ISO 3166-1 alpha-2 code. Andrea is male in Italy and female in Germany.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    /// Language tag such as `it-IT`; its region is the country when `country`
    /// is not sent. A tag without a region (`en`) sets none.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,
    /// End user IP address; its country is used when neither `country` nor a
    /// regional `locale` is sent. Not stored by the API.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip: Option<String>,
    /// Return the more likely gender even when the evidence is weak.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub best_guess: bool,
    /// Ask a language model when the dataset has no answer. Requires AI
    /// lookups to be enabled on the account.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub ai_fallback: bool,
}

/// How the values of a bulk request are read.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ValueType {
    #[default]
    Name,
    Email,
    Username,
}

/// One resolved value.
#[derive(Debug, Clone, Deserialize)]
pub struct GenderResult {
    pub query: String,
    pub name: Option<String>,
    pub first_name: Option<String>,
    pub middle_name: Option<String>,
    pub last_name: Option<String>,
    pub name_type: Option<String>,
    /// `"male"`, `"female"` or `None` when the API does not know.
    pub gender: Option<String>,
    pub country: Option<String>,
    /// How many real people the answer is based on; 0 when the source
    /// records proportions rather than counts.
    pub sample_size: u64,
    pub probability: u8,
    pub took_ms: u64,
    pub source: String,
    pub confidence: String,
    pub matched_as: Option<String>,
}

/// Response of a single lookup.
#[derive(Debug, Clone, Deserialize)]
pub struct GenderResponse {
    pub credits_charged: u64,
    pub credits_remaining: u64,
    pub data_version: Option<String>,
    pub request_id: Option<String>,
    /// Where the country came from: `"country"`, `"locale"`, `"ip"` or `None`.
    pub country_source: Option<String>,
    #[serde(flatten)]
    pub result: GenderResult,
}

impl std::ops::Deref for GenderResponse {
    type Target = GenderResult;
    fn deref(&self) -> &GenderResult {
        &self.result
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct BulkSummary {
    pub total: u64,
    pub identified: u64,
    pub unknown: u64,
    pub match_rate: f64,
}

/// Response of a bulk lookup; `results` is in the order the values were sent.
#[derive(Debug, Clone, Deserialize)]
pub struct BulkResponse {
    pub credits_charged: u64,
    pub credits_remaining: u64,
    pub data_version: Option<String>,
    pub request_id: Option<String>,
    pub country_source: Option<String>,
    pub took_ms: u64,
    pub summary: BulkSummary,
    pub results: Vec<GenderResult>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Registration {
    pub country: String,
    pub count: u64,
    pub share: f64,
    pub gender: Option<String>,
    pub probability: u8,
    pub source: String,
}

/// Which countries a name is recorded in. Not a country-of-origin or
/// ethnicity inference: show `basis["note"]` next to any percentage.
#[derive(Debug, Clone, Deserialize)]
pub struct CountriesResponse {
    pub credits_charged: u64,
    pub credits_remaining: u64,
    pub registrations: Vec<Registration>,
    pub attested_in: Vec<String>,
    pub basis: serde_json::Value,
}

/// Credit balance and account status. Costs no credit.
#[derive(Debug, Clone, Deserialize)]
pub struct Account {
    pub email: String,
    pub credits_remaining: u64,
    pub free_today: u64,
    pub free_daily_limit: u64,
}

/// Options for the salutation endpoints. Fields left as `None` are not sent.
#[derive(Debug, Clone, Default, Serialize)]
pub struct SalutationOptions {
    /// Language of the salutation: `en`, `en-US`, `en-GB`, `de`, `de-AT`,
    /// `de-CH`, `fr`, `es`, `it`, `pt`, `pt-PT`, `pt-BR`, `nl`, `tr`, `pl` or
    /// `ja`. Defaults to the language of `locale`, else the main language of
    /// the country, else English. Any other value is a 422 `invalid_input`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// Country hint for the gender lookup, as in [`Options`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip: Option<String>,
    /// A gender you already know: `male`, `female` or `neutral`. Overrides
    /// the lookup; `neutral` always gives the neutral form.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gender: Option<String>,
    /// Lowest probability (50-100) for a gendered salutation; the API
    /// default is 90. Below it the neutral form is used.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_probability: Option<u8>,
    /// Academic title kept in a separate field, such as `Dr.`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

/// The three ready lines. `neutral` is always the gender-free form.
#[derive(Debug, Clone, Deserialize)]
pub struct SalutationLines {
    pub formal: String,
    pub informal: String,
    pub neutral: String,
}

/// Pieces of the formal line, for building your own template.
#[derive(Debug, Clone, Deserialize)]
pub struct SalutationParts {
    pub opening: Option<String>,
    pub courtesy: Option<String>,
    pub academic: Option<String>,
    pub name: Option<String>,
}

/// The salutation for one name.
#[derive(Debug, Clone, Deserialize)]
pub struct SalutationResult {
    pub query: String,
    pub language: String,
    /// `"gendered"`, `"neutral"` or `"organization"`.
    pub form: String,
    /// Why the neutral form was used, such as `"gender_unknown"` or
    /// `"below_min_probability"`; `None` for the other forms.
    pub reason: Option<String>,
    pub salutation: SalutationLines,
    pub parts: SalutationParts,
    pub gender: Option<String>,
    /// `"lookup"`, `"input"`, `"title"` or `None`.
    pub gender_source: Option<String>,
    pub probability: Option<u8>,
    pub confidence: Option<String>,
    pub first_name: Option<String>,
    pub last_name: Option<String>,
    pub name_type: String,
    pub country: Option<String>,
}

/// Response of a single salutation.
#[derive(Debug, Clone, Deserialize)]
pub struct SalutationResponse {
    pub credits_charged: u64,
    pub credits_remaining: u64,
    pub data_version: Option<String>,
    pub request_id: Option<String>,
    pub country_source: Option<String>,
    #[serde(flatten)]
    pub result: SalutationResult,
}

impl std::ops::Deref for SalutationResponse {
    type Target = SalutationResult;
    fn deref(&self) -> &SalutationResult {
        &self.result
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct SalutationSummary {
    pub total: u64,
    pub gendered: u64,
    pub neutral: u64,
    pub organization: u64,
}

/// Response of a bulk salutation; `results` is in the order the names were
/// sent.
#[derive(Debug, Clone, Deserialize)]
pub struct SalutationBulkResponse {
    pub credits_charged: u64,
    pub credits_remaining: u64,
    pub data_version: Option<String>,
    pub request_id: Option<String>,
    pub country_source: Option<String>,
    pub took_ms: u64,
    pub language: String,
    pub summary: SalutationSummary,
    pub results: Vec<SalutationResult>,
}

/// Options for the name check endpoints. Fields left as `None` are not sent.
#[derive(Debug, Clone, Default, Serialize)]
pub struct NameCheckOptions {
    /// Country hint, as in [`Options`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip: Option<String>,
}

/// One reason behind an assessment.
#[derive(Debug, Clone, Deserialize)]
pub struct NameCheckSignal {
    /// Such as `"keyboard_pattern"`, `"placeholder"` or `"first_name_attested"`.
    pub code: String,
    /// `"high"`, `"medium"`, `"low"`, `"info"` or `"positive"`.
    pub severity: String,
    /// `"full"`, `"first_name"`, `"last_name"` or `None`.
    pub part: Option<String>,
    pub value: Option<String>,
}

/// What the database knows about the first name. Surnames are judged by
/// their shape only.
#[derive(Debug, Clone, Deserialize)]
pub struct NameCheckEvidence {
    /// `"counted"`, `"attested"`, `"not_found"` or `None`.
    pub first_name_status: Option<String>,
    pub first_name_counted_records: u64,
}

/// Whether one name looks like a real person's name. It never calls a name
/// fake: use it to flag records, not to reject people automatically.
#[derive(Debug, Clone, Deserialize)]
pub struct NameCheckResult {
    pub query: String,
    /// `"plausible"`, `"suspicious"` or `"implausible"`.
    pub assessment: String,
    /// 0-100.
    pub score: u8,
    pub signals: Vec<NameCheckSignal>,
    pub first_name: Option<String>,
    pub last_name: Option<String>,
    /// `"personal"`, `"organization"` or `"role"`.
    pub name_type: String,
    pub evidence: NameCheckEvidence,
}

/// Response of a single name check.
#[derive(Debug, Clone, Deserialize)]
pub struct NameCheckResponse {
    pub credits_charged: u64,
    pub credits_remaining: u64,
    pub data_version: Option<String>,
    pub request_id: Option<String>,
    pub country_source: Option<String>,
    #[serde(flatten)]
    pub result: NameCheckResult,
}

impl std::ops::Deref for NameCheckResponse {
    type Target = NameCheckResult;
    fn deref(&self) -> &NameCheckResult {
        &self.result
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct NameCheckSummary {
    pub total: u64,
    pub plausible: u64,
    pub suspicious: u64,
    pub implausible: u64,
}

/// Response of a bulk name check; `results` is in the order the names were
/// sent.
#[derive(Debug, Clone, Deserialize)]
pub struct NameCheckBulkResponse {
    pub credits_charged: u64,
    pub credits_remaining: u64,
    pub data_version: Option<String>,
    pub request_id: Option<String>,
    pub country_source: Option<String>,
    pub took_ms: u64,
    pub summary: NameCheckSummary,
    pub results: Vec<NameCheckResult>,
}

/// Options for the age endpoints. Fields left as `None` are not sent.
#[derive(Debug, Clone, Default, Serialize)]
pub struct AgeOptions {
    /// `male` or `female`: only that gender's records are counted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gender: Option<String>,
    /// Country hint, as in [`Options`]. With no hint at all US data is used.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip: Option<String>,
}

/// A range of ages in years, `low` to `high` inclusive.
#[derive(Debug, Clone, Deserialize)]
pub struct AgeRange {
    pub low: u16,
    pub high: u16,
}

/// The typical age of the people who carry a first name. It describes a
/// group, not a person: never use it for decisions about an individual.
#[derive(Debug, Clone, Deserialize)]
pub struct AgeResult {
    /// The name as sent.
    pub name: String,
    pub first_name: Option<String>,
    /// The gender the estimate was narrowed to, or `None` for both.
    pub gender: Option<String>,
    /// Median age; `None` when there is no estimate, with `reason` saying why.
    pub age: Option<u16>,
    /// The middle half of the people with the name.
    pub age_range: Option<AgeRange>,
    /// The middle 80% of the people with the name.
    pub age_range_80: Option<AgeRange>,
    /// Median birth year.
    pub birth_year: Option<u16>,
    /// Estimated living people the answer is based on.
    pub sample_size: u64,
    /// Recorded births with the name.
    pub births: u64,
    pub country: String,
    /// Where the country came from: `"country"`, `"locale"`, `"ip"` or
    /// `"default"` (no hint, US data used).
    pub country_source: String,
    /// Such as `"ssa"`; `None` for a country that is not covered.
    pub source: Option<String>,
    /// Years of birth records, such as `"1880-2024"`.
    pub series: Option<String>,
    /// The year ages are counted to.
    pub reference_year: u16,
    /// `"not_found"`, `"insufficient_data"` or `"country_not_covered"` when
    /// `age` is `None`. Not an error; `country_not_covered` costs no credit.
    pub reason: Option<String>,
}

/// Response of a single age estimate.
#[derive(Debug, Clone, Deserialize)]
pub struct AgeResponse {
    pub credits_charged: u64,
    pub credits_remaining: u64,
    pub request_id: Option<String>,
    #[serde(flatten)]
    pub result: AgeResult,
}

impl std::ops::Deref for AgeResponse {
    type Target = AgeResult;
    fn deref(&self) -> &AgeResult {
        &self.result
    }
}

/// Response of a bulk age estimate; `results` is in the order the names were
/// sent.
#[derive(Debug, Clone, Deserialize)]
pub struct AgeBulkResponse {
    pub credits_charged: u64,
    pub credits_remaining: u64,
    pub request_id: Option<String>,
    pub country_source: Option<String>,
    pub results: Vec<AgeResult>,
}

#[derive(Debug)]
pub enum Error {
    /// The API answered with a non-2xx status. `error` is the reason code to
    /// branch on, such as `no_credits` or `invalid_key`.
    Api {
        status: u16,
        error: String,
        message: String,
        request_id: Option<String>,
    },
    /// The request did not complete, or the response could not be read.
    Http(reqwest::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Api {
                status,
                error,
                message,
                ..
            } => write!(f, "{message} ({error}, HTTP {status})"),
            Error::Http(e) => write!(f, "{e}"),
        }
    }
}

impl std::error::Error for Error {}

impl From<reqwest::Error> for Error {
    fn from(e: reqwest::Error) -> Self {
        Error::Http(e)
    }
}

#[derive(Deserialize)]
struct ErrorBody {
    error: String,
    #[serde(default)]
    message: String,
    request_id: Option<String>,
}

/// The API client. Cheap to clone; reuse one per process.
#[derive(Debug, Clone)]
pub struct NameGender {
    api_key: String,
    base_url: String,
    http: reqwest::Client,
}

impl NameGender {
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            base_url: DEFAULT_BASE_URL.to_string(),
            http: reqwest::Client::new(),
        }
    }

    /// Point the client at another base URL, for example a test server.
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = base_url.into().trim_end_matches('/').to_string();
        self
    }

    pub async fn name(&self, name: &str, options: &Options) -> Result<GenderResponse, Error> {
        self.post("/gender", &with_field("name", name, options))
            .await
    }

    pub async fn email(&self, email: &str, options: &Options) -> Result<GenderResponse, Error> {
        self.post("/gender/email", &with_field("email", email, options))
            .await
    }

    pub async fn username(
        &self,
        username: &str,
        options: &Options,
    ) -> Result<GenderResponse, Error> {
        self.post(
            "/gender/username",
            &with_field("username", username, options),
        )
        .await
    }

    /// Up to 100 values in one request, one credit each.
    pub async fn bulk<S: AsRef<str>>(
        &self,
        values: &[S],
        value_type: ValueType,
        options: &Options,
    ) -> Result<BulkResponse, Error> {
        let mut body = serde_json::to_value(options).expect("options serialize");
        body["names"] = values.iter().map(|v| v.as_ref()).collect::<Vec<_>>().into();
        body["type"] = serde_json::to_value(value_type).expect("type serializes");
        self.post("/gender/bulk", &body).await
    }

    pub async fn countries(&self, name: &str, limit: u8) -> Result<CountriesResponse, Error> {
        self.post(
            "/gender/countries",
            &serde_json::json!({ "name": name, "limit": limit.clamp(1, 100) }),
        )
        .await
    }

    /// The letter salutation for a full name, titles included
    /// (`Dr. Anna Müller`). One credit. The form is neutral when the gender
    /// is not certain; `form` and `reason` say why.
    pub async fn salutation(
        &self,
        name: &str,
        options: &SalutationOptions,
    ) -> Result<SalutationResponse, Error> {
        let mut body = serde_json::to_value(options).expect("options serialize");
        body["name"] = name.into();
        self.post("/salutation", &body).await
    }

    /// Like [`salutation`](Self::salutation) for a first and last name stored
    /// separately; they are not parsed. An empty string is not sent.
    pub async fn salutation_by_parts(
        &self,
        first_name: &str,
        last_name: &str,
        options: &SalutationOptions,
    ) -> Result<SalutationResponse, Error> {
        let mut body = serde_json::to_value(options).expect("options serialize");
        for (field, value) in [("first_name", first_name), ("last_name", last_name)] {
            if !value.is_empty() {
                body[field] = value.into();
            }
        }
        self.post("/salutation", &body).await
    }

    /// Salutations for up to 100 names in one request, one credit each.
    pub async fn salutation_bulk<S: AsRef<str>>(
        &self,
        names: &[S],
        options: &SalutationOptions,
    ) -> Result<SalutationBulkResponse, Error> {
        let mut body = serde_json::to_value(options).expect("options serialize");
        body["names"] = names.iter().map(|n| n.as_ref()).collect::<Vec<_>>().into();
        self.post("/salutation/bulk", &body).await
    }

    /// Whether a name typed into a form looks like a real person's name,
    /// with the reasons. One credit. It never calls a name fake: use it to
    /// flag records, not to reject people automatically.
    pub async fn name_check(
        &self,
        name: &str,
        options: &NameCheckOptions,
    ) -> Result<NameCheckResponse, Error> {
        let mut body = serde_json::to_value(options).expect("options serialize");
        body["name"] = name.into();
        self.post("/name-check", &body).await
    }

    /// Like [`name_check`](Self::name_check) for a first and last name stored
    /// separately; they are not parsed. An empty string is not sent.
    pub async fn name_check_by_parts(
        &self,
        first_name: &str,
        last_name: &str,
        options: &NameCheckOptions,
    ) -> Result<NameCheckResponse, Error> {
        let mut body = serde_json::to_value(options).expect("options serialize");
        for (field, value) in [("first_name", first_name), ("last_name", last_name)] {
            if !value.is_empty() {
                body[field] = value.into();
            }
        }
        self.post("/name-check", &body).await
    }

    /// Checks up to 100 names in one request, one credit each.
    pub async fn name_check_bulk<S: AsRef<str>>(
        &self,
        names: &[S],
        options: &NameCheckOptions,
    ) -> Result<NameCheckBulkResponse, Error> {
        let mut body = serde_json::to_value(options).expect("options serialize");
        body["names"] = names.iter().map(|n| n.as_ref()).collect::<Vec<_>>().into();
        self.post("/name-check/bulk", &body).await
    }

    /// The typical age of the people who carry a first name: median `age`,
    /// `age_range` (middle half) and `age_range_80`. One credit; a country
    /// that is not covered (only the US, France and Norway are) costs none
    /// and comes back with `age` `None` and a `reason`, not as an error.
    pub async fn age(&self, name: &str, options: &AgeOptions) -> Result<AgeResponse, Error> {
        let mut body = serde_json::to_value(options).expect("options serialize");
        body["name"] = name.into();
        self.post("/age", &body).await
    }

    /// Age estimates for up to 100 names in one request, one credit each.
    pub async fn age_bulk<S: AsRef<str>>(
        &self,
        names: &[S],
        options: &AgeOptions,
    ) -> Result<AgeBulkResponse, Error> {
        let mut body = serde_json::to_value(options).expect("options serialize");
        body["names"] = names.iter().map(|n| n.as_ref()).collect::<Vec<_>>().into();
        self.post("/age/bulk", &body).await
    }

    pub async fn account(&self) -> Result<Account, Error> {
        let request = self.http.get(format!("{}/me", self.base_url));
        self.send(request).await
    }

    async fn post<T: for<'de> Deserialize<'de>>(
        &self,
        path: &str,
        body: &serde_json::Value,
    ) -> Result<T, Error> {
        let request = self
            .http
            .post(format!("{}{}", self.base_url, path))
            .json(body);
        self.send(request).await
    }

    async fn send<T: for<'de> Deserialize<'de>>(
        &self,
        request: reqwest::RequestBuilder,
    ) -> Result<T, Error> {
        let response = request
            .bearer_auth(&self.api_key)
            .header(reqwest::header::ACCEPT, "application/json")
            .send()
            .await?;

        let status = response.status();
        if status.is_success() {
            return Ok(response.json::<T>().await?);
        }

        let text = response.text().await.unwrap_or_default();
        let body: Option<ErrorBody> = serde_json::from_str(&text).ok();
        Err(match body {
            Some(b) => Error::Api {
                status: status.as_u16(),
                message: if b.message.is_empty() {
                    format!("HTTP {}", status.as_u16())
                } else {
                    b.message
                },
                error: b.error,
                request_id: b.request_id,
            },
            None => Error::Api {
                status: status.as_u16(),
                error: "http_error".into(),
                message: format!("HTTP {}", status.as_u16()),
                request_id: None,
            },
        })
    }
}

fn with_field(field: &str, value: &str, options: &Options) -> serde_json::Value {
    let mut body = serde_json::to_value(options).expect("options serialize");
    body[field] = value.into();
    body
}