use serde::{Deserialize, Serialize};
use std::fmt;
const DEFAULT_BASE_URL: &str = "https://namegender.com/api/v1";
#[derive(Debug, Clone, Default, Serialize)]
pub struct 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>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub best_guess: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub ai_fallback: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ValueType {
#[default]
Name,
Email,
Username,
}
#[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>,
pub gender: Option<String>,
pub country: Option<String>,
pub sample_size: u64,
pub probability: u8,
pub took_ms: u64,
pub source: String,
pub confidence: String,
pub matched_as: Option<String>,
}
#[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>,
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,
}
#[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,
}
#[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,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Account {
pub email: String,
pub credits_remaining: u64,
pub free_today: u64,
pub free_daily_limit: u64,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SalutationOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub language: Option<String>,
#[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>,
#[serde(skip_serializing_if = "Option::is_none")]
pub gender: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub min_probability: Option<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct SalutationLines {
pub formal: String,
pub informal: String,
pub neutral: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct SalutationParts {
pub opening: Option<String>,
pub courtesy: Option<String>,
pub academic: Option<String>,
pub name: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct SalutationResult {
pub query: String,
pub language: String,
pub form: String,
pub reason: Option<String>,
pub salutation: SalutationLines,
pub parts: SalutationParts,
pub gender: Option<String>,
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>,
}
#[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,
}
#[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>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct NameCheckOptions {
#[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>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct NameCheckSignal {
pub code: String,
pub severity: String,
pub part: Option<String>,
pub value: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct NameCheckEvidence {
pub first_name_status: Option<String>,
pub first_name_counted_records: u64,
}
#[derive(Debug, Clone, Deserialize)]
pub struct NameCheckResult {
pub query: String,
pub assessment: String,
pub score: u8,
pub signals: Vec<NameCheckSignal>,
pub first_name: Option<String>,
pub last_name: Option<String>,
pub name_type: String,
pub evidence: NameCheckEvidence,
}
#[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,
}
#[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>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct AgeOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub gender: Option<String>,
#[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>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct AgeRange {
pub low: u16,
pub high: u16,
}
#[derive(Debug, Clone, Deserialize)]
pub struct AgeResult {
pub name: String,
pub first_name: Option<String>,
pub gender: Option<String>,
pub age: Option<u16>,
pub age_range: Option<AgeRange>,
pub age_range_80: Option<AgeRange>,
pub birth_year: Option<u16>,
pub sample_size: u64,
pub births: u64,
pub country: String,
pub country_source: String,
pub source: Option<String>,
pub series: Option<String>,
pub reference_year: u16,
pub reason: Option<String>,
}
#[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
}
}
#[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 {
Api {
status: u16,
error: String,
message: String,
request_id: Option<String>,
},
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>,
}
#[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(),
}
}
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
}
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
}
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
}
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
}
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
}
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
}
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
}
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
}
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
}
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
}